blob: c3055ae482d17dc56b3445df33eb82f701977041 [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 Lattnerbcd7db52005-08-02 19:16:58 +000055#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000057#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000058#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000059#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000060#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000061#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000062#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000063#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000064#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000065#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000066using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000067using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000068
Chris Lattner0e5f4992006-12-19 21:40:18 +000069STATISTIC(NumCombined , "Number of insts combined");
70STATISTIC(NumConstProp, "Number of constant folds");
71STATISTIC(NumDeadInst , "Number of dead inst eliminated");
72STATISTIC(NumDeadStore, "Number of dead stores eliminated");
73STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000074
Chris Lattner0e5f4992006-12-19 21:40:18 +000075namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000076 class VISIBILITY_HIDDEN InstCombiner
77 : public FunctionPass,
78 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000079 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000080 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000082 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000083 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000085 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000086 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000087
Owen Andersone922c022009-07-22 00:24:57 +000088 LLVMContext *Context;
89 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000090
Chris Lattnerdbab3862007-03-02 21:28:56 +000091 /// AddToWorkList - Add the specified instruction to the worklist if it
92 /// isn't already in it.
93 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000095 Worklist.push_back(I);
96 }
97
98 // RemoveFromWorkList - remove I from the worklist if it exists.
99 void RemoveFromWorkList(Instruction *I) {
100 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
101 if (It == WorklistMap.end()) return; // Not in worklist.
102
103 // Don't bother moving everything down, just null out the slot.
104 Worklist[It->second] = 0;
105
106 WorklistMap.erase(It);
107 }
108
109 Instruction *RemoveOneFromWorkList() {
110 Instruction *I = Worklist.back();
111 Worklist.pop_back();
112 WorklistMap.erase(I);
113 return I;
114 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115
Chris Lattnerdbab3862007-03-02 21:28:56 +0000116
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000117 /// AddUsersToWorkList - When an instruction is simplified, add all users of
118 /// the instruction to the work lists because they might get more simplified
119 /// now.
120 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000121 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000122 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000123 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000124 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000125 }
126
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 /// AddUsesToWorkList - When an instruction is simplified, add operands to
128 /// the work lists because they might get more simplified now.
129 ///
130 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000131 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
132 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000133 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000134 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000135
136 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
137 /// dead. Add all of its operands to the worklist, turning them into
138 /// undef's to reduce the number of uses of those instructions.
139 ///
140 /// Return the specified operand before it is turned into an undef.
141 ///
142 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
143 Value *R = I.getOperand(op);
144
Gabor Greif177dd3f2008-06-12 21:37:33 +0000145 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
146 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000147 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000148 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000149 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000150 }
151
152 return R;
153 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000154
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000155 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000156 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000157
158 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000159
Chris Lattner97e52e42002-04-28 21:27:06 +0000160 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000161 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000162 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000163 }
164
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000165 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000166
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // Visitation implementation - Implement instruction combining for different
168 // instruction types. The semantics are as follows:
169 // Return Value:
170 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000171 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000172 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000173 //
Chris Lattner7e708292002-06-25 16:13:24 +0000174 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000175 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000176 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000177 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000178 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000179 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000180 Instruction *visitURem(BinaryOperator &I);
181 Instruction *visitSRem(BinaryOperator &I);
182 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000183 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000184 Instruction *commonRemTransforms(BinaryOperator &I);
185 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000186 Instruction *commonDivTransforms(BinaryOperator &I);
187 Instruction *commonIDivTransforms(BinaryOperator &I);
188 Instruction *visitUDiv(BinaryOperator &I);
189 Instruction *visitSDiv(BinaryOperator &I);
190 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000191 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000192 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000193 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000194 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000195 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000196 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000197 Instruction *visitOr (BinaryOperator &I);
198 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000199 Instruction *visitShl(BinaryOperator &I);
200 Instruction *visitAShr(BinaryOperator &I);
201 Instruction *visitLShr(BinaryOperator &I);
202 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000203 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
204 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000205 Instruction *visitFCmpInst(FCmpInst &I);
206 Instruction *visitICmpInst(ICmpInst &I);
207 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000208 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
209 Instruction *LHS,
210 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000211 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
212 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000213
Reid Spencere4d87aa2006-12-23 06:05:41 +0000214 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
215 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000216 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000217 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000218 Instruction *commonCastTransforms(CastInst &CI);
219 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000220 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000221 Instruction *visitTrunc(TruncInst &CI);
222 Instruction *visitZExt(ZExtInst &CI);
223 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000224 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000225 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000226 Instruction *visitFPToUI(FPToUIInst &FI);
227 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000228 Instruction *visitUIToFP(CastInst &CI);
229 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000230 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000231 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000232 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000233 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
234 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000235 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000236 Instruction *visitSelectInst(SelectInst &SI);
237 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 Instruction *visitCallInst(CallInst &CI);
239 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000240 Instruction *visitPHINode(PHINode &PN);
241 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000242 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000243 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000244 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000245 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000246 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000247 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000248 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000249 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000250 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000251 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000252
253 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000254 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000255
Chris Lattner9fe38862003-06-19 17:00:31 +0000256 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000257 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000258 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000259 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000260 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
261 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000262 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000263 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
264
Chris Lattner9fe38862003-06-19 17:00:31 +0000265
Chris Lattner28977af2004-04-05 01:30:19 +0000266 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000267 // InsertNewInstBefore - insert an instruction New before instruction Old
268 // in the program. Add the new instruction to the worklist.
269 //
Chris Lattner955f3312004-09-28 21:48:02 +0000270 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000271 assert(New && New->getParent() == 0 &&
272 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000273 BasicBlock *BB = Old.getParent();
274 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000275 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000276 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000277 }
278
Chris Lattner0c967662004-09-24 15:21:34 +0000279 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
280 /// This also adds the cast to the worklist. Finally, this returns the
281 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000282 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
283 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000284 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000285
Chris Lattnere2ed0572006-04-06 19:19:17 +0000286 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000287 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000288
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000289 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000290 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000291 return C;
292 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000293
294 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
295 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
296 }
297
Chris Lattner0c967662004-09-24 15:21:34 +0000298
Chris Lattner8b170942002-08-09 23:47:40 +0000299 // ReplaceInstUsesWith - This method is to be used when an instruction is
300 // found to be dead, replacable with another preexisting expression. Here
301 // we add all uses of I to the worklist, replace all uses of I with the new
302 // value, then return I, so that the inst combiner will know that I was
303 // modified.
304 //
305 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000306 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000307 if (&I != V) {
308 I.replaceAllUsesWith(V);
309 return &I;
310 } else {
311 // If we are replacing the instruction with itself, this must be in a
312 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000313 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000314 return &I;
315 }
Chris Lattner8b170942002-08-09 23:47:40 +0000316 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000317
318 // EraseInstFromFunction - When dealing with an instruction that has side
319 // effects or produces a void value, we can't rely on DCE to delete the
320 // instruction. Instead, visit methods should return the value returned by
321 // this function.
322 Instruction *EraseInstFromFunction(Instruction &I) {
323 assert(I.use_empty() && "Cannot erase instruction that is used!");
324 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000325 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000326 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000327 return 0; // Don't do anything with FI
328 }
Chris Lattner173234a2008-06-02 01:18:21 +0000329
330 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331 APInt &KnownOne, unsigned Depth = 0) const {
332 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
333 }
334
335 bool MaskedValueIsZero(Value *V, const APInt &Mask,
336 unsigned Depth = 0) const {
337 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338 }
339 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340 return llvm::ComputeNumSignBits(Op, TD, Depth);
341 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000342
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000343 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000344
Reid Spencere4d87aa2006-12-23 06:05:41 +0000345 /// SimplifyCommutative - This performs a few simplifications for
346 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000347 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000348
Reid Spencere4d87aa2006-12-23 06:05:41 +0000349 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
350 /// most-complex to least-complex order.
351 bool SimplifyCompare(CmpInst &I);
352
Chris Lattner886ab6c2009-01-31 08:15:18 +0000353 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
354 /// based on the demanded bits.
355 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
356 APInt& KnownZero, APInt& KnownOne,
357 unsigned Depth);
358 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000359 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000360 unsigned Depth=0);
361
362 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
363 /// SimplifyDemandedBits knows about. See if the instruction has any
364 /// properties that allow us to simplify its operands.
365 bool SimplifyDemandedInstructionBits(Instruction &Inst);
366
Evan Cheng388df622009-02-03 10:05:09 +0000367 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
368 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000369
Chris Lattner4e998b22004-09-29 05:07:12 +0000370 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
371 // PHI node as operand #0, see if we can fold the instruction into the PHI
372 // (which is only possible if all operands to the PHI are constants).
373 Instruction *FoldOpIntoPhi(Instruction &I);
374
Chris Lattnerbac32862004-11-14 19:13:23 +0000375 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
376 // operator and they all are only used by the PHI, PHI together their
377 // inputs, and do the operation once, to the result of the PHI.
378 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000379 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000380 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
381
Chris Lattner7da52b22006-11-01 04:51:18 +0000382
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000383 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
384 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000385
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000386 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000387 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000388 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000389 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000390 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000391 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000392 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000393 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000394 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000395
Chris Lattnerafe91a52006-06-15 19:07:26 +0000396
Reid Spencerc55b2432006-12-13 18:21:21 +0000397 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000398
Dan Gohman6de29f82009-06-15 22:12:54 +0000399 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000400 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000401 unsigned GetOrEnforceKnownAlignment(Value *V,
402 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000403
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000404 };
405}
406
Dan Gohman844731a2008-05-13 00:00:25 +0000407char InstCombiner::ID = 0;
408static RegisterPass<InstCombiner>
409X("instcombine", "Combine redundant instructions");
410
Chris Lattner4f98c562003-03-10 21:43:22 +0000411// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000412// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000413static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000414 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000415 if (BinaryOperator::isNeg(V) ||
416 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000417 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000418 return 3;
419 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000420 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000421 if (isa<Argument>(V)) return 3;
422 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000423}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000424
Chris Lattnerc8802d22003-03-11 00:12:48 +0000425// isOnlyUse - Return true if this instruction will be deleted if we stop using
426// it.
427static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000428 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000429}
430
Chris Lattner4cb170c2004-02-23 06:38:22 +0000431// getPromotedType - Return the specified type promoted as it would be to pass
432// though a va_arg area...
433static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000434 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
435 if (ITy->getBitWidth() < 32)
436 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000437 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000438 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000439}
440
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000441/// getBitCastOperand - If the specified operand is a CastInst, a constant
442/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
443/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000444static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000445 if (Operator *O = dyn_cast<Operator>(V)) {
446 if (O->getOpcode() == Instruction::BitCast)
447 return O->getOperand(0);
448 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
449 if (GEP->hasAllZeroIndices())
450 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000451 }
Chris Lattnereed48272005-09-13 00:40:14 +0000452 return 0;
453}
454
Reid Spencer3da59db2006-11-27 01:05:10 +0000455/// This function is a wrapper around CastInst::isEliminableCastPair. It
456/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000457static Instruction::CastOps
458isEliminableCastPair(
459 const CastInst *CI, ///< The first cast instruction
460 unsigned opcode, ///< The opcode of the second cast instruction
461 const Type *DstTy, ///< The target type for the second cast instruction
462 TargetData *TD ///< The target data for pointer size
463) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000464
Reid Spencer3da59db2006-11-27 01:05:10 +0000465 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
466 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000467
Reid Spencer3da59db2006-11-27 01:05:10 +0000468 // Get the opcodes of the two Cast instructions
469 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
470 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000471
Chris Lattnera0e69692009-03-24 18:35:40 +0000472 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000473 DstTy,
474 TD ? TD->getIntPtrType() : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000475
476 // We don't want to form an inttoptr or ptrtoint that converts to an integer
477 // type that differs from the pointer size.
478 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
479 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
480 Res = 0;
481
482 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000483}
484
485/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
486/// in any code being generated. It does not require codegen if V is simple
487/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000488static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
489 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000490 if (V->getType() == Ty || isa<Constant>(V)) return false;
491
Chris Lattner01575b72006-05-25 23:24:33 +0000492 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000493 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000494 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000495 return false;
496 return true;
497}
498
Chris Lattner4f98c562003-03-10 21:43:22 +0000499// SimplifyCommutative - This performs a few simplifications for commutative
500// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000501//
Chris Lattner4f98c562003-03-10 21:43:22 +0000502// 1. Order operands such that they are listed from right (least complex) to
503// left (most complex). This puts constants before unary operators before
504// binary operators.
505//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000508//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000509bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000510 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000511 if (getComplexity(Context, I.getOperand(0)) <
512 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000513 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000514
Chris Lattner4f98c562003-03-10 21:43:22 +0000515 if (!I.isAssociative()) return Changed;
516 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
518 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
519 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000520 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000521 cast<Constant>(I.getOperand(1)),
522 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000523 I.setOperand(0, Op->getOperand(0));
524 I.setOperand(1, Folded);
525 return true;
526 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
527 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
528 isOnlyUse(Op) && isOnlyUse(Op1)) {
529 Constant *C1 = cast<Constant>(Op->getOperand(1));
530 Constant *C2 = cast<Constant>(Op1->getOperand(1));
531
532 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000533 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000534 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000535 Op1->getOperand(0),
536 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000537 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538 I.setOperand(0, New);
539 I.setOperand(1, Folded);
540 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000541 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000542 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000543 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000544}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000545
Reid Spencere4d87aa2006-12-23 06:05:41 +0000546/// SimplifyCompare - For a CmpInst this function just orders the operands
547/// so that theyare listed from right (least complex) to left (most complex).
548/// This puts constants before unary operators before binary operators.
549bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000550 if (getComplexity(Context, I.getOperand(0)) >=
551 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000552 return false;
553 I.swapOperands();
554 // Compare instructions are not associative so there's nothing else we can do.
555 return true;
556}
557
Chris Lattner8d969642003-03-10 23:06:50 +0000558// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
559// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000560//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000561static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000562 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000563 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000564
Chris Lattner0ce85802004-12-14 20:08:06 +0000565 // Constants can be considered to be negated values if they can be folded.
566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000567 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000568
569 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
570 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000571 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000572
Chris Lattner8d969642003-03-10 23:06:50 +0000573 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000574}
575
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000576// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
577// instruction if the LHS is a constant negative zero (which is the 'negate'
578// form).
579//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000580static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000581 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000582 return BinaryOperator::getFNegArgument(V);
583
584 // Constants can be considered to be negated values if they can be folded.
585 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000586 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000587
588 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
589 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000590 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000591
592 return 0;
593}
594
Owen Anderson07cf79e2009-07-06 23:00:19 +0000595static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000596 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000597 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000598
599 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000600 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000601 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000602 return 0;
603}
604
Chris Lattnerc8802d22003-03-11 00:12:48 +0000605// dyn_castFoldableMul - If this value is a multiply that can be folded into
606// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000607// non-constant operand of the multiply, and set CST to point to the multiplier.
608// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000609//
Owen Andersond672ecb2009-07-03 00:17:18 +0000610static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000611 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000612 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000613 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000614 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000615 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000617 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000618 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000619 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000620 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000621 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000622 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000623 return I->getOperand(0);
624 }
625 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000626 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000627}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000628
Chris Lattner574da9b2005-01-13 20:14:25 +0000629/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
630/// expression, return it.
631static User *dyn_castGetElementPtr(Value *V) {
632 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
633 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
634 if (CE->getOpcode() == Instruction::GetElementPtr)
635 return cast<User>(V);
636 return false;
637}
638
Reid Spencer7177c3a2007-03-25 05:33:51 +0000639/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000640static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000641 return Context->getConstantExprAdd(C,
642 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000643}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000644/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000645static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000646 return Context->getConstantExprSub(C,
647 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000648}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000649/// MultiplyOverflows - True if the multiply can not be expressed in an int
650/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000651static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000652 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000653 uint32_t W = C1->getBitWidth();
654 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
655 if (sign) {
656 LHSExt.sext(W * 2);
657 RHSExt.sext(W * 2);
658 } else {
659 LHSExt.zext(W * 2);
660 RHSExt.zext(W * 2);
661 }
662
663 APInt MulExt = LHSExt * RHSExt;
664
665 if (sign) {
666 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
667 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
668 return MulExt.slt(Min) || MulExt.sgt(Max);
669 } else
670 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
671}
Chris Lattner955f3312004-09-28 21:48:02 +0000672
Reid Spencere7816b52007-03-08 01:52:58 +0000673
Chris Lattner255d8912006-02-11 09:31:47 +0000674/// ShrinkDemandedConstant - Check to see if the specified operand of the
675/// specified instruction is a constant integer. If so, check to see if there
676/// are any bits set in the constant that are not demanded. If so, shrink the
677/// constant and return true.
678static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000679 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000680 assert(I && "No instruction?");
681 assert(OpNo < I->getNumOperands() && "Operand index too large");
682
683 // If the operand is not a constant integer, nothing to do.
684 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
685 if (!OpC) return false;
686
687 // If there are no bits set that aren't demanded, nothing to do.
688 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
689 if ((~Demanded & OpC->getValue()) == 0)
690 return false;
691
692 // This instruction is producing bits that are not demanded. Shrink the RHS.
693 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000694 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000695 return true;
696}
697
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000698// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
699// set of known zero and one bits, compute the maximum and minimum values that
700// could have the specified known zero and known one bits, returning them in
701// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000702static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000705 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
706 KnownZero.getBitWidth() == Min.getBitWidth() &&
707 KnownZero.getBitWidth() == Max.getBitWidth() &&
708 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000709 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000710
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
712 // bit if it is unknown.
713 Min = KnownOne;
714 Max = KnownOne|UnknownBits;
715
Dan Gohman1c8491e2009-04-25 17:12:48 +0000716 if (UnknownBits.isNegative()) { // Sign bit is unknown
717 Min.set(Min.getBitWidth()-1);
718 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000719 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720}
721
722// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
723// a set of known zero and one bits, compute the maximum and minimum values that
724// could have the specified known zero and known one bits, returning them in
725// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000726static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000727 const APInt &KnownOne,
728 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000729 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
730 KnownZero.getBitWidth() == Min.getBitWidth() &&
731 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000732 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000733 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000734
735 // The minimum value is when the unknown bits are all zeros.
736 Min = KnownOne;
737 // The maximum value is when the unknown bits are all ones.
738 Max = KnownOne|UnknownBits;
739}
Chris Lattner255d8912006-02-11 09:31:47 +0000740
Chris Lattner886ab6c2009-01-31 08:15:18 +0000741/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
742/// SimplifyDemandedBits knows about. See if the instruction has any
743/// properties that allow us to simplify its operands.
744bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000745 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000746 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
747 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
748
749 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
750 KnownZero, KnownOne, 0);
751 if (V == 0) return false;
752 if (V == &Inst) return true;
753 ReplaceInstUsesWith(Inst, V);
754 return true;
755}
756
757/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
758/// specified instruction operand if possible, updating it in place. It returns
759/// true if it made any change and false otherwise.
760bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
761 APInt &KnownZero, APInt &KnownOne,
762 unsigned Depth) {
763 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
764 KnownZero, KnownOne, Depth);
765 if (NewVal == 0) return false;
766 U.set(NewVal);
767 return true;
768}
769
770
771/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
772/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000773/// that only the bits set in DemandedMask of the result of V are ever used
774/// downstream. Consequently, depending on the mask and V, it may be possible
775/// to replace V with a constant or one of its operands. In such cases, this
776/// function does the replacement and returns true. In all other cases, it
777/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000778/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000779/// to be zero in the expression. These are provided to potentially allow the
780/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
781/// the expression. KnownOne and KnownZero always follow the invariant that
782/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
783/// the bits in KnownOne and KnownZero may only be accurate for those bits set
784/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
785/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000786///
787/// This returns null if it did not change anything and it permits no
788/// simplification. This returns V itself if it did some simplification of V's
789/// operands based on the information about what bits are demanded. This returns
790/// some other non-null value if it found out that V is equal to another value
791/// in the context where the specified bits are demanded, but not for all users.
792Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
793 APInt &KnownZero, APInt &KnownOne,
794 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000795 assert(V != 0 && "Null pointer of Value???");
796 assert(Depth <= 6 && "Limit Search Depth");
797 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000798 const Type *VTy = V->getType();
799 assert((TD || !isa<PointerType>(VTy)) &&
800 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000801 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
802 (!VTy->isIntOrIntVector() ||
803 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000804 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000805 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000806 "Value *V, DemandedMask, KnownZero and KnownOne "
807 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000808 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
809 // We know all of the bits for a constant!
810 KnownOne = CI->getValue() & DemandedMask;
811 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000812 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000813 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000814 if (isa<ConstantPointerNull>(V)) {
815 // We know all of the bits for a constant!
816 KnownOne.clear();
817 KnownZero = DemandedMask;
818 return 0;
819 }
820
Chris Lattner08d2cc72009-01-31 07:26:06 +0000821 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000822 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000823 if (DemandedMask == 0) { // Not demanding any bits from V.
824 if (isa<UndefValue>(V))
825 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000826 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 }
828
Chris Lattner4598c942009-01-31 08:24:16 +0000829 if (Depth == 6) // Limit search depth.
830 return 0;
831
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000832 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
833 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
834
Dan Gohman1c8491e2009-04-25 17:12:48 +0000835 Instruction *I = dyn_cast<Instruction>(V);
836 if (!I) {
837 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
838 return 0; // Only analyze instructions.
839 }
840
Chris Lattner4598c942009-01-31 08:24:16 +0000841 // If there are multiple uses of this value and we aren't at the root, then
842 // we can't do any simplifications of the operands, because DemandedMask
843 // only reflects the bits demanded by *one* of the users.
844 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000845 // Despite the fact that we can't simplify this instruction in all User's
846 // context, we can at least compute the knownzero/knownone bits, and we can
847 // do simplifications that apply to *just* the one user if we know that
848 // this instruction has a simpler value in that context.
849 if (I->getOpcode() == Instruction::And) {
850 // If either the LHS or the RHS are Zero, the result is zero.
851 ComputeMaskedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1);
853 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
854 LHSKnownZero, LHSKnownOne, Depth+1);
855
856 // If all of the demanded bits are known 1 on one side, return the other.
857 // These bits cannot contribute to the result of the 'and' in this
858 // context.
859 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
860 (DemandedMask & ~LHSKnownZero))
861 return I->getOperand(0);
862 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
863 (DemandedMask & ~RHSKnownZero))
864 return I->getOperand(1);
865
866 // If all of the demanded bits in the inputs are known zeros, return zero.
867 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000868 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000869
870 } else if (I->getOpcode() == Instruction::Or) {
871 // We can simplify (X|Y) -> X or Y in the user's context if we know that
872 // only bits from X or Y are demanded.
873
874 // If either the LHS or the RHS are One, the result is One.
875 ComputeMaskedBits(I->getOperand(1), DemandedMask,
876 RHSKnownZero, RHSKnownOne, Depth+1);
877 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
878 LHSKnownZero, LHSKnownOne, Depth+1);
879
880 // If all of the demanded bits are known zero on one side, return the
881 // other. These bits cannot contribute to the result of the 'or' in this
882 // context.
883 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
884 (DemandedMask & ~LHSKnownOne))
885 return I->getOperand(0);
886 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
887 (DemandedMask & ~RHSKnownOne))
888 return I->getOperand(1);
889
890 // If all of the potentially set bits on one side are known to be set on
891 // the other side, just use the 'other' side.
892 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
893 (DemandedMask & (~RHSKnownZero)))
894 return I->getOperand(0);
895 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
896 (DemandedMask & (~LHSKnownZero)))
897 return I->getOperand(1);
898 }
899
Chris Lattner4598c942009-01-31 08:24:16 +0000900 // Compute the KnownZero/KnownOne bits to simplify things downstream.
901 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
902 return 0;
903 }
904
905 // If this is the root being simplified, allow it to have multiple uses,
906 // just set the DemandedMask to all bits so that we can try to simplify the
907 // operands. This allows visitTruncInst (for example) to simplify the
908 // operand of a trunc without duplicating all the logic below.
909 if (Depth == 0 && !V->hasOneUse())
910 DemandedMask = APInt::getAllOnesValue(BitWidth);
911
Reid Spencer8cb68342007-03-12 17:25:59 +0000912 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000913 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000914 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000915 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000916 case Instruction::And:
917 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000918 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
919 RHSKnownZero, RHSKnownOne, Depth+1) ||
920 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000921 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000922 return I;
923 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
924 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000925
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and'.
928 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
929 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000930 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000931 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
932 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000934
935 // If all of the demanded bits in the inputs are known zeros, return zero.
936 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000937 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000938
939 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000940 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000942
943 // Output known-1 bits are only known if set in both the LHS & RHS.
944 RHSKnownOne &= LHSKnownOne;
945 // Output known-0 are known to be clear if zero in either the LHS | RHS.
946 RHSKnownZero |= LHSKnownZero;
947 break;
948 case Instruction::Or:
949 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000950 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
951 RHSKnownZero, RHSKnownOne, Depth+1) ||
952 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return I;
955 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
956 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000957
958 // If all of the demanded bits are known zero on one side, return the other.
959 // These bits cannot contribute to the result of the 'or'.
960 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
961 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
964 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000966
967 // If all of the potentially set bits on one side are known to be set on
968 // the other side, just use the 'other' side.
969 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
970 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000972 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
973 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000974 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000975
976 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000977 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000979
980 // Output known-0 bits are only known if clear in both the LHS & RHS.
981 RHSKnownZero &= LHSKnownZero;
982 // Output known-1 are known to be set if set in either the LHS | RHS.
983 RHSKnownOne |= LHSKnownOne;
984 break;
985 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
987 RHSKnownZero, RHSKnownOne, Depth+1) ||
988 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000989 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000990 return I;
991 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
992 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000993
994 // If all of the demanded bits are known zero on one side, return the other.
995 // These bits cannot contribute to the result of the 'xor'.
996 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000998 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1002 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1003 (RHSKnownOne & LHSKnownOne);
1004 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1005 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1006 (RHSKnownOne & LHSKnownZero);
1007
1008 // If all of the demanded bits are known to be zero on one side or the
1009 // other, turn this into an *inclusive* or.
1010 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1011 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1012 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001013 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001015 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001016 }
1017
1018 // If all of the demanded bits on one side are known, and all of the set
1019 // bits on that side are also known to be set on the other side, turn this
1020 // into an AND, as we know the bits will be cleared.
1021 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1022 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1023 // all known
1024 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001025 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001026 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001027 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001028 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 }
1030 }
1031
1032 // If the RHS is a constant, see if we can simplify it.
1033 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001034 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001035 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001036
1037 RHSKnownZero = KnownZeroOut;
1038 RHSKnownOne = KnownOneOut;
1039 break;
1040 }
1041 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1043 RHSKnownZero, RHSKnownOne, Depth+1) ||
1044 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001045 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001046 return I;
1047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1048 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001049
1050 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001051 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1052 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001053 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001054
1055 // Only known if known in both the LHS and RHS.
1056 RHSKnownOne &= LHSKnownOne;
1057 RHSKnownZero &= LHSKnownZero;
1058 break;
1059 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001060 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001061 DemandedMask.zext(truncBf);
1062 RHSKnownZero.zext(truncBf);
1063 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001065 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001066 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001067 DemandedMask.trunc(BitWidth);
1068 RHSKnownZero.trunc(BitWidth);
1069 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001070 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001071 break;
1072 }
1073 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001074 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001075 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001076
1077 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1078 if (const VectorType *SrcVTy =
1079 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1080 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1081 // Don't touch a bitcast between vectors of different element counts.
1082 return false;
1083 } else
1084 // Don't touch a scalar-to-vector bitcast.
1085 return false;
1086 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1087 // Don't touch a vector-to-scalar bitcast.
1088 return false;
1089
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001091 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 return I;
1093 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001094 break;
1095 case Instruction::ZExt: {
1096 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001097 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001098
Zhou Shengd48653a2007-03-29 04:45:55 +00001099 DemandedMask.trunc(SrcBitWidth);
1100 RHSKnownZero.trunc(SrcBitWidth);
1101 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001103 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001104 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001105 DemandedMask.zext(BitWidth);
1106 RHSKnownZero.zext(BitWidth);
1107 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001110 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001111 break;
1112 }
1113 case Instruction::SExt: {
1114 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001116
Reid Spencer8cb68342007-03-12 17:25:59 +00001117 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001118 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001119
Zhou Sheng01542f32007-03-29 02:26:30 +00001120 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001121 // If any of the sign extended bits are demanded, we know that the sign
1122 // bit is demanded.
1123 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001124 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001125
Zhou Shengd48653a2007-03-29 04:45:55 +00001126 InputDemandedBits.trunc(SrcBitWidth);
1127 RHSKnownZero.trunc(SrcBitWidth);
1128 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001130 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 InputDemandedBits.zext(BitWidth);
1133 RHSKnownZero.zext(BitWidth);
1134 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001135 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001136
1137 // If the sign bit of the input is known set or clear, then we know the
1138 // top bits of the result.
1139
1140 // If the input sign bit is known zero, or if the NewBits are not demanded
1141 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001142 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001143 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001146 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001148 }
1149 break;
1150 }
1151 case Instruction::Add: {
1152 // Figure out what the input bits are. If the top bits of the and result
1153 // are not demanded, then the add doesn't demand them from its input
1154 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001155 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001156
1157 // If there is a constant on the RHS, there are a variety of xformations
1158 // we can do.
1159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160 // If null, this should be simplified elsewhere. Some of the xforms here
1161 // won't work if the RHS is zero.
1162 if (RHS->isZero())
1163 break;
1164
1165 // If the top bit of the output is demanded, demand everything from the
1166 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001167 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001168
1169 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001171 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001173
1174 // If the RHS of the add has bits set that can't affect the input, reduce
1175 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001176 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001177 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
1179 // Avoid excess work.
1180 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1181 break;
1182
1183 // Turn it into OR if input bits are zero.
1184 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1185 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001186 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 }
1190
1191 // We can say something about the output known-zero and known-one bits,
1192 // depending on potential carries from the input constant and the
1193 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1194 // bits set and the RHS constant is 0x01001, then we know we have a known
1195 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1196
1197 // To compute this, we first compute the potential carry bits. These are
1198 // the bits which may be modified. I'm not aware of a better way to do
1199 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001201 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001202
1203 // Now that we know which bits have carries, compute the known-1/0 sets.
1204
1205 // Bits are known one if they are known zero in one operand and one in the
1206 // other, and there is no input carry.
1207 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1208 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1209
1210 // Bits are known zero if they are known zero in both operands and there
1211 // is no input carry.
1212 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1213 } else {
1214 // If the high-bits of this ADD are not demanded, then it does not demand
1215 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001216 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 // Right fill the mask of bits for this ADD to demand the most
1218 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001219 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001220 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1221 LHSKnownZero, LHSKnownOne, Depth+1) ||
1222 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001224 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 }
1226 }
1227 break;
1228 }
1229 case Instruction::Sub:
1230 // If the high-bits of this SUB are not demanded, then it does not demand
1231 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001232 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 // Right fill the mask of bits for this SUB to demand the most
1234 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001235 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001236 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001237 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1238 LHSKnownZero, LHSKnownOne, Depth+1) ||
1239 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001241 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001243 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1244 // the known zeros and ones.
1245 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 break;
1247 case Instruction::Shl:
1248 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001249 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001250 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001253 return I;
1254 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 RHSKnownZero <<= ShiftAmt;
1256 RHSKnownOne <<= ShiftAmt;
1257 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001258 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001259 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 }
1261 break;
1262 case Instruction::LShr:
1263 // For a logical shift right
1264 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001265 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001266
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001268 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001271 return I;
1272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1274 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001275 if (ShiftAmt) {
1276 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001277 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001278 RHSKnownZero |= HighBits; // high bits known zero.
1279 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 }
1281 break;
1282 case Instruction::AShr:
1283 // If this is an arithmetic shift right and only the low-bit is set, we can
1284 // always convert this into a logical shr, even if the shift amount is
1285 // variable. The low bit of the shift cannot be an input sign bit unless
1286 // the shift amount is >= the size of the datatype, which is undefined.
1287 if (DemandedMask == 1) {
1288 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001293
1294 // If the sign bit is the only bit demanded by this ashr, then there is no
1295 // need to do it, the shift doesn't change the high bit.
1296 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001297 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001298
1299 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001300 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001301
Reid Spencer8cb68342007-03-12 17:25:59 +00001302 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001303 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001304 // If any of the "high bits" are demanded, we should set the sign bit as
1305 // demanded.
1306 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1307 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001310 return I;
1311 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001313 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1315 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1316
1317 // Handle the sign bits.
1318 APInt SignBit(APInt::getSignBit(BitWidth));
1319 // Adjust to where it is now in the mask.
1320 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1321
1322 // If the input sign bit is known to be zero, or if none of the top bits
1323 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001324 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001325 (HighBits & ~DemandedMask) == HighBits) {
1326 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001327 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1331 RHSKnownOne |= HighBits;
1332 }
1333 }
1334 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001335 case Instruction::SRem:
1336 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001337 APInt RA = Rem->getValue().abs();
1338 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001339 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001340 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001341
Nick Lewycky8e394322008-11-02 02:41:50 +00001342 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001343 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001344 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001345 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001346 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001347
1348 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1349 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350
1351 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001352
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001354 }
1355 }
1356 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001357 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001358 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1359 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001360 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1361 KnownZero2, KnownOne2, Depth+1) ||
1362 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001363 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001364 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001365
Chris Lattner455e9ab2009-01-21 18:09:24 +00001366 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001367 Leaders = std::max(Leaders,
1368 KnownZero2.countLeadingOnes());
1369 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001370 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001371 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001372 case Instruction::Call:
1373 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1374 switch (II->getIntrinsicID()) {
1375 default: break;
1376 case Intrinsic::bswap: {
1377 // If the only bits demanded come from one byte of the bswap result,
1378 // just shift the input byte into position to eliminate the bswap.
1379 unsigned NLZ = DemandedMask.countLeadingZeros();
1380 unsigned NTZ = DemandedMask.countTrailingZeros();
1381
1382 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1383 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1384 // have 14 leading zeros, round to 8.
1385 NLZ &= ~7;
1386 NTZ &= ~7;
1387 // If we need exactly one byte, we can do this transformation.
1388 if (BitWidth-NLZ-NTZ == 8) {
1389 unsigned ResultBit = NTZ;
1390 unsigned InputBit = BitWidth-NTZ-8;
1391
1392 // Replace this with either a left or right shift to get the byte into
1393 // the right place.
1394 Instruction *NewVal;
1395 if (InputBit > ResultBit)
1396 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001397 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001398 else
1399 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001400 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001401 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001402 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001403 }
1404
1405 // TODO: Could compute known zero/one bits based on the input.
1406 break;
1407 }
1408 }
1409 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001410 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001411 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001412 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001413
1414 // If the client is only demanding bits that we know, return the known
1415 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001416 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001417 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001418 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001419 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001420 return C;
1421 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001422 return false;
1423}
1424
Chris Lattner867b99f2006-10-05 06:55:50 +00001425
Mon P Wangaeb06d22008-11-10 04:46:22 +00001426/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001427/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001428/// actually used by the caller. This method analyzes which elements of the
1429/// operand are undef and returns that information in UndefElts.
1430///
1431/// If the information about demanded elements can be used to simplify the
1432/// operation, the operation is simplified, then the resultant value is
1433/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001434Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1435 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001436 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001437 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001438 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001439 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001440
1441 if (isa<UndefValue>(V)) {
1442 // If the entire vector is undefined, just return this info.
1443 UndefElts = EltMask;
1444 return 0;
1445 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1446 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001447 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001448 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001449
Chris Lattner867b99f2006-10-05 06:55:50 +00001450 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001451 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1452 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001453 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001454
1455 std::vector<Constant*> Elts;
1456 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001457 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001459 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1461 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001462 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 } else { // Otherwise, defined.
1464 Elts.push_back(CP->getOperand(i));
1465 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001466
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001468 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001469 return NewCP != CP ? NewCP : 0;
1470 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001471 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001473
1474 // Check if this is identity. If so, return 0 since we are not simplifying
1475 // anything.
1476 if (DemandedElts == ((1ULL << VWidth) -1))
1477 return 0;
1478
Reid Spencer9d6565a2007-02-15 02:26:10 +00001479 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001480 Constant *Zero = Context->getNullValue(EltTy);
1481 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001483 for (unsigned i = 0; i != VWidth; ++i) {
1484 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1485 Elts.push_back(Elt);
1486 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001488 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001489 }
1490
Dan Gohman488fbfc2008-09-09 18:11:14 +00001491 // Limit search depth.
1492 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001493 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001494
1495 // If multiple users are using the root value, procede with
1496 // simplification conservatively assuming that all elements
1497 // are needed.
1498 if (!V->hasOneUse()) {
1499 // Quit if we find multiple users of a non-root value though.
1500 // They'll be handled when it's their turn to be visited by
1501 // the main instcombine process.
1502 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001504 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001505
1506 // Conservatively assume that all elements are needed.
1507 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001508 }
1509
1510 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001511 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001512
1513 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001514 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001515 Value *TmpV;
1516 switch (I->getOpcode()) {
1517 default: break;
1518
1519 case Instruction::InsertElement: {
1520 // If this is a variable index, we don't know which element it overwrites.
1521 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001522 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001523 if (Idx == 0) {
1524 // Note that we can't propagate undef elt info, because we don't know
1525 // which elt is getting updated.
1526 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527 UndefElts2, Depth+1);
1528 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529 break;
1530 }
1531
1532 // If this is inserting an element that isn't demanded, remove this
1533 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001534 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001535 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001536 return AddSoonDeadInstToWorklist(*I, 0);
1537
1538 // Otherwise, the element inserted overwrites whatever was there, so the
1539 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001540 APInt DemandedElts2 = DemandedElts;
1541 DemandedElts2.clear(IdxNo);
1542 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001543 UndefElts, Depth+1);
1544 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545
1546 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001547 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001548 break;
1549 }
1550 case Instruction::ShuffleVector: {
1551 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001552 uint64_t LHSVWidth =
1553 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001554 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001555 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001556 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001557 unsigned MaskVal = Shuffle->getMaskValue(i);
1558 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001559 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001561 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001562 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 else
Evan Cheng388df622009-02-03 10:05:09 +00001564 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 }
1566 }
1567 }
1568
Nate Begeman7b254672009-02-11 22:36:25 +00001569 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001571 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1573
Nate Begeman7b254672009-02-11 22:36:25 +00001574 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1576 UndefElts3, Depth+1);
1577 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1578
1579 bool NewUndefElts = false;
1580 for (unsigned i = 0; i < VWidth; i++) {
1581 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001582 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001583 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001584 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001585 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001586 NewUndefElts = true;
1587 UndefElts.set(i);
1588 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001589 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001590 if (UndefElts3[MaskVal - LHSVWidth]) {
1591 NewUndefElts = true;
1592 UndefElts.set(i);
1593 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001594 }
1595 }
1596
1597 if (NewUndefElts) {
1598 // Add additional discovered undefs.
1599 std::vector<Constant*> Elts;
1600 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001601 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001602 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001603 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001604 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001605 Shuffle->getMaskValue(i)));
1606 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001607 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001608 MadeChange = true;
1609 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001610 break;
1611 }
Chris Lattner69878332007-04-14 22:29:23 +00001612 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001613 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001614 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1615 if (!VTy) break;
1616 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001617 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001618 unsigned Ratio;
1619
1620 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001621 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001622 // elements as are demanded of us.
1623 Ratio = 1;
1624 InputDemandedElts = DemandedElts;
1625 } else if (VWidth > InVWidth) {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the result than there are in the source,
1630 // then an input element is live if any of the corresponding output
1631 // elements are live.
1632 Ratio = VWidth/InVWidth;
1633 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001634 if (DemandedElts[OutIdx])
1635 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001636 }
1637 } else {
1638 // Untested so far.
1639 break;
1640
1641 // If there are more elements in the source than there are in the result,
1642 // then an input element is live if the corresponding output element is
1643 // live.
1644 Ratio = InVWidth/VWidth;
1645 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001646 if (DemandedElts[InIdx/Ratio])
1647 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001648 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001649
Chris Lattner69878332007-04-14 22:29:23 +00001650 // div/rem demand all inputs, because they don't want divide by zero.
1651 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1652 UndefElts2, Depth+1);
1653 if (TmpV) {
1654 I->setOperand(0, TmpV);
1655 MadeChange = true;
1656 }
1657
1658 UndefElts = UndefElts2;
1659 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001660 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001661 // If there are more elements in the result than there are in the source,
1662 // then an output element is undef if the corresponding input element is
1663 // undef.
1664 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001665 if (UndefElts2[OutIdx/Ratio])
1666 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001667 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001668 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001669 // If there are more elements in the source than there are in the result,
1670 // then a result element is undef if all of the corresponding input
1671 // elements are undef.
1672 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1673 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001674 if (!UndefElts2[InIdx]) // Not undef?
1675 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001676 }
1677 break;
1678 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001679 case Instruction::And:
1680 case Instruction::Or:
1681 case Instruction::Xor:
1682 case Instruction::Add:
1683 case Instruction::Sub:
1684 case Instruction::Mul:
1685 // div/rem demand all inputs, because they don't want divide by zero.
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687 UndefElts, Depth+1);
1688 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1690 UndefElts2, Depth+1);
1691 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1692
1693 // Output elements are undefined if both are undefined. Consider things
1694 // like undef&0. The result is known zero, not undef.
1695 UndefElts &= UndefElts2;
1696 break;
1697
1698 case Instruction::Call: {
1699 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1700 if (!II) break;
1701 switch (II->getIntrinsicID()) {
1702 default: break;
1703
1704 // Binary vector operations that work column-wise. A dest element is a
1705 // function of the corresponding input elements from the two inputs.
1706 case Intrinsic::x86_sse_sub_ss:
1707 case Intrinsic::x86_sse_mul_ss:
1708 case Intrinsic::x86_sse_min_ss:
1709 case Intrinsic::x86_sse_max_ss:
1710 case Intrinsic::x86_sse2_sub_sd:
1711 case Intrinsic::x86_sse2_mul_sd:
1712 case Intrinsic::x86_sse2_min_sd:
1713 case Intrinsic::x86_sse2_max_sd:
1714 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1715 UndefElts, Depth+1);
1716 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1717 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1718 UndefElts2, Depth+1);
1719 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1720
1721 // If only the low elt is demanded and this is a scalarizable intrinsic,
1722 // scalarize it now.
1723 if (DemandedElts == 1) {
1724 switch (II->getIntrinsicID()) {
1725 default: break;
1726 case Intrinsic::x86_sse_sub_ss:
1727 case Intrinsic::x86_sse_mul_ss:
1728 case Intrinsic::x86_sse2_sub_sd:
1729 case Intrinsic::x86_sse2_mul_sd:
1730 // TODO: Lower MIN/MAX/ABS/etc
1731 Value *LHS = II->getOperand(1);
1732 Value *RHS = II->getOperand(2);
1733 // Extract the element as scalars.
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001734 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
1735 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1736 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1737 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001738
1739 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001740 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001741 case Intrinsic::x86_sse_sub_ss:
1742 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001743 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001744 II->getName()), *II);
1745 break;
1746 case Intrinsic::x86_sse_mul_ss:
1747 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001748 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001749 II->getName()), *II);
1750 break;
1751 }
1752
1753 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001754 InsertElementInst::Create(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001755 Context->getUndef(II->getType()), TmpV,
1756 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001757 InsertNewInstBefore(New, *II);
1758 AddSoonDeadInstToWorklist(*II, 0);
1759 return New;
1760 }
1761 }
1762
1763 // Output elements are undefined if both are undefined. Consider things
1764 // like undef&0. The result is known zero, not undef.
1765 UndefElts &= UndefElts2;
1766 break;
1767 }
1768 break;
1769 }
1770 }
1771 return MadeChange ? I : 0;
1772}
1773
Dan Gohman45b4e482008-05-19 22:14:15 +00001774
Chris Lattner564a7272003-08-13 19:01:45 +00001775/// AssociativeOpt - Perform an optimization on an associative operator. This
1776/// function is designed to check a chain of associative operators for a
1777/// potential to apply a certain optimization. Since the optimization may be
1778/// applicable if the expression was reassociated, this checks the chain, then
1779/// reassociates the expression as necessary to expose the optimization
1780/// opportunity. This makes use of a special Functor, which must define
1781/// 'shouldApply' and 'apply' methods.
1782///
1783template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001784static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001785 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001786 unsigned Opcode = Root.getOpcode();
1787 Value *LHS = Root.getOperand(0);
1788
1789 // Quick check, see if the immediate LHS matches...
1790 if (F.shouldApply(LHS))
1791 return F.apply(Root);
1792
1793 // Otherwise, if the LHS is not of the same opcode as the root, return.
1794 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001795 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001796 // Should we apply this transform to the RHS?
1797 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1798
1799 // If not to the RHS, check to see if we should apply to the LHS...
1800 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1801 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1802 ShouldApply = true;
1803 }
1804
1805 // If the functor wants to apply the optimization to the RHS of LHSI,
1806 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1807 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001808 // Now all of the instructions are in the current basic block, go ahead
1809 // and perform the reassociation.
1810 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1811
1812 // First move the selected RHS to the LHS of the root...
1813 Root.setOperand(0, LHSI->getOperand(1));
1814
1815 // Make what used to be the LHS of the root be the user of the root...
1816 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001817 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001818 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001819 return 0;
1820 }
Chris Lattner65725312004-04-16 18:08:07 +00001821 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001822 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001823 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001824 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001825 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001826
1827 // Now propagate the ExtraOperand down the chain of instructions until we
1828 // get to LHSI.
1829 while (TmpLHSI != LHSI) {
1830 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001831 // Move the instruction to immediately before the chain we are
1832 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001833 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001834 ARI = NextLHSI;
1835
Chris Lattner564a7272003-08-13 19:01:45 +00001836 Value *NextOp = NextLHSI->getOperand(1);
1837 NextLHSI->setOperand(1, ExtraOperand);
1838 TmpLHSI = NextLHSI;
1839 ExtraOperand = NextOp;
1840 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001841
Chris Lattner564a7272003-08-13 19:01:45 +00001842 // Now that the instructions are reassociated, have the functor perform
1843 // the transformation...
1844 return F.apply(Root);
1845 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001846
Chris Lattner564a7272003-08-13 19:01:45 +00001847 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1848 }
1849 return 0;
1850}
1851
Dan Gohman844731a2008-05-13 00:00:25 +00001852namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001853
Nick Lewycky02d639f2008-05-23 04:34:58 +00001854// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001855struct AddRHS {
1856 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001857 LLVMContext *Context;
1858 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001859 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1860 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001861 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001862 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001863 }
1864};
1865
1866// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1867// iff C1&C2 == 0
1868struct AddMaskingAnd {
1869 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001870 LLVMContext *Context;
1871 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001872 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001873 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001874 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001875 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001876 }
1877 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001878 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001879 }
1880};
1881
Dan Gohman844731a2008-05-13 00:00:25 +00001882}
1883
Chris Lattner6e7ba452005-01-01 16:22:27 +00001884static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001885 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001886 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001887
Reid Spencer3da59db2006-11-27 01:05:10 +00001888 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001889 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001890 }
1891
Chris Lattner2eefe512004-04-09 19:05:30 +00001892 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001893 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1894 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001895
Chris Lattner2eefe512004-04-09 19:05:30 +00001896 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1897 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001898 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1899 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001900 }
1901
1902 Value *Op0 = SO, *Op1 = ConstOperand;
1903 if (!ConstIsRHS)
1904 std::swap(Op0, Op1);
1905 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001906 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001907 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001908 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001909 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1910 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001911 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001912 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001913 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001914 return IC->InsertNewInstBefore(New, I);
1915}
1916
1917// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1918// constant as the other operand, try to fold the binary operator into the
1919// select arguments. This also works for Cast instructions, which obviously do
1920// not have a second operand.
1921static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1922 InstCombiner *IC) {
1923 // Don't modify shared select instructions
1924 if (!SI->hasOneUse()) return 0;
1925 Value *TV = SI->getOperand(1);
1926 Value *FV = SI->getOperand(2);
1927
1928 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001929 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001930 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001931
Chris Lattner6e7ba452005-01-01 16:22:27 +00001932 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1933 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1934
Gabor Greif051a9502008-04-06 20:25:17 +00001935 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1936 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001937 }
1938 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001939}
1940
Chris Lattner4e998b22004-09-29 05:07:12 +00001941
1942/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1943/// node as operand #0, see if we can fold the instruction into the PHI (which
1944/// is only possible if all operands to the PHI are constants).
1945Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1946 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001947 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001948 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001949
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001950 // Check to see if all of the operands of the PHI are constants. If there is
1951 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001952 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001953 BasicBlock *NonConstBB = 0;
1954 for (unsigned i = 0; i != NumPHIValues; ++i)
1955 if (!isa<Constant>(PN->getIncomingValue(i))) {
1956 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001957 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001958 NonConstBB = PN->getIncomingBlock(i);
1959
1960 // If the incoming non-constant value is in I's block, we have an infinite
1961 // loop.
1962 if (NonConstBB == I.getParent())
1963 return 0;
1964 }
1965
1966 // If there is exactly one non-constant value, we can insert a copy of the
1967 // operation in that block. However, if this is a critical edge, we would be
1968 // inserting the computation one some other paths (e.g. inside a loop). Only
1969 // do this if the pred block is unconditionally branching into the phi block.
1970 if (NonConstBB) {
1971 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1972 if (!BI || !BI->isUnconditional()) return 0;
1973 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001974
1975 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001976 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001977 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001978 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001979 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001980
1981 // Next, add all of the operands to the PHI.
1982 if (I.getNumOperands() == 2) {
1983 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001984 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001985 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001986 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001987 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00001988 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001989 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001990 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001991 } else {
1992 assert(PN->getIncomingBlock(i) == NonConstBB);
1993 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001994 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001995 PN->getIncomingValue(i), C, "phitmp",
1996 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001997 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001998 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001999 CI->getPredicate(),
2000 PN->getIncomingValue(i), C, "phitmp",
2001 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002003 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002004
Chris Lattnerdbab3862007-03-02 21:28:56 +00002005 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006 }
2007 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002008 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002009 } else {
2010 CastInst *CI = cast<CastInst>(&I);
2011 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002012 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 Value *InV;
2014 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002015 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002016 } else {
2017 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002018 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002019 I.getType(), "phitmp",
2020 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002021 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002022 }
2023 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002024 }
2025 }
2026 return ReplaceInstUsesWith(I, NewPN);
2027}
2028
Chris Lattner2454a2e2008-01-29 06:52:45 +00002029
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002030/// WillNotOverflowSignedAdd - Return true if we can prove that:
2031/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2032/// This basically requires proving that the add in the original type would not
2033/// overflow to change the sign bit or have a carry out.
2034bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2035 // There are different heuristics we can use for this. Here are some simple
2036 // ones.
2037
2038 // Add has the property that adding any two 2's complement numbers can only
2039 // have one carry bit which can change a sign. As such, if LHS and RHS each
2040 // have at least two sign bits, we know that the addition of the two values will
2041 // sign extend fine.
2042 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2043 return true;
2044
2045
2046 // If one of the operands only has one non-zero bit, and if the other operand
2047 // has a known-zero bit in a more significant place than it (not including the
2048 // sign bit) the ripple may go up to and fill the zero, but won't change the
2049 // sign. For example, (X & ~4) + 1.
2050
2051 // TODO: Implement.
2052
2053 return false;
2054}
2055
Chris Lattner2454a2e2008-01-29 06:52:45 +00002056
Chris Lattner7e708292002-06-25 16:13:24 +00002057Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002058 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002059 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002060
Chris Lattner66331a42004-04-10 22:01:55 +00002061 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002062 // X + undef -> undef
2063 if (isa<UndefValue>(RHS))
2064 return ReplaceInstUsesWith(I, RHS);
2065
Chris Lattner66331a42004-04-10 22:01:55 +00002066 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002067 if (RHSC->isNullValue())
2068 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002069
Chris Lattner66331a42004-04-10 22:01:55 +00002070 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002071 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002072 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002073 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002074 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002075 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002076
2077 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2078 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002079 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002080 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002081
Eli Friedman709b33d2009-07-13 22:27:52 +00002082 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002083 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002084 if (ZI->getSrcTy() == Type::Int1Ty)
2085 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002086 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002087
2088 if (isa<PHINode>(LHS))
2089 if (Instruction *NV = FoldOpIntoPhi(I))
2090 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002091
Chris Lattner4f637d42006-01-06 17:59:59 +00002092 ConstantInt *XorRHS = 0;
2093 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002094 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002095 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002096 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002097 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002098
Zhou Sheng4351c642007-04-02 08:20:41 +00002099 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002100 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2101 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002102 do {
2103 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002104 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2105 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002106 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2107 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002108 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002109 if (!MaskedValueIsZero(XorLHS,
2110 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002111 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002112 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002113 }
2114 }
2115 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002116 C0080Val = APIntOps::lshr(C0080Val, Size);
2117 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2118 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002119
Reid Spencer35c38852007-03-28 01:36:16 +00002120 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002121 // with funny bit widths then this switch statement should be removed. It
2122 // is just here to get the size of the "middle" type back up to something
2123 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002124 const Type *MiddleType = 0;
2125 switch (Size) {
2126 default: break;
2127 case 32: MiddleType = Type::Int32Ty; break;
2128 case 16: MiddleType = Type::Int16Ty; break;
2129 case 8: MiddleType = Type::Int8Ty; break;
2130 }
2131 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002132 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002133 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002134 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002135 }
2136 }
Chris Lattner66331a42004-04-10 22:01:55 +00002137 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002138
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002139 if (I.getType() == Type::Int1Ty)
2140 return BinaryOperator::CreateXor(LHS, RHS);
2141
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002142 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002143 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002144 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2145 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002146
2147 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2148 if (RHSI->getOpcode() == Instruction::Sub)
2149 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2150 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2151 }
2152 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2153 if (LHSI->getOpcode() == Instruction::Sub)
2154 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2155 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2156 }
Robert Bocchino71698282004-07-27 21:02:21 +00002157 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002158
Chris Lattner5c4afb92002-05-08 22:46:53 +00002159 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002160 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002161 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002162 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002163 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002164 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002165 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002166 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002167 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002168 }
2169
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002170 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002171 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002172
2173 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002174 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002175 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002176 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002177
Misha Brukmanfd939082005-04-21 23:48:37 +00002178
Chris Lattner50af16a2004-11-13 19:50:12 +00002179 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002180 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002181 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002182 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002183
2184 // X*C1 + X*C2 --> X * (C1+C2)
2185 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002186 if (X == dyn_castFoldableMul(RHS, C1, Context))
2187 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002188 }
2189
2190 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002191 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2192 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002193
Chris Lattnere617c9e2007-01-05 02:17:46 +00002194 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002195 if (dyn_castNotVal(LHS, Context) == RHS ||
2196 dyn_castNotVal(RHS, Context) == LHS)
2197 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002198
Chris Lattnerad3448c2003-02-18 19:57:07 +00002199
Chris Lattner564a7272003-08-13 19:01:45 +00002200 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002201 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002202 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002203 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002204
2205 // A+B --> A|B iff A and B have no bits set in common.
2206 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2207 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2208 APInt LHSKnownOne(IT->getBitWidth(), 0);
2209 APInt LHSKnownZero(IT->getBitWidth(), 0);
2210 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2211 if (LHSKnownZero != 0) {
2212 APInt RHSKnownOne(IT->getBitWidth(), 0);
2213 APInt RHSKnownZero(IT->getBitWidth(), 0);
2214 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2215
2216 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002217 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002218 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002219 }
2220 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002221
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002222 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002223 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002224 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002225 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2226 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002227 if (W != Y) {
2228 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002229 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002230 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002231 std::swap(W, X);
2232 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002233 std::swap(Y, Z);
2234 std::swap(W, X);
2235 }
2236 }
2237
2238 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002239 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002240 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002241 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002242 }
2243 }
2244 }
2245
Chris Lattner6b032052003-10-02 15:11:26 +00002246 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002247 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002248 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002249 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002250
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002251 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002252 if (LHS->hasOneUse() &&
2253 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002254 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002255 if (Anded == CRHS) {
2256 // See if all bits from the first bit set in the Add RHS up are included
2257 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002258 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002259
2260 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002261 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262
2263 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002264 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002265
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002266 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2267 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002268 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002269 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002270 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002271 }
2272 }
2273 }
2274
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002275 // Try to fold constant add into select arguments.
2276 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002277 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002278 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002279 }
2280
Chris Lattner42790482007-12-20 01:56:58 +00002281 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002282 {
2283 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002284 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002285 if (!SI) {
2286 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002287 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002288 }
Chris Lattner42790482007-12-20 01:56:58 +00002289 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002290 Value *TV = SI->getTrueValue();
2291 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002292 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002293
2294 // Can we fold the add into the argument of the select?
2295 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002296 if (match(FV, m_Zero(), *Context) &&
2297 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002298 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002299 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002300 if (match(TV, m_Zero(), *Context) &&
2301 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002302 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002303 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002304 }
2305 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002306
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002307 // Check for (add (sext x), y), see if we can merge this into an
2308 // integer add followed by a sext.
2309 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2310 // (add (sext x), cst) --> (sext (add x, cst'))
2311 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2312 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002313 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002314 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002315 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002316 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2317 // Insert the new, smaller add.
2318 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2319 CI, "addconv");
2320 InsertNewInstBefore(NewAdd, I);
2321 return new SExtInst(NewAdd, I.getType());
2322 }
2323 }
2324
2325 // (add (sext x), (sext y)) --> (sext (add int x, y))
2326 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2327 // Only do this if x/y have the same type, if at last one of them has a
2328 // single use (so we don't increase the number of sexts), and if the
2329 // integer add will not overflow.
2330 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2331 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2332 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2333 RHSConv->getOperand(0))) {
2334 // Insert the new integer add.
2335 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2336 RHSConv->getOperand(0),
2337 "addconv");
2338 InsertNewInstBefore(NewAdd, I);
2339 return new SExtInst(NewAdd, I.getType());
2340 }
2341 }
2342 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002343
2344 return Changed ? &I : 0;
2345}
2346
2347Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2348 bool Changed = SimplifyCommutative(I);
2349 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2350
2351 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2352 // X + 0 --> X
2353 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002354 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002355 (I.getType())->getValueAPF()))
2356 return ReplaceInstUsesWith(I, LHS);
2357 }
2358
2359 if (isa<PHINode>(LHS))
2360 if (Instruction *NV = FoldOpIntoPhi(I))
2361 return NV;
2362 }
2363
2364 // -A + B --> B - A
2365 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002366 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002367 return BinaryOperator::CreateFSub(RHS, LHSV);
2368
2369 // A + -B --> A - B
2370 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002371 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002372 return BinaryOperator::CreateFSub(LHS, V);
2373
2374 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2375 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2376 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2377 return ReplaceInstUsesWith(I, LHS);
2378
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002379 // Check for (add double (sitofp x), y), see if we can merge this into an
2380 // integer add followed by a promotion.
2381 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2382 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2383 // ... if the constant fits in the integer value. This is useful for things
2384 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2385 // requires a constant pool load, and generally allows the add to be better
2386 // instcombined.
2387 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2388 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002389 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002390 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002391 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002392 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2393 // Insert the new integer add.
2394 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2395 CI, "addconv");
2396 InsertNewInstBefore(NewAdd, I);
2397 return new SIToFPInst(NewAdd, I.getType());
2398 }
2399 }
2400
2401 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2402 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2403 // Only do this if x/y have the same type, if at last one of them has a
2404 // single use (so we don't increase the number of int->fp conversions),
2405 // and if the integer add will not overflow.
2406 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2407 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2408 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2409 RHSConv->getOperand(0))) {
2410 // Insert the new integer add.
2411 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2412 RHSConv->getOperand(0),
2413 "addconv");
2414 InsertNewInstBefore(NewAdd, I);
2415 return new SIToFPInst(NewAdd, I.getType());
2416 }
2417 }
2418 }
2419
Chris Lattner7e708292002-06-25 16:13:24 +00002420 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002421}
2422
Chris Lattner7e708292002-06-25 16:13:24 +00002423Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002424 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002425
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002426 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002427 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002428
Chris Lattner233f7dc2002-08-12 21:17:25 +00002429 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002430 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002431 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002432
Chris Lattnere87597f2004-10-16 18:11:37 +00002433 if (isa<UndefValue>(Op0))
2434 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2435 if (isa<UndefValue>(Op1))
2436 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2437
Chris Lattnerd65460f2003-11-05 01:06:05 +00002438 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2439 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002440 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002441 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002442
Chris Lattnerd65460f2003-11-05 01:06:05 +00002443 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002444 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002445 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002446 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002447
Chris Lattner76b7a062007-01-15 07:02:54 +00002448 // -(X >>u 31) -> (X >>s 31)
2449 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002450 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002451 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002452 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002453 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002454 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002455 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002456 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002457 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002458 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002459 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002460 }
2461 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002462 }
2463 else if (SI->getOpcode() == Instruction::AShr) {
2464 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2465 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002466 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002467 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002468 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002469 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002470 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002471 }
2472 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002473 }
2474 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002475 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002476
2477 // Try to fold constant sub into select arguments.
2478 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002479 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002480 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002481
2482 // C - zext(bool) -> bool ? C - 1 : C
2483 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2484 if (ZI->getSrcTy() == Type::Int1Ty)
2485 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002486 }
2487
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002488 if (I.getType() == Type::Int1Ty)
2489 return BinaryOperator::CreateXor(Op0, Op1);
2490
Chris Lattner43d84d62005-04-07 16:15:25 +00002491 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002492 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002493 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002494 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2495 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002496 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002497 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2498 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002499 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2500 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2501 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002502 return BinaryOperator::CreateSub(
2503 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002504 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002505 }
2506
Chris Lattnerfd059242003-10-15 16:48:29 +00002507 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002508 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2509 // is not used by anyone else...
2510 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002511 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002512 // Swap the two operands of the subexpr...
2513 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2514 Op1I->setOperand(0, IIOp1);
2515 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002516
Chris Lattnera2881962003-02-18 19:28:33 +00002517 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002518 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002519 }
2520
2521 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2522 //
2523 if (Op1I->getOpcode() == Instruction::And &&
2524 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2525 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2526
Chris Lattnerf523d062004-06-09 05:08:07 +00002527 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002528 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2529 OtherOp, "B.not"), I);
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 Andersond672ecb2009-07-03 00:17:18 +00002539 Context->getConstantExprNeg(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;
Owen Andersond672ecb2009-07-03 00:17:18 +00002543 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2544 Constant *CP1 =
2545 Context->getConstantExprSub(Context->getConstantInt(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
Owen Anderson0a5372e2009-07-13 04:09:18 +00002560 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2561 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;
Owen Andersond672ecb2009-07-03 00:17:18 +00002566 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002567 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002568 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
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)
Owen Andersond672ecb2009-07-03 00:17:18 +00002571 if (X == dyn_castFoldableMul(Op1, C2, Context))
2572 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(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...
Owen Andersond672ecb2009-07-03 00:17:18 +00002581 if (Value *V = dyn_castFNegVal(Op1, Context))
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
Owen Anderson0a5372e2009-07-13 04:09:18 +00002587 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2588 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002589 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002590 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2591 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 Andersond672ecb2009-07-03 00:17:18 +00002633 return ReplaceInstUsesWith(I, Context->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 Andersond672ecb2009-07-03 00:17:18 +00002644 Context->getConstantExprShl(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
Owen Anderson0a5372e2009-07-13 04:09:18 +00002651 return BinaryOperator::CreateNeg(*Context, 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 Andersond672ecb2009-07-03 00:17:18 +00002656 Context->getConstantInt(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
Owen Anderson0a5372e2009-07-13 04:09:18 +00002664 return BinaryOperator::CreateNeg(*Context, 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.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002679 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002680 Op1, "tmp");
2681 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002682 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002683 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002685
2686 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002687
2688 // Try to fold constant mul into select arguments.
2689 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002690 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002691 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002692
2693 if (isa<PHINode>(Op0))
2694 if (Instruction *NV = FoldOpIntoPhi(I))
2695 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002696 }
2697
Owen Andersond672ecb2009-07-03 00:17:18 +00002698 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2699 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002700 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002701
Nick Lewycky0c730792008-11-21 07:33:58 +00002702 // (X / Y) * Y = X - (X % Y)
2703 // (X / Y) * -Y = (X % Y) - X
2704 {
2705 Value *Op1 = I.getOperand(1);
2706 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2707 if (!BO ||
2708 (BO->getOpcode() != Instruction::UDiv &&
2709 BO->getOpcode() != Instruction::SDiv)) {
2710 Op1 = Op0;
2711 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2712 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002713 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002714 if (BO && BO->hasOneUse() &&
2715 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2716 (BO->getOpcode() == Instruction::UDiv ||
2717 BO->getOpcode() == Instruction::SDiv)) {
2718 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2719
2720 Instruction *Rem;
2721 if (BO->getOpcode() == Instruction::UDiv)
2722 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2723 else
2724 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2725
2726 InsertNewInstBefore(Rem, I);
2727 Rem->takeName(BO);
2728
2729 if (Op1BO == Op1)
2730 return BinaryOperator::CreateSub(Op0BO, Rem);
2731 else
2732 return BinaryOperator::CreateSub(Rem, Op0BO);
2733 }
2734 }
2735
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002736 if (I.getType() == Type::Int1Ty)
2737 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2738
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002739 // If one of the operands of the multiply is a cast from a boolean value, then
2740 // we know the bool is either zero or one, so this is a 'masking' multiply.
2741 // See if we can simplify things based on how the boolean was originally
2742 // formed.
2743 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002744 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002745 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002746 BoolCast = CI;
2747 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002748 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002749 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002750 BoolCast = CI;
2751 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002752 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002753 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2754 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002755 bool TIS = false;
2756
Reid Spencere4d87aa2006-12-23 06:05:41 +00002757 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002758 // multiply into a shift/and combination.
2759 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002760 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2761 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002762 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002763 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002764 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002765 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002766 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002767 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002768 BoolCast->getOperand(0)->getName()+
2769 ".mask"), I);
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
Owen Andersond672ecb2009-07-03 00:17:18 +00002823 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2824 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
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);
2879 AddToWorkList(BBI);
2880 } else if (*I == SelectCond) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00002881 *I = NonNullOperand == 1 ? Context->getTrue() :
2882 Context->getFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002883 AddToWorkList(BBI);
2884 }
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 Andersond672ecb2009-07-03 00:17:18 +00002914 return ReplaceInstUsesWith(I, Context->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 Andersond672ecb2009-07-03 00:17:18 +00002934 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002935 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002936 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002937 }
2938
Owen Andersond672ecb2009-07-03 00:17:18 +00002939 Constant *CI = Context->getConstantInt(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,
2961 I.getOpcode()==Instruction::SDiv, Context))
2962 return ReplaceInstUsesWith(I, Context->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 Andersond672ecb2009-07-03 00:17:18 +00002965 Context->getConstantExprMul(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 Andersond672ecb2009-07-03 00:17:18 +00002981 return ReplaceInstUsesWith(I, Context->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.
2984 if (I.getType() == Type::Int1Ty)
2985 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 Andersond672ecb2009-07-03 00:17:18 +00003010 Context->getConstantInt(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()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003014 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3015 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003016 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003017 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3018 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003019 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003020 }
3021
3022 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003023 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 if (RHSI->getOpcode() == Instruction::Shl &&
3025 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003026 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003027 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003028 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003029 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003030 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003031 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003032 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003033 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003035 }
3036 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003037 }
3038
Reid Spencer1628cec2006-10-26 06:15:43 +00003039 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3040 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003042 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003043 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003044 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003045 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003047 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003048 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003049 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003050 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003051 Op0, TC, SI->getName()+".t");
3052 TSI = InsertNewInstBefore(TSI, I);
3053
3054 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003055 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003056 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003057 Op0, FC, SI->getName()+".f");
3058 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003059
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003060 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003061 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003063 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003064 return 0;
3065}
3066
Reid Spencer1628cec2006-10-26 06:15:43 +00003067Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3068 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3069
3070 // Handle the integer div common cases
3071 if (Instruction *Common = commonIDivTransforms(I))
3072 return Common;
3073
3074 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3075 // sdiv X, -1 == -X
3076 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003077 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003078 }
3079
3080 // If the sign bits of both operands are zero (i.e. we can prove they are
3081 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003082 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003083 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003084 if (MaskedValueIsZero(Op0, Mask)) {
3085 if (MaskedValueIsZero(Op1, Mask)) {
3086 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3087 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3088 }
3089 ConstantInt *ShiftedInt;
3090 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3091 ShiftedInt->getValue().isPowerOf2()) {
3092 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3093 // Safe because the only negative value (1 << Y) can take on is
3094 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3095 // the sign bit set.
3096 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3097 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003098 }
Eli Friedman8be17392009-07-18 09:53:21 +00003099 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003100
3101 return 0;
3102}
3103
3104Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3105 return commonDivTransforms(I);
3106}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003107
Reid Spencer0a783f72006-11-02 01:53:59 +00003108/// This function implements the transforms on rem instructions that work
3109/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3110/// is used by the visitors to those instructions.
3111/// @brief Transforms common to all three rem instructions
3112Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003113 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003114
Chris Lattner50b2ca42008-02-19 06:12:18 +00003115 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3116 if (I.getType()->isFPOrFPVector())
3117 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003118 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003119 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003120 if (isa<UndefValue>(Op1))
3121 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003122
3123 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003124 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3125 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003126
Reid Spencer0a783f72006-11-02 01:53:59 +00003127 return 0;
3128}
3129
3130/// This function implements the transforms common to both integer remainder
3131/// instructions (urem and srem). It is called by the visitors to those integer
3132/// remainder instructions.
3133/// @brief Common integer remainder transforms
3134Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3135 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3136
3137 if (Instruction *common = commonRemTransforms(I))
3138 return common;
3139
Dale Johannesened6af242009-01-21 00:35:19 +00003140 // 0 % X == 0 for integer, we don't need to preserve faults!
3141 if (Constant *LHS = dyn_cast<Constant>(Op0))
3142 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003143 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003144
Chris Lattner857e8cd2004-12-12 21:48:58 +00003145 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003146 // X % 0 == undef, we don't need to preserve faults!
3147 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003148 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003149
Chris Lattnera2881962003-02-18 19:28:33 +00003150 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003151 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003152
Chris Lattner97943922006-02-28 05:49:21 +00003153 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3154 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3155 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3156 return R;
3157 } else if (isa<PHINode>(Op0I)) {
3158 if (Instruction *NV = FoldOpIntoPhi(I))
3159 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003160 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003161
3162 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003163 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003164 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003165 }
Chris Lattnera2881962003-02-18 19:28:33 +00003166 }
3167
Reid Spencer0a783f72006-11-02 01:53:59 +00003168 return 0;
3169}
3170
3171Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3173
3174 if (Instruction *common = commonIRemTransforms(I))
3175 return common;
3176
3177 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3178 // X urem C^2 -> X and C
3179 // Check to see if this is an unsigned remainder with an exact power of 2,
3180 // if so, convert to a bitwise and.
3181 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003182 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003183 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003184 }
3185
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003186 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003187 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3188 if (RHSI->getOpcode() == Instruction::Shl &&
3189 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003190 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003191 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003192 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003193 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003194 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003195 }
3196 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003197 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003198
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3200 // where C1&C2 are powers of two.
3201 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3202 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3203 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3204 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003205 if ((STO->getValue().isPowerOf2()) &&
3206 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003207 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003208 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3209 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003210 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003211 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3212 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003213 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003214 }
3215 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003216 }
3217
Chris Lattner3f5b8772002-05-06 16:14:14 +00003218 return 0;
3219}
3220
Reid Spencer0a783f72006-11-02 01:53:59 +00003221Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3223
Dan Gohmancff55092007-11-05 23:16:33 +00003224 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003225 if (Instruction *common = commonIRemTransforms(I))
3226 return common;
3227
Owen Andersond672ecb2009-07-03 00:17:18 +00003228 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003229 if (!isa<Constant>(RHSNeg) ||
3230 (isa<ConstantInt>(RHSNeg) &&
3231 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003232 // X % -Y -> X % Y
3233 AddUsesToWorkList(I);
3234 I.setOperand(1, RHSNeg);
3235 return &I;
3236 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003237
Dan Gohmancff55092007-11-05 23:16:33 +00003238 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003239 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003240 if (I.getType()->isInteger()) {
3241 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3242 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3243 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003244 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003245 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003246 }
3247
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003248 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003249 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3250 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003251
Nick Lewycky9dce8732008-12-20 16:48:00 +00003252 bool hasNegative = false;
3253 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3254 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3255 if (RHS->getValue().isNegative())
3256 hasNegative = true;
3257
3258 if (hasNegative) {
3259 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003260 for (unsigned i = 0; i != VWidth; ++i) {
3261 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3262 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003263 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003264 else
3265 Elts[i] = RHS;
3266 }
3267 }
3268
Owen Andersond672ecb2009-07-03 00:17:18 +00003269 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003271 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003272 I.setOperand(1, NewRHSV);
3273 return &I;
3274 }
3275 }
3276 }
3277
Reid Spencer0a783f72006-11-02 01:53:59 +00003278 return 0;
3279}
3280
3281Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003282 return commonRemTransforms(I);
3283}
3284
Chris Lattner457dd822004-06-09 07:59:58 +00003285// isOneBitSet - Return true if there is exactly one bit set in the specified
3286// constant.
3287static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003288 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003289}
3290
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003291// isHighOnes - Return true if the constant is of the form 1+0+.
3292// This is the same as lowones(~X).
3293static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003294 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003295}
3296
Reid Spencere4d87aa2006-12-23 06:05:41 +00003297/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003298/// are carefully arranged to allow folding of expressions such as:
3299///
3300/// (A < B) | (A > B) --> (A != B)
3301///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003302/// Note that this is only valid if the first and second predicates have the
3303/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003304///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003305/// Three bits are used to represent the condition, as follows:
3306/// 0 A > B
3307/// 1 A == B
3308/// 2 A < B
3309///
3310/// <=> Value Definition
3311/// 000 0 Always false
3312/// 001 1 A > B
3313/// 010 2 A == B
3314/// 011 3 A >= B
3315/// 100 4 A < B
3316/// 101 5 A != B
3317/// 110 6 A <= B
3318/// 111 7 Always true
3319///
3320static unsigned getICmpCode(const ICmpInst *ICI) {
3321 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003322 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003323 case ICmpInst::ICMP_UGT: return 1; // 001
3324 case ICmpInst::ICMP_SGT: return 1; // 001
3325 case ICmpInst::ICMP_EQ: return 2; // 010
3326 case ICmpInst::ICMP_UGE: return 3; // 011
3327 case ICmpInst::ICMP_SGE: return 3; // 011
3328 case ICmpInst::ICMP_ULT: return 4; // 100
3329 case ICmpInst::ICMP_SLT: return 4; // 100
3330 case ICmpInst::ICMP_NE: return 5; // 101
3331 case ICmpInst::ICMP_ULE: return 6; // 110
3332 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003333 // True -> 7
3334 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003335 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003336 return 0;
3337 }
3338}
3339
Evan Cheng8db90722008-10-14 17:15:11 +00003340/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3341/// predicate into a three bit mask. It also returns whether it is an ordered
3342/// predicate by reference.
3343static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3344 isOrdered = false;
3345 switch (CC) {
3346 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3347 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003348 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3349 case FCmpInst::FCMP_UGT: return 1; // 001
3350 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3351 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003352 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3353 case FCmpInst::FCMP_UGE: return 3; // 011
3354 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3355 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003356 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3357 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003358 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3359 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003360 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003361 default:
3362 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003363 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003364 return 0;
3365 }
3366}
3367
Reid Spencere4d87aa2006-12-23 06:05:41 +00003368/// getICmpValue - This is the complement of getICmpCode, which turns an
3369/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003370/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003371/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003372static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003373 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003374 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003375 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersonb3056fa2009-07-21 18:03:38 +00003376 case 0: return Context->getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003377 case 1:
3378 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003379 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003380 else
Owen Anderson333c4002009-07-09 23:48:35 +00003381 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3382 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003383 case 3:
3384 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003385 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 else
Owen Anderson333c4002009-07-09 23:48:35 +00003387 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003388 case 4:
3389 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003390 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391 else
Owen Anderson333c4002009-07-09 23:48:35 +00003392 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3393 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394 case 6:
3395 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003396 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 else
Owen Anderson333c4002009-07-09 23:48:35 +00003398 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003399 case 7: return Context->getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003400 }
3401}
3402
Evan Cheng8db90722008-10-14 17:15:11 +00003403/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3404/// opcode and two operands into either a FCmp instruction. isordered is passed
3405/// in to determine which kind of predicate to use in the new fcmp instruction.
3406static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003407 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003408 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003409 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003410 case 0:
3411 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003412 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003413 else
Owen Anderson333c4002009-07-09 23:48:35 +00003414 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003415 case 1:
3416 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003417 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003418 else
Owen Anderson333c4002009-07-09 23:48:35 +00003419 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003420 case 2:
3421 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003422 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003423 else
Owen Anderson333c4002009-07-09 23:48:35 +00003424 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003425 case 3:
3426 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003428 else
Owen Anderson333c4002009-07-09 23:48:35 +00003429 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003430 case 4:
3431 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 else
Owen Anderson333c4002009-07-09 23:48:35 +00003434 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003435 case 5:
3436 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003438 else
Owen Anderson333c4002009-07-09 23:48:35 +00003439 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003440 case 6:
3441 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003443 else
Owen Anderson333c4002009-07-09 23:48:35 +00003444 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003445 case 7: return Context->getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003446 }
3447}
3448
Chris Lattnerb9553d62008-11-16 04:55:20 +00003449/// PredicatesFoldable - Return true if both predicates match sign or if at
3450/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3452 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003453 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3454 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003455}
3456
3457namespace {
3458// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3459struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003460 InstCombiner &IC;
3461 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003462 ICmpInst::Predicate pred;
3463 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3464 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3465 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003466 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3468 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003469 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3470 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003471 return false;
3472 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003473 Instruction *apply(Instruction &Log) const {
3474 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3475 if (ICI->getOperand(0) != LHS) {
3476 assert(ICI->getOperand(1) == LHS);
3477 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478 }
3479
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003480 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003481 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003482 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003483 unsigned Code;
3484 switch (Log.getOpcode()) {
3485 case Instruction::And: Code = LHSCode & RHSCode; break;
3486 case Instruction::Or: Code = LHSCode | RHSCode; break;
3487 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003488 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003489 }
3490
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003491 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3492 ICmpInst::isSignedPredicate(ICI->getPredicate());
3493
Owen Andersond672ecb2009-07-03 00:17:18 +00003494 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 if (Instruction *I = dyn_cast<Instruction>(RV))
3496 return I;
3497 // Otherwise, it's a constant boolean value...
3498 return IC.ReplaceInstUsesWith(Log, RV);
3499 }
3500};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003501} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003502
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003503// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3504// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003505// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003506Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003507 ConstantInt *OpRHS,
3508 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003509 BinaryOperator &TheAnd) {
3510 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003511 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003512 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003513 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003514
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515 switch (Op->getOpcode()) {
3516 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003517 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003519 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003521 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003522 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523 }
3524 break;
3525 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003526 if (Together == AndRHS) // (X | C) & C --> C
3527 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003528
Chris Lattner6e7ba452005-01-01 16:22:27 +00003529 if (Op->hasOneUse() && Together != OpRHS) {
3530 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003531 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003532 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003533 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003534 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535 }
3536 break;
3537 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003538 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003539 // Adding a one to a single bit bit-field should be turned into an XOR
3540 // of the bit. First thing to check is to see if this AND is with a
3541 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003542 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543
3544 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003545 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 // Ok, at this point, we know that we are masking the result of the
3547 // ADD down to exactly one bit. If the constant we are adding has
3548 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003549 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003550
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 // Check to see if any bits below the one bit set in AndRHSV are set.
3552 if ((AddRHS & (AndRHSV-1)) == 0) {
3553 // If not, the only thing that can effect the output of the AND is
3554 // the bit specified by AndRHSV. If that bit is set, the effect of
3555 // the XOR is to toggle the bit. If it is clear, then the ADD has
3556 // no effect.
3557 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3558 TheAnd.setOperand(0, X);
3559 return &TheAnd;
3560 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003564 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003566 }
3567 }
3568 }
3569 }
3570 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003571
3572 case Instruction::Shl: {
3573 // We know that the AND will not produce any of the bits shifted in, so if
3574 // the anded constant includes them, clear them now!
3575 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003576 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003577 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003578 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003579 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003580
Zhou Sheng290bec52007-03-29 08:15:12 +00003581 if (CI->getValue() == ShlMask) {
3582 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003583 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3584 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003585 TheAnd.setOperand(1, CI);
3586 return &TheAnd;
3587 }
3588 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003589 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003590 case Instruction::LShr:
3591 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003592 // We know that the AND will not produce any of the bits shifted in, so if
3593 // the anded constant includes them, clear them now! This only applies to
3594 // unsigned shifts, because a signed shr may bring in set bits!
3595 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003596 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003597 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003598 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003599 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003600
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 if (CI->getValue() == ShrMask) {
3602 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003603 return ReplaceInstUsesWith(TheAnd, Op);
3604 } else if (CI != AndRHS) {
3605 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3606 return &TheAnd;
3607 }
3608 break;
3609 }
3610 case Instruction::AShr:
3611 // Signed shr.
3612 // See if this is shifting in some sign extension, then masking it out
3613 // with an and.
3614 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003615 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003616 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003617 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003618 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003619 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003620 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003621 // Make the argument unsigned.
3622 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003623 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003624 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003625 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003626 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003627 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003628 }
3629 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003630 }
3631 return 0;
3632}
3633
Chris Lattner8b170942002-08-09 23:47:40 +00003634
Chris Lattnera96879a2004-09-29 17:40:11 +00003635/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3636/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003637/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3638/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003639/// insert new instructions.
3640Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641 bool isSigned, bool Inside,
3642 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003643 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003644 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003645 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646
Chris Lattnera96879a2004-09-29 17:40:11 +00003647 if (Inside) {
3648 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003649 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003650
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003652 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003653 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003655 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 }
3657
3658 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003659 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003660 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003661 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003662 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003663 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003664 }
3665
3666 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003667 return new ICmpInst(*Context, 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
Owen Andersond672ecb2009-07-03 00:17:18 +00003670 Hi = SubOne(cast<ConstantInt>(Hi), Context);
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);
Owen Anderson333c4002009-07-09 23:48:35 +00003674 return new ICmpInst(*Context, 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 Andersond672ecb2009-07-03 00:17:18 +00003679 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003680 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003681 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003682 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003683 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003684}
3685
Chris Lattner7203e152005-09-18 07:22:02 +00003686// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3687// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3688// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3689// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003690static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003691 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003692 uint32_t BitWidth = Val->getType()->getBitWidth();
3693 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003694
3695 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003696 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003697 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003698 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003699 return true;
3700}
3701
Chris Lattner7203e152005-09-18 07:22:02 +00003702/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3703/// where isSub determines whether the operator is a sub. If we can fold one of
3704/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003705///
3706/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3707/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3709///
3710/// return (A +/- B).
3711///
3712Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003713 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003714 Instruction &I) {
3715 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3716 if (!LHSI || LHSI->getNumOperands() != 2 ||
3717 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3718
3719 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3720
3721 switch (LHSI->getOpcode()) {
3722 default: return 0;
3723 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003724 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003725 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003726 if ((Mask->getValue().countLeadingZeros() +
3727 Mask->getValue().countPopulation()) ==
3728 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003729 break;
3730
3731 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3732 // part, we don't need any explicit masks to take them out of A. If that
3733 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003734 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003735 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003736 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003737 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003738 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003739 break;
3740 }
3741 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003742 return 0;
3743 case Instruction::Or:
3744 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003745 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003746 if ((Mask->getValue().countLeadingZeros() +
3747 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003748 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003749 break;
3750 return 0;
3751 }
3752
3753 Instruction *New;
3754 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003755 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003757 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003758 return InsertNewInstBefore(New, I);
3759}
3760
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003761/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3762Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3763 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003764 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003765 ConstantInt *LHSCst, *RHSCst;
3766 ICmpInst::Predicate LHSCC, RHSCC;
3767
Chris Lattnerea065fb2008-11-16 05:10:52 +00003768 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003769 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3770 m_ConstantInt(LHSCst)), *Context) ||
3771 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3772 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003773 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003774
3775 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3776 // where C is a power of 2
3777 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3778 LHSCst->getValue().isPowerOf2()) {
3779 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3780 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003781 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003782 }
3783
3784 // From here on, we only handle:
3785 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3786 if (Val != Val2) return 0;
3787
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003788 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3789 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3790 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3791 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3792 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3793 return 0;
3794
3795 // We can't fold (ugt x, C) & (sgt x, C2).
3796 if (!PredicatesFoldable(LHSCC, RHSCC))
3797 return 0;
3798
3799 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003800 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003801 if (ICmpInst::isSignedPredicate(LHSCC) ||
3802 (ICmpInst::isEquality(LHSCC) &&
3803 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003804 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003805 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003806 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3807
3808 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003809 std::swap(LHS, RHS);
3810 std::swap(LHSCst, RHSCst);
3811 std::swap(LHSCC, RHSCC);
3812 }
3813
3814 // At this point, we know we have have two icmp instructions
3815 // comparing a value against two constants and and'ing the result
3816 // together. Because of the above check, we know that we only have
3817 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3818 // (from the FoldICmpLogical check above), that the two constants
3819 // are not equal and that the larger constant is on the RHS
3820 assert(LHSCst != RHSCst && "Compares not folded above?");
3821
3822 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003823 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003824 case ICmpInst::ICMP_EQ:
3825 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003826 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003827 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3828 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3829 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003830 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003831 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3832 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3833 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3834 return ReplaceInstUsesWith(I, LHS);
3835 }
3836 case ICmpInst::ICMP_NE:
3837 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003838 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003839 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003840 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003841 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003842 break; // (X != 13 & X u< 15) -> no change
3843 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003844 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003845 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003846 break; // (X != 13 & X s< 15) -> no change
3847 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3848 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3849 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3850 return ReplaceInstUsesWith(I, RHS);
3851 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003852 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3853 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003854 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3855 Val->getName()+".off");
3856 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003857 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003858 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 }
3860 break; // (X != 13 & X != 15) -> no change
3861 }
3862 break;
3863 case ICmpInst::ICMP_ULT:
3864 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003865 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003866 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3867 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003868 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003869 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3870 break;
3871 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3872 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3873 return ReplaceInstUsesWith(I, LHS);
3874 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3875 break;
3876 }
3877 break;
3878 case ICmpInst::ICMP_SLT:
3879 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003880 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3882 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003883 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003884 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3885 break;
3886 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3887 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3888 return ReplaceInstUsesWith(I, LHS);
3889 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3890 break;
3891 }
3892 break;
3893 case ICmpInst::ICMP_UGT:
3894 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003895 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003896 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3897 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3898 return ReplaceInstUsesWith(I, RHS);
3899 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3900 break;
3901 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003902 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003903 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003904 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003905 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003906 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3907 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003908 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3909 break;
3910 }
3911 break;
3912 case ICmpInst::ICMP_SGT:
3913 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003914 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003915 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3916 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3917 return ReplaceInstUsesWith(I, RHS);
3918 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3919 break;
3920 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003921 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003922 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003923 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003924 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003925 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3926 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003927 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3928 break;
3929 }
3930 break;
3931 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003932
3933 return 0;
3934}
3935
Chris Lattner42d1be02009-07-23 05:14:02 +00003936Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3937 FCmpInst *RHS) {
3938
3939 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3940 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3941 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3942 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3943 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3944 // If either of the constants are nans, then the whole thing returns
3945 // false.
3946 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3947 return ReplaceInstUsesWith(I, Context->getFalse());
3948 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3949 LHS->getOperand(0), RHS->getOperand(0));
3950 }
3951 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)
3968 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3969
3970 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3971 return ReplaceInstUsesWith(I, Context->getFalse());
3972 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)
3995 return ReplaceInstUsesWith(I, Context->getFalse());
3996 // 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 Andersond672ecb2009-07-03 00:17:18 +00004011 return ReplaceInstUsesWith(I, Context->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.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004046 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004047 Op0RHS->getName()+".masked");
4048 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004049 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004050 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004051 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004052 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004053 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4054 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004055 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004056 Op0LHS->getName()+".masked");
4057 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004058 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004059 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4060 }
4061 }
4062
Chris Lattner6e7ba452005-01-01 16:22:27 +00004063 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004064 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004065 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4066 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4067 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4068 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004069 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004070 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004071 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004072 break;
4073
4074 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004075 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4076 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4077 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4078 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004080
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004081 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4082 // has 1's for all bits that the subtraction with A might affect.
4083 if (Op0I->hasOneUse()) {
4084 uint32_t BitWidth = AndRHSMask.getBitWidth();
4085 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4086 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4087
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004088 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004089 if (!(A && A->isZero()) && // avoid infinite recursion.
4090 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004091 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004092 InsertNewInstBefore(NewNeg, I);
4093 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4094 }
4095 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004096 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004097
4098 case Instruction::Shl:
4099 case Instruction::LShr:
4100 // (1 << x) & 1 --> zext(x == 0)
4101 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004102 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004103 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4104 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004105 InsertNewInstBefore(NewICmp, I);
4106 return new ZExtInst(NewICmp, I.getType());
4107 }
4108 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004109 }
4110
Chris Lattner58403262003-07-23 19:25:52 +00004111 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004112 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004113 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004114 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004115 // If this is an integer truncation or change from signed-to-unsigned, and
4116 // if the source is an and/or with immediate, transform it. This
4117 // frequently occurs for bitfield accesses.
4118 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004119 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004120 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004121 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004122 if (CastOp->getOpcode() == Instruction::And) {
4123 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004124 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4125 // This will fold the two constants together, which may allow
4126 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004127 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004128 CastOp->getOperand(0), I.getType(),
4129 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004130 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004131 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004132 Constant *C3 =
4133 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4134 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004136 } else if (CastOp->getOpcode() == Instruction::Or) {
4137 // Change: and (cast (or X, C1) to T), C2
4138 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004139 Constant *C3 =
4140 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4141 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4142 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004143 return ReplaceInstUsesWith(I, AndRHS);
4144 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004145 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004146 }
Chris Lattner06782f82003-07-23 19:36:21 +00004147 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004148
4149 // Try to fold constant and into select arguments.
4150 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004151 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004152 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004153 if (isa<PHINode>(Op0))
4154 if (Instruction *NV = FoldOpIntoPhi(I))
4155 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004156 }
4157
Owen Andersond672ecb2009-07-03 00:17:18 +00004158 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4159 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004160
Chris Lattner5b62aa72004-06-18 06:07:51 +00004161 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004162 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004163
Misha Brukmancb6267b2004-07-30 12:50:08 +00004164 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004165 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004166 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004167 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004168 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004169 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004170 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004171
4172 {
Chris Lattner003b6202007-06-15 05:58:24 +00004173 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004174 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004175 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4176 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004177
4178 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004179 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004180 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004181 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004182 }
4183 }
4184
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004185 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004186 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4187 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004188
4189 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004190 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004191 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004192 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004193 }
4194 }
Chris Lattner64daab52006-04-01 08:03:55 +00004195
4196 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004197 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004198 if (A == Op1) { // (A^B)&A -> A&(A^B)
4199 I.swapOperands(); // Simplify below
4200 std::swap(Op0, Op1);
4201 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4202 cast<BinaryOperator>(Op0)->swapOperands();
4203 I.swapOperands(); // Simplify below
4204 std::swap(Op0, Op1);
4205 }
4206 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004207
Chris Lattner64daab52006-04-01 08:03:55 +00004208 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004209 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004210 if (B == Op0) { // B&(A^B) -> B&(B^A)
4211 cast<BinaryOperator>(Op1)->swapOperands();
4212 std::swap(A, B);
4213 }
4214 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004215 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004216 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004217 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004218 }
4219 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004220
4221 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004222 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4223 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004224 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004225 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4226 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004227 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004228 }
4229
Reid Spencere4d87aa2006-12-23 06:05:41 +00004230 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4231 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004232 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004233 return R;
4234
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004235 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4236 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4237 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004238 }
4239
Chris Lattner6fc205f2006-05-05 06:39:07 +00004240 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004241 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4242 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4243 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4244 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004245 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004246 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004247 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4248 I.getType(), TD) &&
4249 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4250 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004251 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004252 Op1C->getOperand(0),
4253 I.getName());
4254 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004255 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004256 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004257 }
Chris Lattnere511b742006-11-14 07:46:50 +00004258
4259 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004260 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4261 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4262 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004263 SI0->getOperand(1) == SI1->getOperand(1) &&
4264 (SI0->hasOneUse() || SI1->hasOneUse())) {
4265 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004266 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004267 SI1->getOperand(0),
4268 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004269 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004270 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004271 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004272 }
4273
Evan Cheng8db90722008-10-14 17:15:11 +00004274 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004275 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004276 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4277 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4278 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004279 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004280
Chris Lattner7e708292002-06-25 16:13:24 +00004281 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004282}
4283
Chris Lattner8c34cd22008-10-05 02:13:19 +00004284/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4285/// capable of providing pieces of a bswap. The subexpression provides pieces
4286/// of a bswap if it is proven that each of the non-zero bytes in the output of
4287/// the expression came from the corresponding "byte swapped" byte in some other
4288/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4289/// we know that the expression deposits the low byte of %X into the high byte
4290/// of the bswap result and that all other bytes are zero. This expression is
4291/// accepted, the high byte of ByteValues is set to X to indicate a correct
4292/// match.
4293///
4294/// This function returns true if the match was unsuccessful and false if so.
4295/// On entry to the function the "OverallLeftShift" is a signed integer value
4296/// indicating the number of bytes that the subexpression is later shifted. For
4297/// example, if the expression is later right shifted by 16 bits, the
4298/// OverallLeftShift value would be -2 on entry. This is used to specify which
4299/// byte of ByteValues is actually being set.
4300///
4301/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4302/// byte is masked to zero by a user. For example, in (X & 255), X will be
4303/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4304/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4305/// always in the local (OverallLeftShift) coordinate space.
4306///
4307static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4308 SmallVector<Value*, 8> &ByteValues) {
4309 if (Instruction *I = dyn_cast<Instruction>(V)) {
4310 // If this is an or instruction, it may be an inner node of the bswap.
4311 if (I->getOpcode() == Instruction::Or) {
4312 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4313 ByteValues) ||
4314 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4315 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004316 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004317
4318 // If this is a logical shift by a constant multiple of 8, recurse with
4319 // OverallLeftShift and ByteMask adjusted.
4320 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4321 unsigned ShAmt =
4322 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4323 // Ensure the shift amount is defined and of a byte value.
4324 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4325 return true;
4326
4327 unsigned ByteShift = ShAmt >> 3;
4328 if (I->getOpcode() == Instruction::Shl) {
4329 // X << 2 -> collect(X, +2)
4330 OverallLeftShift += ByteShift;
4331 ByteMask >>= ByteShift;
4332 } else {
4333 // X >>u 2 -> collect(X, -2)
4334 OverallLeftShift -= ByteShift;
4335 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004336 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004337 }
4338
4339 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4340 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4341
4342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4343 ByteValues);
4344 }
4345
4346 // If this is a logical 'and' with a mask that clears bytes, clear the
4347 // corresponding bytes in ByteMask.
4348 if (I->getOpcode() == Instruction::And &&
4349 isa<ConstantInt>(I->getOperand(1))) {
4350 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4351 unsigned NumBytes = ByteValues.size();
4352 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4353 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4354
4355 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4356 // If this byte is masked out by a later operation, we don't care what
4357 // the and mask is.
4358 if ((ByteMask & (1 << i)) == 0)
4359 continue;
4360
4361 // If the AndMask is all zeros for this byte, clear the bit.
4362 APInt MaskB = AndMask & Byte;
4363 if (MaskB == 0) {
4364 ByteMask &= ~(1U << i);
4365 continue;
4366 }
4367
4368 // If the AndMask is not all ones for this byte, it's not a bytezap.
4369 if (MaskB != Byte)
4370 return true;
4371
4372 // Otherwise, this byte is kept.
4373 }
4374
4375 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4376 ByteValues);
4377 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004378 }
4379
Chris Lattner8c34cd22008-10-05 02:13:19 +00004380 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4381 // the input value to the bswap. Some observations: 1) if more than one byte
4382 // is demanded from this input, then it could not be successfully assembled
4383 // into a byteswap. At least one of the two bytes would not be aligned with
4384 // their ultimate destination.
4385 if (!isPowerOf2_32(ByteMask)) return true;
4386 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004387
Chris Lattner8c34cd22008-10-05 02:13:19 +00004388 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4389 // is demanded, it needs to go into byte 0 of the result. This means that the
4390 // byte needs to be shifted until it lands in the right byte bucket. The
4391 // shift amount depends on the position: if the byte is coming from the high
4392 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4393 // low part, it must be shifted left.
4394 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4395 if (InputByteNo < ByteValues.size()/2) {
4396 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4397 return true;
4398 } else {
4399 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4400 return true;
4401 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004402
4403 // If the destination byte value is already defined, the values are or'd
4404 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004405 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004406 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004407 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004408 return false;
4409}
4410
4411/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4412/// If so, insert the new bswap intrinsic and return it.
4413Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004414 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004415 if (!ITy || ITy->getBitWidth() % 16 ||
4416 // ByteMask only allows up to 32-byte values.
4417 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004418 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004419
4420 /// ByteValues - For each byte of the result, we keep track of which value
4421 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004422 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004423 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004424
4425 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004426 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4427 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428 return 0;
4429
4430 // Check to see if all of the bytes come from the same value.
4431 Value *V = ByteValues[0];
4432 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4433
4434 // Check to make sure that all of the bytes come from the same value.
4435 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4436 if (ByteValues[i] != V)
4437 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004438 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004439 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004440 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004441 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442}
4443
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004444/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4445/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4446/// we can simplify this expression to "cond ? C : D or B".
4447static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004448 Value *C, Value *D,
4449 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004450 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004451 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004452 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004453 return 0;
4454
Chris Lattnera6a474d2008-11-16 04:26:55 +00004455 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004456 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004457 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004458 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004459 return SelectInst::Create(Cond, C, B);
4460 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004461 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004462 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004463 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004464 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004465 return 0;
4466}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004467
Chris Lattner69d4ced2008-11-16 05:20:07 +00004468/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4469Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4470 ICmpInst *LHS, ICmpInst *RHS) {
4471 Value *Val, *Val2;
4472 ConstantInt *LHSCst, *RHSCst;
4473 ICmpInst::Predicate LHSCC, RHSCC;
4474
4475 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004476 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4477 m_ConstantInt(LHSCst)), *Context) ||
4478 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4479 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004480 return 0;
4481
4482 // From here on, we only handle:
4483 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4484 if (Val != Val2) return 0;
4485
4486 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4487 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4488 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4489 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4490 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4491 return 0;
4492
4493 // We can't fold (ugt x, C) | (sgt x, C2).
4494 if (!PredicatesFoldable(LHSCC, RHSCC))
4495 return 0;
4496
4497 // Ensure that the larger constant is on the RHS.
4498 bool ShouldSwap;
4499 if (ICmpInst::isSignedPredicate(LHSCC) ||
4500 (ICmpInst::isEquality(LHSCC) &&
4501 ICmpInst::isSignedPredicate(RHSCC)))
4502 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4503 else
4504 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4505
4506 if (ShouldSwap) {
4507 std::swap(LHS, RHS);
4508 std::swap(LHSCst, RHSCst);
4509 std::swap(LHSCC, RHSCC);
4510 }
4511
4512 // At this point, we know we have have two icmp instructions
4513 // comparing a value against two constants and or'ing the result
4514 // together. Because of the above check, we know that we only have
4515 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4516 // FoldICmpLogical check above), that the two constants are not
4517 // equal.
4518 assert(LHSCst != RHSCst && "Compares not folded above?");
4519
4520 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004521 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004522 case ICmpInst::ICMP_EQ:
4523 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004524 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004525 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004526 if (LHSCst == SubOne(RHSCst, Context)) {
4527 // (X == 13 | X == 14) -> X-13 <u 2
4528 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004529 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4530 Val->getName()+".off");
4531 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004532 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004533 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004534 }
4535 break; // (X == 13 | X == 15) -> no change
4536 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4537 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4538 break;
4539 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4540 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4541 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4542 return ReplaceInstUsesWith(I, RHS);
4543 }
4544 break;
4545 case ICmpInst::ICMP_NE:
4546 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004547 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004548 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4549 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4550 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4551 return ReplaceInstUsesWith(I, LHS);
4552 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4553 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4554 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004555 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004556 }
4557 break;
4558 case ICmpInst::ICMP_ULT:
4559 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004560 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004561 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4562 break;
4563 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4564 // If RHSCst is [us]MAXINT, it is always false. Not handling
4565 // this can cause overflow.
4566 if (RHSCst->isMaxValue(false))
4567 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004568 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4569 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004570 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4571 break;
4572 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4573 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4574 return ReplaceInstUsesWith(I, RHS);
4575 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4576 break;
4577 }
4578 break;
4579 case ICmpInst::ICMP_SLT:
4580 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004581 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004582 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4583 break;
4584 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4585 // If RHSCst is [us]MAXINT, it is always false. Not handling
4586 // this can cause overflow.
4587 if (RHSCst->isMaxValue(true))
4588 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004589 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4590 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004591 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4592 break;
4593 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4594 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4595 return ReplaceInstUsesWith(I, RHS);
4596 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4597 break;
4598 }
4599 break;
4600 case ICmpInst::ICMP_UGT:
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 u> 13 | X == 15) -> X u> 13
4604 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4605 return ReplaceInstUsesWith(I, LHS);
4606 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4607 break;
4608 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4609 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004610 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004611 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4612 break;
4613 }
4614 break;
4615 case ICmpInst::ICMP_SGT:
4616 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004617 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004618 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4619 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4620 return ReplaceInstUsesWith(I, LHS);
4621 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4622 break;
4623 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4624 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004625 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004626 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4627 break;
4628 }
4629 break;
4630 }
4631 return 0;
4632}
4633
Bill Wendlinga698a472008-12-01 08:23:25 +00004634/// FoldOrWithConstants - This helper function folds:
4635///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004636/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004637///
4638/// into:
4639///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004640/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004641///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004642/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004643Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004644 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004645 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4646 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004647
Bill Wendling286a0542008-12-02 06:24:20 +00004648 Value *V1 = 0;
4649 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004650 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004651
Bill Wendling29976b92008-12-02 06:18:11 +00004652 APInt Xor = CI1->getValue() ^ CI2->getValue();
4653 if (!Xor.isAllOnesValue()) return 0;
4654
Bill Wendling286a0542008-12-02 06:24:20 +00004655 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004656 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004657 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4658 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004659 }
4660
4661 return 0;
4662}
4663
Chris Lattner7e708292002-06-25 16:13:24 +00004664Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004665 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004666 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004667
Chris Lattner42593e62007-03-24 23:56:43 +00004668 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004669 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004670
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004671 // or X, X = X
4672 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004673 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004674
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004675 // See if we can simplify any instructions used by the instruction whose sole
4676 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004677 if (SimplifyDemandedInstructionBits(I))
4678 return &I;
4679 if (isa<VectorType>(I.getType())) {
4680 if (isa<ConstantAggregateZero>(Op1)) {
4681 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4682 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4683 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4684 return ReplaceInstUsesWith(I, I.getOperand(1));
4685 }
Chris Lattner42593e62007-03-24 23:56:43 +00004686 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004687
Chris Lattner3f5b8772002-05-06 16:14:14 +00004688 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004689 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004690 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004691 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004692 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4693 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004694 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004695 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004696 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004697 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004698 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004699 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004700
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004701 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004702 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4703 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004704 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004705 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004706 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004707 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004708 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004709 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004710
4711 // Try to fold constant and into select arguments.
4712 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004713 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004714 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004715 if (isa<PHINode>(Op0))
4716 if (Instruction *NV = FoldOpIntoPhi(I))
4717 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004718 }
4719
Chris Lattner4f637d42006-01-06 17:59:59 +00004720 Value *A = 0, *B = 0;
4721 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004722
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004723 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004724 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4725 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004726 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004727 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4728 return ReplaceInstUsesWith(I, Op0);
4729
Chris Lattner6423d4c2006-07-10 20:25:24 +00004730 // (A | B) | C and A | (B | C) -> bswap if possible.
4731 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004732 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4733 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4734 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4735 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004736 if (Instruction *BSwap = MatchBSwap(I))
4737 return BSwap;
4738 }
4739
Chris Lattner6e4c6492005-05-09 04:58:36 +00004740 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004741 if (Op0->hasOneUse() &&
4742 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004743 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004744 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004745 InsertNewInstBefore(NOr, I);
4746 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004747 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004748 }
4749
4750 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004751 if (Op1->hasOneUse() &&
4752 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004753 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004754 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004755 InsertNewInstBefore(NOr, I);
4756 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004757 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004758 }
4759
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004760 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004761 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004762 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4763 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004764 Value *V1 = 0, *V2 = 0, *V3 = 0;
4765 C1 = dyn_cast<ConstantInt>(C);
4766 C2 = dyn_cast<ConstantInt>(D);
4767 if (C1 && C2) { // (A & C1)|(B & C2)
4768 // If we have: ((V + N) & C1) | (V & C2)
4769 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4770 // replace with V+N.
4771 if (C1->getValue() == ~C2->getValue()) {
4772 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004773 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004774 // Add commutes, try both ways.
4775 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4776 return ReplaceInstUsesWith(I, A);
4777 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4778 return ReplaceInstUsesWith(I, A);
4779 }
4780 // Or commutes, try both ways.
4781 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004782 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004783 // Add commutes, try both ways.
4784 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4785 return ReplaceInstUsesWith(I, B);
4786 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4787 return ReplaceInstUsesWith(I, B);
4788 }
4789 }
Chris Lattner044e5332007-04-08 08:01:49 +00004790 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004791 }
4792
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004793 // Check to see if we have any common things being and'ed. If so, find the
4794 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004795 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4796 if (A == B) // (A & C)|(A & D) == A & (C|D)
4797 V1 = A, V2 = C, V3 = D;
4798 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4799 V1 = A, V2 = B, V3 = C;
4800 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4801 V1 = C, V2 = A, V3 = D;
4802 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4803 V1 = C, V2 = A, V3 = B;
4804
4805 if (V1) {
4806 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004807 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4808 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004809 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004810 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004811
Dan Gohman1975d032008-10-30 20:40:10 +00004812 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004813 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004814 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004815 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004816 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004817 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004818 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004819 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004820 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004821
Bill Wendlingb01865c2008-11-30 13:52:49 +00004822 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004823 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4824 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004825 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004826 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004827 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4828 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004829 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004830 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004831 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4832 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004833 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004834 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004835 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4836 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004837 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004838 }
Chris Lattnere511b742006-11-14 07:46:50 +00004839
4840 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004841 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4842 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4843 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004844 SI0->getOperand(1) == SI1->getOperand(1) &&
4845 (SI0->hasOneUse() || SI1->hasOneUse())) {
4846 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004847 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004848 SI1->getOperand(0),
4849 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004850 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004851 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004852 }
4853 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004854
Bill Wendlingb3833d12008-12-01 01:07:11 +00004855 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004856 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4857 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004858 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004859 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004860 }
4861 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004862 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4863 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004864 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004865 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004866 }
4867
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004868 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004869 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004870 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004871 } else {
4872 A = 0;
4873 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004874 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004875 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004876 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004877 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004878
Misha Brukmancb6267b2004-07-30 12:50:08 +00004879 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004880 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004881 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004882 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004883 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004884 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004885 }
Chris Lattnera2881962003-02-18 19:28:33 +00004886
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4888 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004889 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004890 return R;
4891
Chris Lattner69d4ced2008-11-16 05:20:07 +00004892 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4893 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4894 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004895 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004896
4897 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004898 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004899 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004900 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004901 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4902 !isa<ICmpInst>(Op1C->getOperand(0))) {
4903 const Type *SrcTy = Op0C->getOperand(0)->getType();
4904 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4905 // Only do this if the casts both really cause code to be
4906 // generated.
4907 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4908 I.getType(), TD) &&
4909 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4910 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004911 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004912 Op1C->getOperand(0),
4913 I.getName());
4914 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004915 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004916 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004917 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004918 }
Chris Lattner99c65742007-10-24 05:38:08 +00004919 }
4920
4921
4922 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4923 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4924 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4925 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004926 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004927 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004928 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4929 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4930 // If either of the constants are nans, then the whole thing returns
4931 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004932 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb3056fa2009-07-21 18:03:38 +00004933 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004934
4935 // Otherwise, no need to compare the two constants, compare the
4936 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004937 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4938 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004939 }
Evan Cheng40300622008-10-14 18:44:08 +00004940 } else {
4941 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4942 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004943 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4944 m_Value(Op0RHS)), *Context) &&
4945 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4946 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004947 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4948 // Swap RHS operands to match LHS.
4949 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4950 std::swap(Op1LHS, Op1RHS);
4951 }
4952 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4953 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4954 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004955 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4956 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004957 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4958 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004959 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004960 else if (Op0CC == FCmpInst::FCMP_FALSE)
4961 return ReplaceInstUsesWith(I, Op1);
4962 else if (Op1CC == FCmpInst::FCMP_FALSE)
4963 return ReplaceInstUsesWith(I, Op0);
4964 bool Op0Ordered;
4965 bool Op1Ordered;
4966 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4967 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4968 if (Op0Ordered == Op1Ordered) {
4969 // If both are ordered or unordered, return a new fcmp with
4970 // or'ed predicates.
4971 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004972 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004973 if (Instruction *I = dyn_cast<Instruction>(RV))
4974 return I;
4975 // Otherwise, it's a constant boolean value...
4976 return ReplaceInstUsesWith(I, RV);
4977 }
4978 }
4979 }
4980 }
Chris Lattner99c65742007-10-24 05:38:08 +00004981 }
4982 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004983
Chris Lattner7e708292002-06-25 16:13:24 +00004984 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004985}
4986
Dan Gohman844731a2008-05-13 00:00:25 +00004987namespace {
4988
Chris Lattnerc317d392004-02-16 01:20:27 +00004989// XorSelf - Implements: X ^ X --> 0
4990struct XorSelf {
4991 Value *RHS;
4992 XorSelf(Value *rhs) : RHS(rhs) {}
4993 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4994 Instruction *apply(BinaryOperator &Xor) const {
4995 return &Xor;
4996 }
4997};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004998
Dan Gohman844731a2008-05-13 00:00:25 +00004999}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005000
Chris Lattner7e708292002-06-25 16:13:24 +00005001Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005002 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005003 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005004
Evan Chengd34af782008-03-25 20:07:13 +00005005 if (isa<UndefValue>(Op1)) {
5006 if (isa<UndefValue>(Op0))
5007 // Handle undef ^ undef -> 0 special case. This is a common
5008 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005009 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005010 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005011 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005012
Chris Lattnerc317d392004-02-16 01:20:27 +00005013 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005014 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005015 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005016 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005017 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005018
5019 // See if we can simplify any instructions used by the instruction whose sole
5020 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005021 if (SimplifyDemandedInstructionBits(I))
5022 return &I;
5023 if (isa<VectorType>(I.getType()))
5024 if (isa<ConstantAggregateZero>(Op1))
5025 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005026
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005027 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005028 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005029 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5030 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5031 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5032 if (Op0I->getOpcode() == Instruction::And ||
5033 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005034 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5035 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005036 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005037 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005038 Op0I->getOperand(1)->getName()+".not");
5039 InsertNewInstBefore(NotY, I);
5040 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005041 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005042 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005043 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005044 }
5045 }
5046 }
5047 }
5048
5049
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005050 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00005051 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005052 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005053 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005054 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005055 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005056
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005057 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005058 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005059 FCI->getOperand(0), FCI->getOperand(1));
5060 }
5061
Nick Lewycky517e1f52008-05-31 19:01:33 +00005062 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5063 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5064 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5065 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5066 Instruction::CastOps Opcode = Op0C->getOpcode();
5067 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005068 if (RHS == Context->getConstantExprCast(Opcode,
Owen Andersonb3056fa2009-07-21 18:03:38 +00005069 Context->getTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005070 Op0C->getDestTy())) {
5071 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005072 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005073 CI->getOpcode(), CI->getInversePredicate(),
5074 CI->getOperand(0), CI->getOperand(1)), I);
5075 NewCI->takeName(CI);
5076 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5077 }
5078 }
5079 }
5080 }
5081 }
5082
Reid Spencere4d87aa2006-12-23 06:05:41 +00005083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005084 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005085 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5086 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005087 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5088 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5089 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005090 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005091 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005092
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005093 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005094 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005095 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005096 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005097 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005098 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005099 Context->getConstantExprSub(NegOp0CI,
5100 Context->getConstantInt(I.getType(), 1)),
5101 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005102 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005103 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005104 Constant *C =
5105 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005106 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005107
Chris Lattner7c4049c2004-01-12 19:35:11 +00005108 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005109 } else if (Op0I->getOpcode() == Instruction::Or) {
5110 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005111 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005112 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005113 // Anything in both C1 and C2 is known to be zero, remove it from
5114 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005115 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5116 NewRHS = Context->getConstantExprAnd(NewRHS,
5117 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005118 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005119 I.setOperand(0, Op0I->getOperand(0));
5120 I.setOperand(1, NewRHS);
5121 return &I;
5122 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005123 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005124 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005125 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005126
5127 // Try to fold constant and into select arguments.
5128 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005129 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005130 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005131 if (isa<PHINode>(Op0))
5132 if (Instruction *NV = FoldOpIntoPhi(I))
5133 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005134 }
5135
Owen Andersond672ecb2009-07-03 00:17:18 +00005136 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005137 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005138 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005139
Owen Andersond672ecb2009-07-03 00:17:18 +00005140 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005141 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005142 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005143
Chris Lattner318bf792007-03-18 22:51:34 +00005144
5145 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5146 if (Op1I) {
5147 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005148 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005149 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005150 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005151 I.swapOperands();
5152 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005153 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005154 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005155 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005156 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005157 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005158 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005159 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005160 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005161 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5162 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005163 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005164 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005165 std::swap(A, B);
5166 }
Chris Lattner318bf792007-03-18 22:51:34 +00005167 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005168 I.swapOperands(); // Simplified below.
5169 std::swap(Op0, Op1);
5170 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005171 }
Chris Lattner318bf792007-03-18 22:51:34 +00005172 }
5173
5174 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5175 if (Op0I) {
5176 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005177 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5178 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005179 if (A == Op1) // (B|A)^B == (A|B)^B
5180 std::swap(A, B);
5181 if (B == Op1) { // (A|B)^B == A & ~B
5182 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005183 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5184 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005185 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005186 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005187 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005188 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005189 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005190 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005191 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5192 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005193 if (A == Op1) // (A&B)^A -> (B&A)^A
5194 std::swap(A, B);
5195 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005196 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005197 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005198 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005199 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005200 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005201 }
Chris Lattner318bf792007-03-18 22:51:34 +00005202 }
5203
5204 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5205 if (Op0I && Op1I && Op0I->isShift() &&
5206 Op0I->getOpcode() == Op1I->getOpcode() &&
5207 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5208 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5209 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005210 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005211 Op1I->getOperand(0),
5212 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005213 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005214 Op1I->getOperand(1));
5215 }
5216
5217 if (Op0I && Op1I) {
5218 Value *A, *B, *C, *D;
5219 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005220 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5221 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005222 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005223 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005224 }
5225 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005226 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5227 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005228 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005229 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005230 }
5231
5232 // (A & B)^(C & D)
5233 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005234 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5235 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005236 // (X & Y)^(X & Y) -> (Y^Z) & X
5237 Value *X = 0, *Y = 0, *Z = 0;
5238 if (A == C)
5239 X = A, Y = B, Z = D;
5240 else if (A == D)
5241 X = A, Y = B, Z = C;
5242 else if (B == C)
5243 X = B, Y = A, Z = D;
5244 else if (B == D)
5245 X = B, Y = A, Z = C;
5246
5247 if (X) {
5248 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005249 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5250 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005251 }
5252 }
5253 }
5254
Reid Spencere4d87aa2006-12-23 06:05:41 +00005255 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5256 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005257 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005258 return R;
5259
Chris Lattner6fc205f2006-05-05 06:39:07 +00005260 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005261 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005262 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005263 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5264 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005265 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005266 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005267 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5268 I.getType(), TD) &&
5269 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5270 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005271 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005272 Op1C->getOperand(0),
5273 I.getName());
5274 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005275 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005276 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005277 }
Chris Lattner99c65742007-10-24 05:38:08 +00005278 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005279
Chris Lattner7e708292002-06-25 16:13:24 +00005280 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005281}
5282
Owen Andersond672ecb2009-07-03 00:17:18 +00005283static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005284 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005285 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005286}
Chris Lattnera96879a2004-09-29 17:40:11 +00005287
Dan Gohman6de29f82009-06-15 22:12:54 +00005288static bool HasAddOverflow(ConstantInt *Result,
5289 ConstantInt *In1, ConstantInt *In2,
5290 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005291 if (IsSigned)
5292 if (In2->getValue().isNegative())
5293 return Result->getValue().sgt(In1->getValue());
5294 else
5295 return Result->getValue().slt(In1->getValue());
5296 else
5297 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005298}
5299
Dan Gohman6de29f82009-06-15 22:12:54 +00005300/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005301/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005302static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005303 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005304 bool IsSigned = false) {
5305 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005306
Dan Gohman6de29f82009-06-15 22:12:54 +00005307 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5308 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005309 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5310 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5311 ExtractElement(In1, Idx, Context),
5312 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005313 IsSigned))
5314 return true;
5315 }
5316 return false;
5317 }
5318
5319 return HasAddOverflow(cast<ConstantInt>(Result),
5320 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5321 IsSigned);
5322}
5323
5324static bool HasSubOverflow(ConstantInt *Result,
5325 ConstantInt *In1, ConstantInt *In2,
5326 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005327 if (IsSigned)
5328 if (In2->getValue().isNegative())
5329 return Result->getValue().slt(In1->getValue());
5330 else
5331 return Result->getValue().sgt(In1->getValue());
5332 else
5333 return Result->getValue().ugt(In1->getValue());
5334}
5335
Dan Gohman6de29f82009-06-15 22:12:54 +00005336/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5337/// overflowed for this type.
5338static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005339 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005340 bool IsSigned = false) {
5341 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005342
5343 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5344 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005345 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5346 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5347 ExtractElement(In1, Idx, Context),
5348 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005349 IsSigned))
5350 return true;
5351 }
5352 return false;
5353 }
5354
5355 return HasSubOverflow(cast<ConstantInt>(Result),
5356 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5357 IsSigned);
5358}
5359
Chris Lattner574da9b2005-01-13 20:14:25 +00005360/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5361/// code necessary to compute the offset from the base pointer (without adding
5362/// in the base pointer). Return the result as a signed integer of intptr size.
5363static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005364 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005365 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005366 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005367 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005368 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005369
5370 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005371 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005372 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005373
Gabor Greif177dd3f2008-06-12 21:37:33 +00005374 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5375 ++i, ++GTI) {
5376 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005377 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005378 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5379 if (OpC->isZero()) continue;
5380
5381 // Handle a struct index, which adds its field offset to the pointer.
5382 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5383 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5384
5385 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005386 Result =
5387 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005388 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005389 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005390 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005391 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005392 GEP->getName()+".offs"), I);
5393 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005394 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005395
Owen Andersond672ecb2009-07-03 00:17:18 +00005396 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5397 Constant *OC =
5398 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5399 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005400 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005401 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005402 else {
5403 // Emit an add instruction.
5404 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005405 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005406 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005407 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005408 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005409 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005410 // Convert to correct type.
5411 if (Op->getType() != IntPtrTy) {
5412 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005413 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005414 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005415 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5416 true,
5417 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005418 }
5419 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005420 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005421 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005422 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005424 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005425 GEP->getName()+".idx"), I);
5426 }
5427
5428 // Emit an add instruction.
5429 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005430 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005431 cast<Constant>(Result));
5432 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005433 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005434 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005435 }
5436 return Result;
5437}
5438
Chris Lattner10c0d912008-04-22 02:53:33 +00005439
Dan Gohman8f080f02009-07-17 22:16:21 +00005440/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5441/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5442/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5443/// be complex, and scales are involved. The above expression would also be
5444/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5445/// This later form is less amenable to optimization though, and we are allowed
5446/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005447///
5448/// If we can't emit an optimized form for this expression, this returns null.
5449///
5450static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5451 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005452 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005453 gep_type_iterator GTI = gep_type_begin(GEP);
5454
5455 // Check to see if this gep only has a single variable index. If so, and if
5456 // any constant indices are a multiple of its scale, then we can compute this
5457 // in terms of the scale of the variable index. For example, if the GEP
5458 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5459 // because the expression will cross zero at the same point.
5460 unsigned i, e = GEP->getNumOperands();
5461 int64_t Offset = 0;
5462 for (i = 1; i != e; ++i, ++GTI) {
5463 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5464 // Compute the aggregate offset of constant indices.
5465 if (CI->isZero()) continue;
5466
5467 // Handle a struct index, which adds its field offset to the pointer.
5468 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5469 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5470 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005471 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005472 Offset += Size*CI->getSExtValue();
5473 }
5474 } else {
5475 // Found our variable index.
5476 break;
5477 }
5478 }
5479
5480 // If there are no variable indices, we must have a constant offset, just
5481 // evaluate it the general way.
5482 if (i == e) return 0;
5483
5484 Value *VariableIdx = GEP->getOperand(i);
5485 // Determine the scale factor of the variable element. For example, this is
5486 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005487 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005488
5489 // Verify that there are no other variable indices. If so, emit the hard way.
5490 for (++i, ++GTI; i != e; ++i, ++GTI) {
5491 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5492 if (!CI) return 0;
5493
5494 // Compute the aggregate offset of constant indices.
5495 if (CI->isZero()) continue;
5496
5497 // Handle a struct index, which adds its field offset to the pointer.
5498 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5499 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5500 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005501 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005502 Offset += Size*CI->getSExtValue();
5503 }
5504 }
5505
5506 // Okay, we know we have a single variable index, which must be a
5507 // pointer/array/vector index. If there is no offset, life is simple, return
5508 // the index.
5509 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5510 if (Offset == 0) {
5511 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5512 // we don't need to bother extending: the extension won't affect where the
5513 // computation crosses zero.
5514 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5515 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5516 VariableIdx->getNameStart(), &I);
5517 return VariableIdx;
5518 }
5519
5520 // Otherwise, there is an index. The computation we will do will be modulo
5521 // the pointer size, so get it.
5522 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5523
5524 Offset &= PtrSizeMask;
5525 VariableScale &= PtrSizeMask;
5526
5527 // To do this transformation, any constant index must be a multiple of the
5528 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5529 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5530 // multiple of the variable scale.
5531 int64_t NewOffs = Offset / (int64_t)VariableScale;
5532 if (Offset != NewOffs*(int64_t)VariableScale)
5533 return 0;
5534
5535 // Okay, we can do this evaluation. Start by converting the index to intptr.
5536 const Type *IntPtrTy = TD.getIntPtrType();
5537 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005538 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005539 true /*SExt*/,
5540 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005541 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005542 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005543}
5544
5545
Reid Spencere4d87aa2006-12-23 06:05:41 +00005546/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005547/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005548Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5549 ICmpInst::Predicate Cond,
5550 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005551 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005552
Chris Lattner10c0d912008-04-22 02:53:33 +00005553 // Look through bitcasts.
5554 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5555 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005556
Chris Lattner574da9b2005-01-13 20:14:25 +00005557 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005558 if (TD && PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005559 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005560 // This transformation (ignoring the base and scales) is valid because we
5561 // know pointers can't overflow. See if we can output an optimized form.
5562 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5563
5564 // If not, synthesize the offset the hard way.
5565 if (Offset == 0)
5566 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005567 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005568 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005569 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005570 // If the base pointers are different, but the indices are the same, just
5571 // compare the base pointer.
5572 if (PtrBase != GEPRHS->getOperand(0)) {
5573 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005574 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005575 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005576 if (IndicesTheSame)
5577 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5578 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5579 IndicesTheSame = false;
5580 break;
5581 }
5582
5583 // If all indices are the same, just compare the base pointers.
5584 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005585 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005586 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005587
5588 // Otherwise, the base pointers are different and the indices are
5589 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005590 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005591 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005592
Chris Lattnere9d782b2005-01-13 22:25:21 +00005593 // If one of the GEPs has all zero indices, recurse.
5594 bool AllZeros = true;
5595 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5596 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5597 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5598 AllZeros = false;
5599 break;
5600 }
5601 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005602 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5603 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005604
5605 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005606 AllZeros = true;
5607 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5608 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5609 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5610 AllZeros = false;
5611 break;
5612 }
5613 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005614 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005615
Chris Lattner4401c9c2005-01-14 00:20:05 +00005616 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5617 // If the GEPs only differ by one index, compare it.
5618 unsigned NumDifferences = 0; // Keep track of # differences.
5619 unsigned DiffOperand = 0; // The operand that differs.
5620 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5621 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005622 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5623 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005624 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005625 NumDifferences = 2;
5626 break;
5627 } else {
5628 if (NumDifferences++) break;
5629 DiffOperand = i;
5630 }
5631 }
5632
5633 if (NumDifferences == 0) // SAME GEP?
5634 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005635 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005636 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005637
Chris Lattner4401c9c2005-01-14 00:20:05 +00005638 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005639 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5640 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005641 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005642 return new ICmpInst(*Context,
5643 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005644 }
5645 }
5646
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005648 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005649 if (TD &&
5650 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005651 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5652 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5653 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5654 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005655 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005656 }
5657 }
5658 return 0;
5659}
5660
Chris Lattnera5406232008-05-19 20:18:56 +00005661/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5662///
5663Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5664 Instruction *LHSI,
5665 Constant *RHSC) {
5666 if (!isa<ConstantFP>(RHSC)) return 0;
5667 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5668
5669 // Get the width of the mantissa. We don't want to hack on conversions that
5670 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005671 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005672 if (MantissaWidth == -1) return 0; // Unknown.
5673
5674 // Check to see that the input is converted from an integer type that is small
5675 // enough that preserves all bits. TODO: check here for "known" sign bits.
5676 // 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 +00005677 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005678
5679 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005680 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5681 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005682 ++InputSize;
5683
5684 // If the conversion would lose info, don't hack on this.
5685 if ((int)InputSize > MantissaWidth)
5686 return 0;
5687
5688 // Otherwise, we can potentially simplify the comparison. We know that it
5689 // will always come through as an integer value and we know the constant is
5690 // not a NAN (it would have been previously simplified).
5691 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5692
5693 ICmpInst::Predicate Pred;
5694 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005695 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005696 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005697 case FCmpInst::FCMP_OEQ:
5698 Pred = ICmpInst::ICMP_EQ;
5699 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005700 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005701 case FCmpInst::FCMP_OGT:
5702 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5703 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005704 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005705 case FCmpInst::FCMP_OGE:
5706 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5707 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005708 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005709 case FCmpInst::FCMP_OLT:
5710 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5711 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005712 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005713 case FCmpInst::FCMP_OLE:
5714 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5715 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005717 case FCmpInst::FCMP_ONE:
5718 Pred = ICmpInst::ICMP_NE;
5719 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005720 case FCmpInst::FCMP_ORD:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005721 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005722 case FCmpInst::FCMP_UNO:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005723 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005724 }
5725
5726 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5727
5728 // Now we know that the APFloat is a normal number, zero or inf.
5729
Chris Lattner85162782008-05-20 03:50:52 +00005730 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005731 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005732 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005733
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005734 if (!LHSUnsigned) {
5735 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5736 // and large values.
5737 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5738 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5739 APFloat::rmNearestTiesToEven);
5740 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5741 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5742 Pred == ICmpInst::ICMP_SLE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005743 return ReplaceInstUsesWith(I, Context->getTrue());
5744 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005745 }
5746 } else {
5747 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5748 // +INF and large values.
5749 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5750 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5751 APFloat::rmNearestTiesToEven);
5752 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5753 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5754 Pred == ICmpInst::ICMP_ULE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005755 return ReplaceInstUsesWith(I, Context->getTrue());
5756 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005757 }
Chris Lattnera5406232008-05-19 20:18:56 +00005758 }
5759
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005760 if (!LHSUnsigned) {
5761 // See if the RHS value is < SignedMin.
5762 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5763 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5764 APFloat::rmNearestTiesToEven);
5765 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5766 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5767 Pred == ICmpInst::ICMP_SGE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005768 return ReplaceInstUsesWith(I, Context->getTrue());
5769 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005770 }
Chris Lattnera5406232008-05-19 20:18:56 +00005771 }
5772
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005773 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5774 // [0, UMAX], but it may still be fractional. See if it is fractional by
5775 // casting the FP value to the integer value and back, checking for equality.
5776 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005777 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005778 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5779 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005780 if (!RHS.isZero()) {
5781 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005782 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5783 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005784 if (!Equal) {
5785 // If we had a comparison against a fractional value, we have to adjust
5786 // the compare predicate and sometimes the value. RHSC is rounded towards
5787 // zero at this point.
5788 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005789 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005790 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00005791 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005792 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00005793 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005794 case ICmpInst::ICMP_ULE:
5795 // (float)int <= 4.4 --> int <= 4
5796 // (float)int <= -4.4 --> false
5797 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005798 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005799 break;
5800 case ICmpInst::ICMP_SLE:
5801 // (float)int <= 4.4 --> int <= 4
5802 // (float)int <= -4.4 --> int < -4
5803 if (RHS.isNegative())
5804 Pred = ICmpInst::ICMP_SLT;
5805 break;
5806 case ICmpInst::ICMP_ULT:
5807 // (float)int < -4.4 --> false
5808 // (float)int < 4.4 --> int <= 4
5809 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005810 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005811 Pred = ICmpInst::ICMP_ULE;
5812 break;
5813 case ICmpInst::ICMP_SLT:
5814 // (float)int < -4.4 --> int < -4
5815 // (float)int < 4.4 --> int <= 4
5816 if (!RHS.isNegative())
5817 Pred = ICmpInst::ICMP_SLE;
5818 break;
5819 case ICmpInst::ICMP_UGT:
5820 // (float)int > 4.4 --> int > 4
5821 // (float)int > -4.4 --> true
5822 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005823 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005824 break;
5825 case ICmpInst::ICMP_SGT:
5826 // (float)int > 4.4 --> int > 4
5827 // (float)int > -4.4 --> int >= -4
5828 if (RHS.isNegative())
5829 Pred = ICmpInst::ICMP_SGE;
5830 break;
5831 case ICmpInst::ICMP_UGE:
5832 // (float)int >= -4.4 --> true
5833 // (float)int >= 4.4 --> int > 4
5834 if (!RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005835 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005836 Pred = ICmpInst::ICMP_UGT;
5837 break;
5838 case ICmpInst::ICMP_SGE:
5839 // (float)int >= -4.4 --> int >= -4
5840 // (float)int >= 4.4 --> int > 4
5841 if (!RHS.isNegative())
5842 Pred = ICmpInst::ICMP_SGT;
5843 break;
5844 }
Chris Lattnera5406232008-05-19 20:18:56 +00005845 }
5846 }
5847
5848 // Lower this FP comparison into an appropriate integer version of the
5849 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005850 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005851}
5852
Reid Spencere4d87aa2006-12-23 06:05:41 +00005853Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5854 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005855 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005856
Chris Lattner58e97462007-01-14 19:42:17 +00005857 // Fold trivial predicates.
5858 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005859 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005860 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005861 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005862
5863 // Simplify 'fcmp pred X, X'
5864 if (Op0 == Op1) {
5865 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005866 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005867 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5868 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5869 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005870 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005871 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5872 case FCmpInst::FCMP_OLT: // True if ordered and less than
5873 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005874 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005875
5876 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5877 case FCmpInst::FCMP_ULT: // True if unordered or less than
5878 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5879 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5880 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5881 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005882 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005883 return &I;
5884
5885 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5886 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5887 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5888 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5889 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5890 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005891 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005892 return &I;
5893 }
5894 }
5895
Reid Spencere4d87aa2006-12-23 06:05:41 +00005896 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005897 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005898
Reid Spencere4d87aa2006-12-23 06:05:41 +00005899 // Handle fcmp with constant RHS
5900 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005901 // If the constant is a nan, see if we can fold the comparison based on it.
5902 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5903 if (CFP->getValueAPF().isNaN()) {
5904 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersonb3056fa2009-07-21 18:03:38 +00005905 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005906 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5907 "Comparison must be either ordered or unordered!");
5908 // True if unordered.
Owen Andersonb3056fa2009-07-21 18:03:38 +00005909 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005910 }
5911 }
5912
Reid Spencere4d87aa2006-12-23 06:05:41 +00005913 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5914 switch (LHSI->getOpcode()) {
5915 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005916 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5917 // block. If in the same block, we're encouraging jump threading. If
5918 // not, we are just pessimizing the code by making an i1 phi.
5919 if (LHSI->getParent() == I.getParent())
5920 if (Instruction *NV = FoldOpIntoPhi(I))
5921 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005923 case Instruction::SIToFP:
5924 case Instruction::UIToFP:
5925 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5926 return NV;
5927 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 case Instruction::Select:
5929 // If either operand of the select is a constant, we can fold the
5930 // comparison into the select arms, which will cause one to be
5931 // constant folded and the select turned into a bitwise or.
5932 Value *Op1 = 0, *Op2 = 0;
5933 if (LHSI->hasOneUse()) {
5934 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5935 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005936 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005938 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005939 LHSI->getOperand(2), RHSC,
5940 I.getName()), I);
5941 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5942 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005943 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005944 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005945 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 LHSI->getOperand(1), RHSC,
5947 I.getName()), I);
5948 }
5949 }
5950
5951 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005952 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005953 break;
5954 }
5955 }
5956
5957 return Changed ? &I : 0;
5958}
5959
5960Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5961 bool Changed = SimplifyCompare(I);
5962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5963 const Type *Ty = Op0->getType();
5964
5965 // icmp X, X
5966 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005967 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005968 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969
5970 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005971 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005972
Reid Spencere4d87aa2006-12-23 06:05:41 +00005973 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005974 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005975 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5976 isa<ConstantPointerNull>(Op0)) &&
5977 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005978 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005979 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005980 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005981
Reid Spencere4d87aa2006-12-23 06:05:41 +00005982 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005983 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005984 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005985 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005986 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005987 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005988 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00005989 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005990 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005991 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005992 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005993
Reid Spencere4d87aa2006-12-23 06:05:41 +00005994 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005995 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005996 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005997 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00005998 Instruction *Not = BinaryOperator::CreateNot(*Context,
5999 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006000 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006001 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006002 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006003 case ICmpInst::ICMP_SGT:
6004 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006005 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006006 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006007 Instruction *Not = BinaryOperator::CreateNot(*Context,
6008 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006009 InsertNewInstBefore(Not, I);
6010 return BinaryOperator::CreateAnd(Not, Op0);
6011 }
6012 case ICmpInst::ICMP_UGE:
6013 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6014 // FALL THROUGH
6015 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006016 Instruction *Not = BinaryOperator::CreateNot(*Context,
6017 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006018 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006019 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006020 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006021 case ICmpInst::ICMP_SGE:
6022 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6023 // FALL THROUGH
6024 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006025 Instruction *Not = BinaryOperator::CreateNot(*Context,
6026 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006027 InsertNewInstBefore(Not, I);
6028 return BinaryOperator::CreateOr(Not, Op0);
6029 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006030 }
Chris Lattner8b170942002-08-09 23:47:40 +00006031 }
6032
Dan Gohman1c8491e2009-04-25 17:12:48 +00006033 unsigned BitWidth = 0;
6034 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006035 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6036 else if (Ty->isIntOrIntVector())
6037 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006038
6039 bool isSignBit = false;
6040
Dan Gohman81b28ce2008-09-16 18:46:06 +00006041 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006042 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006043 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006044
Chris Lattnerb6566012008-01-05 01:18:20 +00006045 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6046 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006047 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006048 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006049 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006050 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006051
Dan Gohman81b28ce2008-09-16 18:46:06 +00006052 // If we have an icmp le or icmp ge instruction, turn it into the
6053 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6054 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006055 switch (I.getPredicate()) {
6056 default: break;
6057 case ICmpInst::ICMP_ULE:
6058 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006059 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006060 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6061 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006062 case ICmpInst::ICMP_SLE:
6063 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006064 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006065 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6066 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006067 case ICmpInst::ICMP_UGE:
6068 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006069 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006070 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6071 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006072 case ICmpInst::ICMP_SGE:
6073 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006074 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006075 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6076 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006077 }
6078
Chris Lattner183661e2008-07-11 05:40:05 +00006079 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006080 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006081 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6083 }
6084
6085 // See if we can fold the comparison based on range information we can get
6086 // by checking whether bits are known to be zero or one in the input.
6087 if (BitWidth != 0) {
6088 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6089 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6090
6091 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006092 isSignBit ? APInt::getSignBit(BitWidth)
6093 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006095 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 if (SimplifyDemandedBits(I.getOperandUse(1),
6097 APInt::getAllOnesValue(BitWidth),
6098 Op1KnownZero, Op1KnownOne, 0))
6099 return &I;
6100
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006101 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006102 // in. Compute the Min, Max and RHS values based on the known bits. For the
6103 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006104 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6105 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6106 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6107 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6108 Op0Min, Op0Max);
6109 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6110 Op1Min, Op1Max);
6111 } else {
6112 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6113 Op0Min, Op0Max);
6114 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6115 Op1Min, Op1Max);
6116 }
6117
Chris Lattner183661e2008-07-11 05:40:05 +00006118 // If Min and Max are known to be the same, then SimplifyDemandedBits
6119 // figured out that the LHS is a constant. Just constant fold this now so
6120 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006121 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006122 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006123 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006124 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006125 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006126 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127
Chris Lattner183661e2008-07-11 05:40:05 +00006128 // Based on the range information we know about the LHS, see if we can
6129 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006131 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006132 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006134 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006135 break;
6136 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006138 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006139 break;
6140 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006142 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006144 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006146 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6148 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006149 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6150 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151
6152 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6153 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006154 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006155 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006156 }
Chris Lattner84dff672008-07-11 05:08:55 +00006157 break;
6158 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006160 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006162 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163
6164 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006165 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6167 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006168 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6169 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170
6171 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6172 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006173 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006174 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006175 }
Chris Lattner84dff672008-07-11 05:08:55 +00006176 break;
6177 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006178 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006179 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006181 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006183 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6185 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006186 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6187 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006188 }
Chris Lattner84dff672008-07-11 05:08:55 +00006189 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 case ICmpInst::ICMP_SGT:
6191 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006192 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006194 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006195
6196 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006197 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006198 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6199 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006200 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6201 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 }
6203 break;
6204 case ICmpInst::ICMP_SGE:
6205 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6206 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006207 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006208 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006209 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 break;
6211 case ICmpInst::ICMP_SLE:
6212 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6213 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006214 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006215 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006216 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217 break;
6218 case ICmpInst::ICMP_UGE:
6219 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6220 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006221 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006222 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006223 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 break;
6225 case ICmpInst::ICMP_ULE:
6226 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6227 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006228 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006229 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006230 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006231 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006232 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006233
6234 // Turn a signed comparison into an unsigned one if both operands
6235 // are known to have the same sign.
6236 if (I.isSignedPredicate() &&
6237 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6238 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006239 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006240 }
6241
6242 // Test if the ICmpInst instruction is used exclusively by a select as
6243 // part of a minimum or maximum operation. If so, refrain from doing
6244 // any other folding. This helps out other analyses which understand
6245 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6246 // and CodeGen. And in this case, at least one of the comparison
6247 // operands has at least one user besides the compare (the select),
6248 // which would often largely negate the benefit of folding anyway.
6249 if (I.hasOneUse())
6250 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6251 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6252 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6253 return 0;
6254
6255 // See if we are doing a comparison between a constant and an instruction that
6256 // can be folded into the comparison.
6257 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006258 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006259 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006260 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006261 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006262 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6263 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006264 }
6265
Chris Lattner01deb9d2007-04-03 17:43:25 +00006266 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006267 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6268 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6269 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006270 case Instruction::GetElementPtr:
6271 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006272 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006273 bool isAllZeros = true;
6274 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6275 if (!isa<Constant>(LHSI->getOperand(i)) ||
6276 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6277 isAllZeros = false;
6278 break;
6279 }
6280 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006281 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006282 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006283 }
6284 break;
6285
Chris Lattner6970b662005-04-23 15:31:55 +00006286 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006287 // Only fold icmp into the PHI if the phi and fcmp are in the same
6288 // block. If in the same block, we're encouraging jump threading. If
6289 // not, we are just pessimizing the code by making an i1 phi.
6290 if (LHSI->getParent() == I.getParent())
6291 if (Instruction *NV = FoldOpIntoPhi(I))
6292 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006293 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006294 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006295 // If either operand of the select is a constant, we can fold the
6296 // comparison into the select arms, which will cause one to be
6297 // constant folded and the select turned into a bitwise or.
6298 Value *Op1 = 0, *Op2 = 0;
6299 if (LHSI->hasOneUse()) {
6300 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6301 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006302 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006303 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006304 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006305 LHSI->getOperand(2), RHSC,
6306 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006307 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6308 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006309 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006310 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006311 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006312 LHSI->getOperand(1), RHSC,
6313 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006314 }
6315 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006316
Chris Lattner6970b662005-04-23 15:31:55 +00006317 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006318 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006319 break;
6320 }
Chris Lattner4802d902007-04-06 18:57:34 +00006321 case Instruction::Malloc:
6322 // If we have (malloc != null), and if the malloc has a single use, we
6323 // can assume it is successful and remove the malloc.
6324 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6325 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006326 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006327 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006328 }
6329 break;
6330 }
Chris Lattner6970b662005-04-23 15:31:55 +00006331 }
6332
Reid Spencere4d87aa2006-12-23 06:05:41 +00006333 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006334 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006335 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006336 return NI;
6337 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006338 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6339 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006340 return NI;
6341
Reid Spencere4d87aa2006-12-23 06:05:41 +00006342 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006343 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6344 // now.
6345 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6346 if (isa<PointerType>(Op0->getType()) &&
6347 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006348 // We keep moving the cast from the left operand over to the right
6349 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006350 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006351
Chris Lattner57d86372007-01-06 01:45:59 +00006352 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6353 // so eliminate it as well.
6354 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6355 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006356
Chris Lattnerde90b762003-11-03 04:25:02 +00006357 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006358 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006359 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006360 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006361 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006362 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006363 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006364 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006365 }
Owen Anderson333c4002009-07-09 23:48:35 +00006366 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006367 }
Chris Lattner57d86372007-01-06 01:45:59 +00006368 }
6369
6370 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006371 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006372 // This comes up when you have code like
6373 // int X = A < B;
6374 // if (X) ...
6375 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006376 // with a constant or another cast from the same type.
6377 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006378 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006379 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006380 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006381
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006382 // See if it's the same type of instruction on the left and right.
6383 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6384 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006385 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006386 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006387 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006388 default: break;
6389 case Instruction::Add:
6390 case Instruction::Sub:
6391 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006392 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006393 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006394 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006395 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6396 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6397 if (CI->getValue().isSignBit()) {
6398 ICmpInst::Predicate Pred = I.isSignedPredicate()
6399 ? I.getUnsignedPredicate()
6400 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006401 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006402 Op1I->getOperand(0));
6403 }
6404
6405 if (CI->getValue().isMaxSignedValue()) {
6406 ICmpInst::Predicate Pred = I.isSignedPredicate()
6407 ? I.getUnsignedPredicate()
6408 : I.getSignedPredicate();
6409 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006410 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006411 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006412 }
6413 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006414 break;
6415 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006416 if (!I.isEquality())
6417 break;
6418
Nick Lewycky5d52c452008-08-21 05:56:10 +00006419 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6420 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6421 // Mask = -1 >> count-trailing-zeros(Cst).
6422 if (!CI->isZero() && !CI->isOne()) {
6423 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006424 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006425 APInt::getLowBitsSet(AP.getBitWidth(),
6426 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006427 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006428 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6429 Mask);
6430 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6431 Mask);
6432 InsertNewInstBefore(And1, I);
6433 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006434 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006435 }
6436 }
6437 break;
6438 }
6439 }
6440 }
6441 }
6442
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006443 // ~x < ~y --> y < x
6444 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006445 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6446 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006447 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006448 }
6449
Chris Lattner65b72ba2006-09-18 04:22:48 +00006450 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006451 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006452
6453 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006454 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6455 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006456 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006457
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006458 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006459 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6460 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006461 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006462 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006463 }
6464
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006465 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006466 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006467 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006468 if (match(B, m_ConstantInt(C1), *Context) &&
6469 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006470 Constant *NC =
6471 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006472 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006473 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006474 InsertNewInstBefore(Xor, I));
6475 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006476
6477 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006478 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6479 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6480 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6481 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006482 }
6483 }
6484
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006485 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006486 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006487 // A == (A^B) -> B == 0
6488 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006489 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006490 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006491 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006492
6493 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006494 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006495 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006496 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006497
6498 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006499 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006500 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006501 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006502
Chris Lattner9c2328e2006-11-14 06:06:06 +00006503 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6504 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006505 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6506 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006507 Value *X = 0, *Y = 0, *Z = 0;
6508
6509 if (A == C) {
6510 X = B; Y = D; Z = A;
6511 } else if (A == D) {
6512 X = B; Y = C; Z = A;
6513 } else if (B == C) {
6514 X = A; Y = D; Z = B;
6515 } else if (B == D) {
6516 X = A; Y = C; Z = B;
6517 }
6518
6519 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006520 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6521 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006522 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006523 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006524 return &I;
6525 }
6526 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006527 }
Chris Lattner7e708292002-06-25 16:13:24 +00006528 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006529}
6530
Chris Lattner562ef782007-06-20 23:46:26 +00006531
6532/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6533/// and CmpRHS are both known to be integer constants.
6534Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6535 ConstantInt *DivRHS) {
6536 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6537 const APInt &CmpRHSV = CmpRHS->getValue();
6538
6539 // FIXME: If the operand types don't match the type of the divide
6540 // then don't attempt this transform. The code below doesn't have the
6541 // logic to deal with a signed divide and an unsigned compare (and
6542 // vice versa). This is because (x /s C1) <s C2 produces different
6543 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6544 // (x /u C1) <u C2. Simply casting the operands and result won't
6545 // work. :( The if statement below tests that condition and bails
6546 // if it finds it.
6547 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6548 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6549 return 0;
6550 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006551 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006552 if (DivIsSigned && DivRHS->isAllOnesValue())
6553 return 0; // The overflow computation also screws up here
6554 if (DivRHS->isOne())
6555 return 0; // Not worth bothering, and eliminates some funny cases
6556 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006557
6558 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6559 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6560 // C2 (CI). By solving for X we can turn this into a range check
6561 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006562 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006563
6564 // Determine if the product overflows by seeing if the product is
6565 // not equal to the divide. Make sure we do the same kind of divide
6566 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006567 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6568 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006569
6570 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006571 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006572
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 // Figure out the interval that is being checked. For example, a comparison
6574 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6575 // Compute this interval based on the constants involved and the signedness of
6576 // the compare/divide. This computes a half-open interval, keeping track of
6577 // whether either value in the interval overflows. After analysis each
6578 // overflow variable is set to 0 if it's corresponding bound variable is valid
6579 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6580 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006581 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006582
Chris Lattner562ef782007-06-20 23:46:26 +00006583 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006584 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006585 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 HiOverflow = LoOverflow = ProdOV;
6587 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006588 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006589 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006590 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006592 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6593 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006594 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006595 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006596 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6597 HiOverflow = LoOverflow = ProdOV;
6598 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006599 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006600 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006601 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006602 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006603 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6604 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006605 ConstantInt* DivNeg =
6606 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6607 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006608 true) ? -1 : 0;
6609 }
Chris Lattner562ef782007-06-20 23:46:26 +00006610 }
Dan Gohman76491272008-02-13 22:09:18 +00006611 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006612 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006613 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006614 LoBound = AddOne(DivRHS, Context);
6615 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006616 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6617 HiOverflow = 1; // [INTMIN+1, overflow)
6618 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6619 }
Dan Gohman76491272008-02-13 22:09:18 +00006620 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006621 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006622 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006623 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006624 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006625 LoOverflow = AddWithOverflow(LoBound, HiBound,
6626 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006627 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006628 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6629 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006630 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006631 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006632 }
6633
Chris Lattner1dbfd482007-06-21 18:11:19 +00006634 // Dividing by a negative swaps the condition. LT <-> GT
6635 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006636 }
6637
6638 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006639 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006640 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006641 case ICmpInst::ICMP_EQ:
6642 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006643 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006644 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006645 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006646 ICmpInst::ICMP_UGE, X, LoBound);
6647 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006648 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006649 ICmpInst::ICMP_ULT, X, HiBound);
6650 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006651 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006652 case ICmpInst::ICMP_NE:
6653 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006654 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006655 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006656 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006657 ICmpInst::ICMP_ULT, X, LoBound);
6658 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006659 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006660 ICmpInst::ICMP_UGE, X, HiBound);
6661 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006662 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006663 case ICmpInst::ICMP_ULT:
6664 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006665 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006666 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006667 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006668 return ReplaceInstUsesWith(ICI, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006669 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006670 case ICmpInst::ICMP_UGT:
6671 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006672 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006673 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006674 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006675 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006676 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006677 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006678 else
Owen Anderson333c4002009-07-09 23:48:35 +00006679 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006680 }
6681}
6682
6683
Chris Lattner01deb9d2007-04-03 17:43:25 +00006684/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6685///
6686Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6687 Instruction *LHSI,
6688 ConstantInt *RHS) {
6689 const APInt &RHSV = RHS->getValue();
6690
6691 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006692 case Instruction::Trunc:
6693 if (ICI.isEquality() && LHSI->hasOneUse()) {
6694 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6695 // of the high bits truncated out of x are known.
6696 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6697 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6698 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6699 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6700 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6701
6702 // If all the high bits are known, we can do this xform.
6703 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6704 // Pull in the high bits from known-ones set.
6705 APInt NewRHS(RHS->getValue());
6706 NewRHS.zext(SrcBits);
6707 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006708 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006709 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006710 }
6711 }
6712 break;
6713
Duncan Sands0091bf22007-04-04 06:42:45 +00006714 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006715 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6716 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6717 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006718 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6719 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006720 Value *CompareVal = LHSI->getOperand(0);
6721
6722 // If the sign bit of the XorCST is not set, there is no change to
6723 // the operation, just stop using the Xor.
6724 if (!XorCST->getValue().isNegative()) {
6725 ICI.setOperand(0, CompareVal);
6726 AddToWorkList(LHSI);
6727 return &ICI;
6728 }
6729
6730 // Was the old condition true if the operand is positive?
6731 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6732
6733 // If so, the new one isn't.
6734 isTrueIfPositive ^= true;
6735
6736 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006737 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006738 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006739 else
Owen Anderson333c4002009-07-09 23:48:35 +00006740 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006741 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006742 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006743
6744 if (LHSI->hasOneUse()) {
6745 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6746 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6747 const APInt &SignBit = XorCST->getValue();
6748 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6749 ? ICI.getUnsignedPredicate()
6750 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006751 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006752 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006753 }
6754
6755 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006756 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006757 const APInt &NotSignBit = XorCST->getValue();
6758 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6759 ? ICI.getUnsignedPredicate()
6760 : ICI.getSignedPredicate();
6761 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006762 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006763 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006764 }
6765 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006766 }
6767 break;
6768 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6769 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6770 LHSI->getOperand(0)->hasOneUse()) {
6771 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6772
6773 // If the LHS is an AND of a truncating cast, we can widen the
6774 // and/compare to be the input width without changing the value
6775 // produced, eliminating a cast.
6776 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6777 // We can do this transformation if either the AND constant does not
6778 // have its sign bit set or if it is an equality comparison.
6779 // Extending a relational comparison when we're checking the sign
6780 // bit would not work.
6781 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006782 (ICI.isEquality() ||
6783 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006784 uint32_t BitWidth =
6785 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6786 APInt NewCST = AndCST->getValue();
6787 NewCST.zext(BitWidth);
6788 APInt NewCI = RHSV;
6789 NewCI.zext(BitWidth);
6790 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006791 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006792 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006793 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006794 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006795 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796 }
6797 }
6798
6799 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6800 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6801 // happens a LOT in code produced by the C front-end, for bitfield
6802 // access.
6803 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6804 if (Shift && !Shift->isShift())
6805 Shift = 0;
6806
6807 ConstantInt *ShAmt;
6808 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6809 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6810 const Type *AndTy = AndCST->getType(); // Type of the and.
6811
6812 // We can fold this as long as we can't shift unknown bits
6813 // into the mask. This can only happen with signed shift
6814 // rights, as they sign-extend.
6815 if (ShAmt) {
6816 bool CanFold = Shift->isLogicalShift();
6817 if (!CanFold) {
6818 // To test for the bad case of the signed shr, see if any
6819 // of the bits shifted in could be tested after the mask.
6820 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6821 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6822
6823 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6824 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6825 AndCST->getValue()) == 0)
6826 CanFold = true;
6827 }
6828
6829 if (CanFold) {
6830 Constant *NewCst;
6831 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006832 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006833 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006834 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006835
6836 // Check to see if we are shifting out any of the bits being
6837 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006838 if (Context->getConstantExpr(Shift->getOpcode(),
6839 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006840 // If we shifted bits out, the fold is not going to work out.
6841 // As a special case, check to see if this means that the
6842 // result is always true or false now.
6843 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006844 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006845 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006846 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006847 } else {
6848 ICI.setOperand(1, NewCst);
6849 Constant *NewAndCST;
6850 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006851 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006852 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006853 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006854 LHSI->setOperand(1, NewAndCST);
6855 LHSI->setOperand(0, Shift->getOperand(0));
6856 AddToWorkList(Shift); // Shift is dead.
6857 AddUsesToWorkList(ICI);
6858 return &ICI;
6859 }
6860 }
6861 }
6862
6863 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6864 // preferable because it allows the C<<Y expression to be hoisted out
6865 // of a loop if Y is invariant and X is not.
6866 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006867 ICI.isEquality() && !Shift->isArithmeticShift() &&
6868 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006869 // Compute C << Y.
6870 Value *NS;
6871 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006872 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006873 Shift->getOperand(1), "tmp");
6874 } else {
6875 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006876 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006877 Shift->getOperand(1), "tmp");
6878 }
6879 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6880
6881 // Compute X & (C << Y).
6882 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006883 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006884 InsertNewInstBefore(NewAnd, ICI);
6885
6886 ICI.setOperand(0, NewAnd);
6887 return &ICI;
6888 }
6889 }
6890 break;
6891
Chris Lattnera0141b92007-07-15 20:42:37 +00006892 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6893 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6894 if (!ShAmt) break;
6895
6896 uint32_t TypeBits = RHSV.getBitWidth();
6897
6898 // Check that the shift amount is in range. If not, don't perform
6899 // undefined shifts. When the shift is visited it will be
6900 // simplified.
6901 if (ShAmt->uge(TypeBits))
6902 break;
6903
6904 if (ICI.isEquality()) {
6905 // If we are comparing against bits always shifted out, the
6906 // comparison cannot succeed.
6907 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006908 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6909 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006910 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6911 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006912 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006913 return ReplaceInstUsesWith(ICI, Cst);
6914 }
6915
6916 if (LHSI->hasOneUse()) {
6917 // Otherwise strength reduce the shift into an and.
6918 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6919 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006920 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6921 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006922
Chris Lattnera0141b92007-07-15 20:42:37 +00006923 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006924 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006925 Mask, LHSI->getName()+".mask");
6926 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006927 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006928 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006929 }
6930 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006931
6932 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6933 bool TrueIfSigned = false;
6934 if (LHSI->hasOneUse() &&
6935 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6936 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006937 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006938 (TypeBits-ShAmt->getZExtValue()-1));
6939 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006940 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 Mask, LHSI->getName()+".mask");
6942 Value *And = InsertNewInstBefore(AndI, ICI);
6943
Owen Anderson333c4002009-07-09 23:48:35 +00006944 return new ICmpInst(*Context,
6945 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006946 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006947 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006948 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006949 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006950
6951 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006952 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006953 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006954 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006955 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006956
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006957 // Check that the shift amount is in range. If not, don't perform
6958 // undefined shifts. When the shift is visited it will be
6959 // simplified.
6960 uint32_t TypeBits = RHSV.getBitWidth();
6961 if (ShAmt->uge(TypeBits))
6962 break;
6963
6964 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006965
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006966 // If we are comparing against bits always shifted out, the
6967 // comparison cannot succeed.
6968 APInt Comp = RHSV << ShAmtVal;
6969 if (LHSI->getOpcode() == Instruction::LShr)
6970 Comp = Comp.lshr(ShAmtVal);
6971 else
6972 Comp = Comp.ashr(ShAmtVal);
6973
6974 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6975 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006976 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006977 return ReplaceInstUsesWith(ICI, Cst);
6978 }
6979
6980 // Otherwise, check to see if the bits shifted out are known to be zero.
6981 // If so, we can compare against the unshifted value:
6982 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006983 if (LHSI->hasOneUse() &&
6984 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006985 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00006986 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006987 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006988 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006989
Evan Chengf30752c2008-04-23 00:38:06 +00006990 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006991 // Otherwise strength reduce the shift into an and.
6992 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00006993 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006994
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006995 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006996 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006997 Mask, LHSI->getName()+".mask");
6998 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006999 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007000 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007001 }
7002 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007003 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007004
7005 case Instruction::SDiv:
7006 case Instruction::UDiv:
7007 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7008 // Fold this div into the comparison, producing a range check.
7009 // Determine, based on the divide type, what the range is being
7010 // checked. If there is an overflow on the low or high side, remember
7011 // it, otherwise compute the range [low, hi) bounding the new value.
7012 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007013 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7014 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7015 DivRHS))
7016 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007017 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007018
7019 case Instruction::Add:
7020 // Fold: icmp pred (add, X, C1), C2
7021
7022 if (!ICI.isEquality()) {
7023 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7024 if (!LHSC) break;
7025 const APInt &LHSV = LHSC->getValue();
7026
7027 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7028 .subtract(LHSV);
7029
7030 if (ICI.isSignedPredicate()) {
7031 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007032 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007033 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007034 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007035 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007036 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007037 }
7038 } else {
7039 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007040 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007041 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007042 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007043 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007044 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007045 }
7046 }
7047 }
7048 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007049 }
7050
7051 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7052 if (ICI.isEquality()) {
7053 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7054
7055 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7056 // the second operand is a constant, simplify a bit.
7057 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7058 switch (BO->getOpcode()) {
7059 case Instruction::SRem:
7060 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7061 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7062 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7063 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7064 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007065 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007066 BO->getName());
7067 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007068 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007069 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007070 }
7071 }
7072 break;
7073 case Instruction::Add:
7074 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7075 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7076 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007077 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007078 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007079 } else if (RHSV == 0) {
7080 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7081 // efficiently invertible, or if the add has just this one use.
7082 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7083
Owen Andersond672ecb2009-07-03 00:17:18 +00007084 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007085 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007086 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007087 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007088 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007089 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007090 InsertNewInstBefore(Neg, ICI);
7091 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007092 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007093 }
7094 }
7095 break;
7096 case Instruction::Xor:
7097 // For the xor case, we can xor two constants together, eliminating
7098 // the explicit xor.
7099 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007100 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007101 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007102
7103 // FALLTHROUGH
7104 case Instruction::Sub:
7105 // Replace (([sub|xor] A, B) != 0) with (A != B)
7106 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007107 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 BO->getOperand(1));
7109 break;
7110
7111 case Instruction::Or:
7112 // If bits are being or'd in that are not present in the constant we
7113 // are comparing against, then the comparison could never succeed!
7114 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007115 Constant *NotCI = Context->getConstantExprNot(RHS);
7116 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7117 return ReplaceInstUsesWith(ICI,
7118 Context->getConstantInt(Type::Int1Ty,
7119 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120 }
7121 break;
7122
7123 case Instruction::And:
7124 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7125 // If bits are being compared against that are and'd out, then the
7126 // comparison can never succeed!
7127 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007128 return ReplaceInstUsesWith(ICI,
7129 Context->getConstantInt(Type::Int1Ty,
7130 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007131
7132 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7133 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007134 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007135 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007136 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007137
7138 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007139 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007140 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007141 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007142 ICmpInst::Predicate pred = isICMP_NE ?
7143 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007144 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007145 }
7146
7147 // ((X & ~7) == 0) --> X < 8
7148 if (RHSV == 0 && isHighOnes(BOC)) {
7149 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007150 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007151 ICmpInst::Predicate pred = isICMP_NE ?
7152 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007153 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007154 }
7155 }
7156 default: break;
7157 }
7158 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7159 // Handle icmp {eq|ne} <intrinsic>, intcst.
7160 if (II->getIntrinsicID() == Intrinsic::bswap) {
7161 AddToWorkList(II);
7162 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007163 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007164 return &ICI;
7165 }
7166 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007167 }
7168 return 0;
7169}
7170
7171/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7172/// We only handle extending casts so far.
7173///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007174Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7175 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007176 Value *LHSCIOp = LHSCI->getOperand(0);
7177 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007178 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007179 Value *RHSCIOp;
7180
Chris Lattner8c756c12007-05-05 22:41:33 +00007181 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7182 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007183 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7184 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007185 cast<IntegerType>(DestTy)->getBitWidth()) {
7186 Value *RHSOp = 0;
7187 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007188 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007189 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7190 RHSOp = RHSC->getOperand(0);
7191 // If the pointer types don't match, insert a bitcast.
7192 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007193 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007194 }
7195
7196 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007197 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007198 }
7199
7200 // The code below only handles extension cast instructions, so far.
7201 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007202 if (LHSCI->getOpcode() != Instruction::ZExt &&
7203 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007204 return 0;
7205
Reid Spencere4d87aa2006-12-23 06:05:41 +00007206 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7207 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007208
Reid Spencere4d87aa2006-12-23 06:05:41 +00007209 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007210 // Not an extension from the same type?
7211 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007212 if (RHSCIOp->getType() != LHSCIOp->getType())
7213 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007214
Nick Lewycky4189a532008-01-28 03:48:02 +00007215 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007216 // and the other is a zext), then we can't handle this.
7217 if (CI->getOpcode() != LHSCI->getOpcode())
7218 return 0;
7219
Nick Lewycky4189a532008-01-28 03:48:02 +00007220 // Deal with equality cases early.
7221 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007222 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007223
7224 // A signed comparison of sign extended values simplifies into a
7225 // signed comparison.
7226 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007227 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007228
7229 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007230 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007231 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007232
Reid Spencere4d87aa2006-12-23 06:05:41 +00007233 // If we aren't dealing with a constant on the RHS, exit early
7234 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7235 if (!CI)
7236 return 0;
7237
7238 // Compute the constant that would happen if we truncated to SrcTy then
7239 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007240 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7241 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7242 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007243
7244 // If the re-extended constant didn't change...
7245 if (Res2 == CI) {
7246 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7247 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007248 // %A = sext i16 %X to i32
7249 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007250 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007251 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007252 // because %A may have negative value.
7253 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007254 // However, we allow this when the compare is EQ/NE, because they are
7255 // signless.
7256 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007257 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007258 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259 }
7260
7261 // The re-extended constant changed so the constant cannot be represented
7262 // in the shorter type. Consequently, we cannot emit a simple comparison.
7263
7264 // First, handle some easy cases. We know the result cannot be equal at this
7265 // point so handle the ICI.isEquality() cases
7266 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007267 return ReplaceInstUsesWith(ICI, Context->getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007269 return ReplaceInstUsesWith(ICI, Context->getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007270
7271 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7272 // should have been folded away previously and not enter in here.
7273 Value *Result;
7274 if (isSignedCmp) {
7275 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007276 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00007277 Result = Context->getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007278 else
Owen Andersonb3056fa2009-07-21 18:03:38 +00007279 Result = Context->getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007280 } else {
7281 // We're performing an unsigned comparison.
7282 if (isSignedExt) {
7283 // We're performing an unsigned comp with a sign extended value.
7284 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007285 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007286 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7287 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007288 } else {
7289 // Unsigned extend & unsigned compare -> always true.
Owen Andersonb3056fa2009-07-21 18:03:38 +00007290 Result = Context->getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007291 }
7292 }
7293
7294 // Finally, return the value computed.
7295 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007296 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007297 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007298
7299 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7300 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7301 "ICmp should be folded!");
7302 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007303 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007304 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007305}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007306
Reid Spencer832254e2007-02-02 02:16:23 +00007307Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7308 return commonShiftTransforms(I);
7309}
7310
7311Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7312 return commonShiftTransforms(I);
7313}
7314
7315Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007316 if (Instruction *R = commonShiftTransforms(I))
7317 return R;
7318
7319 Value *Op0 = I.getOperand(0);
7320
7321 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7322 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7323 if (CSI->isAllOnesValue())
7324 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007325
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007326 // See if we can turn a signed shr into an unsigned shr.
7327 if (MaskedValueIsZero(Op0,
7328 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7329 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7330
7331 // Arithmetic shifting an all-sign-bit value is a no-op.
7332 unsigned NumSignBits = ComputeNumSignBits(Op0);
7333 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7334 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007335
Chris Lattner348f6652007-12-06 01:59:46 +00007336 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007337}
7338
7339Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7340 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007342
7343 // shl X, 0 == X and shr X, 0 == X
7344 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007345 if (Op1 == Context->getNullValue(Op1->getType()) ||
7346 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007347 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007348
Reid Spencere4d87aa2006-12-23 06:05:41 +00007349 if (isa<UndefValue>(Op0)) {
7350 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007351 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007352 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007353 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007354 }
7355 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007356 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7357 return ReplaceInstUsesWith(I, Op0);
7358 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007359 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007360 }
7361
Dan Gohman9004c8a2009-05-21 02:28:33 +00007362 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007363 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007364 return &I;
7365
Chris Lattner2eefe512004-04-09 19:05:30 +00007366 // Try to fold constant and into select arguments.
7367 if (isa<Constant>(Op0))
7368 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007369 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007370 return R;
7371
Reid Spencerb83eb642006-10-20 07:07:24 +00007372 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007373 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7374 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007375 return 0;
7376}
7377
Reid Spencerb83eb642006-10-20 07:07:24 +00007378Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007379 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007380 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007381
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007382 // See if we can simplify any instructions used by the instruction whose sole
7383 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007384 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007385
Dan Gohmana119de82009-06-14 23:30:43 +00007386 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7387 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007388 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007389 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007390 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007391 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007392 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007393 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007394 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007395 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007396 }
7397
7398 // ((X*C1) << C2) == (X * (C1 << C2))
7399 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7400 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7401 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007402 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007403 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007404
7405 // Try to fold constant and into select arguments.
7406 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7407 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7408 return R;
7409 if (isa<PHINode>(Op0))
7410 if (Instruction *NV = FoldOpIntoPhi(I))
7411 return NV;
7412
Chris Lattner8999dd32007-12-22 09:07:47 +00007413 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7414 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7415 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7416 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7417 // place. Don't try to do this transformation in this case. Also, we
7418 // require that the input operand is a shift-by-constant so that we have
7419 // confidence that the shifts will get folded together. We could do this
7420 // xform in more cases, but it is unlikely to be profitable.
7421 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7422 isa<ConstantInt>(TrOp->getOperand(1))) {
7423 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007424 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007425 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007426 I.getName());
7427 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7428
7429 // For logical shifts, the truncation has the effect of making the high
7430 // part of the register be zeros. Emulate this by inserting an AND to
7431 // clear the top bits as needed. This 'and' will usually be zapped by
7432 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007433 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7434 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007435 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7436
7437 // The mask we constructed says what the trunc would do if occurring
7438 // between the shifts. We want to know the effect *after* the second
7439 // shift. We know that it is a logical shift by a constant, so adjust the
7440 // mask as appropriate.
7441 if (I.getOpcode() == Instruction::Shl)
7442 MaskV <<= Op1->getZExtValue();
7443 else {
7444 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7445 MaskV = MaskV.lshr(Op1->getZExtValue());
7446 }
7447
Owen Andersond672ecb2009-07-03 00:17:18 +00007448 Instruction *And =
7449 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7450 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007451 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7452
7453 // Return the value truncated to the interesting size.
7454 return new TruncInst(And, I.getType());
7455 }
7456 }
7457
Chris Lattner4d5542c2006-01-06 07:12:35 +00007458 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007459 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7460 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7461 Value *V1, *V2;
7462 ConstantInt *CC;
7463 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007464 default: break;
7465 case Instruction::Add:
7466 case Instruction::And:
7467 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007468 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007469 // These operators commute.
7470 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007471 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007472 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7473 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007474 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007475 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007476 Op0BO->getName());
7477 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007478 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007479 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007480 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007481 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007482 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007483 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007484 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007485 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007486
Chris Lattner150f12a2005-09-18 06:30:59 +00007487 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007488 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007489 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007490 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007491 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007492 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007493 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007494 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007495 Op0BO->getOperand(0), Op1,
7496 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007497 InsertNewInstBefore(YS, I); // (Y << C)
7498 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007499 BinaryOperator::CreateAnd(V1,
7500 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007501 V1->getName()+".mask");
7502 InsertNewInstBefore(XM, I); // X & (CC << C)
7503
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007504 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007505 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007506 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007507
Reid Spencera07cb7d2007-02-02 14:41:37 +00007508 // FALL THROUGH.
7509 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007510 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007511 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007512 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7513 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007514 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007515 Op0BO->getOperand(1), Op1,
7516 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007517 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007518 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007519 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007520 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007521 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007522 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007523 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007524 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007525 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007526
Chris Lattner13d4ab42006-05-31 21:14:00 +00007527 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007528 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7529 match(Op0BO->getOperand(0),
7530 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007531 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007532 cast<BinaryOperator>(Op0BO->getOperand(0))
7533 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007535 Op0BO->getOperand(1), Op1,
7536 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007537 InsertNewInstBefore(YS, I); // (Y << C)
7538 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007539 BinaryOperator::CreateAnd(V1,
7540 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007541 V1->getName()+".mask");
7542 InsertNewInstBefore(XM, I); // X & (CC << C)
7543
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007544 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007545 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007546
Chris Lattner11021cb2005-09-18 05:12:10 +00007547 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007548 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007549 }
7550
7551
7552 // If the operand is an bitwise operator with a constant RHS, and the
7553 // shift is the only use, we can pull it out of the shift.
7554 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7555 bool isValid = true; // Valid only for And, Or, Xor
7556 bool highBitSet = false; // Transform if high bit of constant set?
7557
7558 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007559 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007560 case Instruction::Add:
7561 isValid = isLeftShift;
7562 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007563 case Instruction::Or:
7564 case Instruction::Xor:
7565 highBitSet = false;
7566 break;
7567 case Instruction::And:
7568 highBitSet = true;
7569 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007570 }
7571
7572 // If this is a signed shift right, and the high bit is modified
7573 // by the logical operation, do not perform the transformation.
7574 // The highBitSet boolean indicates the value of the high bit of
7575 // the constant which would cause it to be modified for this
7576 // operation.
7577 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007578 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007579 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007580
7581 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007582 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007583
7584 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007585 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007586 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007587 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007588
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007589 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007590 NewRHS);
7591 }
7592 }
7593 }
7594 }
7595
Chris Lattnerad0124c2006-01-06 07:52:12 +00007596 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007597 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7598 if (ShiftOp && !ShiftOp->isShift())
7599 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007600
Reid Spencerb83eb642006-10-20 07:07:24 +00007601 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007602 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007603 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7604 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007605 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7606 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7607 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007608
Zhou Sheng4351c642007-04-02 08:20:41 +00007609 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007610
7611 const IntegerType *Ty = cast<IntegerType>(I.getType());
7612
7613 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007614 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007615 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7616 // saturates.
7617 if (AmtSum >= TypeBits) {
7618 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007619 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007620 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7621 }
7622
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007623 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007624 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007625 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7626 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007627 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007628 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007629
Chris Lattnerb87056f2007-02-05 00:57:54 +00007630 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007631 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7633 I.getOpcode() == Instruction::LShr) {
7634 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007635 if (AmtSum >= TypeBits)
7636 AmtSum = TypeBits-1;
7637
Chris Lattnerb87056f2007-02-05 00:57:54 +00007638 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007639 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007640 InsertNewInstBefore(Shift, I);
7641
Zhou Shenge9e03f62007-03-28 15:02:20 +00007642 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007643 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007644 }
7645
Chris Lattnerb87056f2007-02-05 00:57:54 +00007646 // Okay, if we get here, one shift must be left, and the other shift must be
7647 // right. See if the amounts are equal.
7648 if (ShiftAmt1 == ShiftAmt2) {
7649 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7650 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007651 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007652 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007653 }
7654 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7655 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007656 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007657 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007658 }
7659 // We can simplify ((X << C) >>s C) into a trunc + sext.
7660 // NOTE: we could do this for any C, but that would make 'unusual' integer
7661 // types. For now, just stick to ones well-supported by the code
7662 // generators.
7663 const Type *SExtType = 0;
7664 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007665 case 1 :
7666 case 8 :
7667 case 16 :
7668 case 32 :
7669 case 64 :
7670 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007671 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007672 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007673 default: break;
7674 }
7675 if (SExtType) {
7676 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7677 InsertNewInstBefore(NewTrunc, I);
7678 return new SExtInst(NewTrunc, Ty);
7679 }
7680 // Otherwise, we can't handle it yet.
7681 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007682 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007683
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007684 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007685 if (I.getOpcode() == Instruction::Shl) {
7686 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7687 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007688 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007689 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007690 InsertNewInstBefore(Shift, I);
7691
Reid Spencer55702aa2007-03-25 21:11:44 +00007692 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007693 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007694 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007695
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007696 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007697 if (I.getOpcode() == Instruction::LShr) {
7698 assert(ShiftOp->getOpcode() == Instruction::Shl);
7699 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007700 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007701 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007702
Reid Spencerd5e30f02007-03-26 17:18:58 +00007703 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007704 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007705 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007706
7707 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7708 } else {
7709 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007710 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007711
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007712 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713 if (I.getOpcode() == Instruction::Shl) {
7714 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7715 ShiftOp->getOpcode() == Instruction::AShr);
7716 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007717 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007718 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007719 InsertNewInstBefore(Shift, I);
7720
Reid Spencer55702aa2007-03-25 21:11:44 +00007721 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007722 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007723 }
7724
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007725 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007726 if (I.getOpcode() == Instruction::LShr) {
7727 assert(ShiftOp->getOpcode() == Instruction::Shl);
7728 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007729 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007730 InsertNewInstBefore(Shift, I);
7731
Reid Spencer68d27cf2007-03-26 23:45:51 +00007732 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007733 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007734 }
7735
7736 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007737 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007738 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007739 return 0;
7740}
7741
Chris Lattnera1be5662002-05-02 17:06:02 +00007742
Chris Lattnercfd65102005-10-29 04:36:15 +00007743/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7744/// expression. If so, decompose it, returning some value X, such that Val is
7745/// X*Scale+Offset.
7746///
7747static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007748 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007749 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007750 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007751 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007752 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007753 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007754 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7755 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7756 if (I->getOpcode() == Instruction::Shl) {
7757 // This is a value scaled by '1 << the shift amt'.
7758 Scale = 1U << RHS->getZExtValue();
7759 Offset = 0;
7760 return I->getOperand(0);
7761 } else if (I->getOpcode() == Instruction::Mul) {
7762 // This value is scaled by 'RHS'.
7763 Scale = RHS->getZExtValue();
7764 Offset = 0;
7765 return I->getOperand(0);
7766 } else if (I->getOpcode() == Instruction::Add) {
7767 // We have X+C. Check to see if we really have (X*C2)+C1,
7768 // where C1 is divisible by C2.
7769 unsigned SubScale;
7770 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007771 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7772 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007773 Offset += RHS->getZExtValue();
7774 Scale = SubScale;
7775 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007776 }
7777 }
7778 }
7779
7780 // Otherwise, we can't look past this.
7781 Scale = 1;
7782 Offset = 0;
7783 return Val;
7784}
7785
7786
Chris Lattnerb3f83972005-10-24 06:03:58 +00007787/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7788/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007789Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007790 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007791 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007792
Chris Lattnerb53c2382005-10-24 06:22:12 +00007793 // Remove any uses of AI that are dead.
7794 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007795
Chris Lattnerb53c2382005-10-24 06:22:12 +00007796 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7797 Instruction *User = cast<Instruction>(*UI++);
7798 if (isInstructionTriviallyDead(User)) {
7799 while (UI != E && *UI == User)
7800 ++UI; // If this instruction uses AI more than once, don't break UI.
7801
Chris Lattnerb53c2382005-10-24 06:22:12 +00007802 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007803 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007804 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007805 }
7806 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007807
7808 // This requires TargetData to get the alloca alignment and size information.
7809 if (!TD) return 0;
7810
Chris Lattnerb3f83972005-10-24 06:03:58 +00007811 // Get the type really allocated and the type casted to.
7812 const Type *AllocElTy = AI.getAllocatedType();
7813 const Type *CastElTy = PTy->getElementType();
7814 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007815
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007816 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7817 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007818 if (CastElTyAlign < AllocElTyAlign) return 0;
7819
Chris Lattner39387a52005-10-24 06:35:18 +00007820 // If the allocation has multiple uses, only promote it if we are strictly
7821 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007822 // same, we open the door to infinite loops of various kinds. (A reference
7823 // from a dbg.declare doesn't count as a use for this purpose.)
7824 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7825 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007826
Duncan Sands777d2302009-05-09 07:06:46 +00007827 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7828 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007829 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007830
Chris Lattner455fcc82005-10-29 03:19:53 +00007831 // See if we can satisfy the modulus by pulling a scale out of the array
7832 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007833 unsigned ArraySizeScale;
7834 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007835 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007836 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7837 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007838
Chris Lattner455fcc82005-10-29 03:19:53 +00007839 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7840 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007841 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7842 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007843
Chris Lattner455fcc82005-10-29 03:19:53 +00007844 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7845 Value *Amt = 0;
7846 if (Scale == 1) {
7847 Amt = NumElements;
7848 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007849 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007850 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007851 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007852 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007853 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007854 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007855 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007856 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007857 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007858 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007859 }
7860
Jeff Cohen86796be2007-04-04 16:58:57 +00007861 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007862 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007863 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007864 Amt = InsertNewInstBefore(Tmp, AI);
7865 }
7866
Chris Lattnerb3f83972005-10-24 06:03:58 +00007867 AllocationInst *New;
7868 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007869 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007870 else
Owen Anderson50dead02009-07-15 23:53:25 +00007871 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007872 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007873 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007874
Dale Johannesena0a66372009-03-05 00:39:02 +00007875 // If the allocation has one real use plus a dbg.declare, just remove the
7876 // declare.
7877 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7878 EraseInstFromFunction(*DI);
7879 }
7880 // If the allocation has multiple real uses, insert a cast and change all
7881 // things that used it to use the new cast. This will also hack on CI, but it
7882 // will die soon.
7883 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007884 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007885 // New is the allocation instruction, pointer typed. AI is the original
7886 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7887 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007888 InsertNewInstBefore(NewCast, AI);
7889 AI.replaceAllUsesWith(NewCast);
7890 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007891 return ReplaceInstUsesWith(CI, New);
7892}
7893
Chris Lattner70074e02006-05-13 02:06:03 +00007894/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007895/// and return it as type Ty without inserting any new casts and without
7896/// changing the computed value. This is used by code that tries to decide
7897/// whether promoting or shrinking integer operations to wider or smaller types
7898/// will allow us to eliminate a truncate or extend.
7899///
7900/// This is a truncation operation if Ty is smaller than V->getType(), or an
7901/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007902///
7903/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7904/// should return true if trunc(V) can be computed by computing V in the smaller
7905/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7906/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7907/// efficiently truncated.
7908///
7909/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7910/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7911/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007912bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007913 unsigned CastOpc,
7914 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007915 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007916 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007917 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007918
7919 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007920 if (!I) return false;
7921
Dan Gohman6de29f82009-06-15 22:12:54 +00007922 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007923
Chris Lattner951626b2007-08-02 06:11:14 +00007924 // If this is an extension or truncate, we can often eliminate it.
7925 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7926 // If this is a cast from the destination type, we can trivially eliminate
7927 // it, and this will remove a cast overall.
7928 if (I->getOperand(0)->getType() == Ty) {
7929 // If the first operand is itself a cast, and is eliminable, do not count
7930 // this as an eliminable cast. We would prefer to eliminate those two
7931 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007932 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007933 ++NumCastsRemoved;
7934 return true;
7935 }
7936 }
7937
7938 // We can't extend or shrink something that has multiple uses: doing so would
7939 // require duplicating the instruction in general, which isn't profitable.
7940 if (!I->hasOneUse()) return false;
7941
Evan Chengf35fd542009-01-15 17:01:23 +00007942 unsigned Opc = I->getOpcode();
7943 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007944 case Instruction::Add:
7945 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007946 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007947 case Instruction::And:
7948 case Instruction::Or:
7949 case Instruction::Xor:
7950 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007951 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007952 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007953 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007954 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007955
Eli Friedman070a9812009-07-13 22:46:01 +00007956 case Instruction::UDiv:
7957 case Instruction::URem: {
7958 // UDiv and URem can be truncated if all the truncated bits are zero.
7959 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7960 uint32_t BitWidth = Ty->getScalarSizeInBits();
7961 if (BitWidth < OrigBitWidth) {
7962 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7963 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7964 MaskedValueIsZero(I->getOperand(1), Mask)) {
7965 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7966 NumCastsRemoved) &&
7967 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7968 NumCastsRemoved);
7969 }
7970 }
7971 break;
7972 }
Chris Lattner46b96052006-11-29 07:18:39 +00007973 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007974 // If we are truncating the result of this SHL, and if it's a shift of a
7975 // constant amount, we can always perform a SHL in a smaller type.
7976 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007977 uint32_t BitWidth = Ty->getScalarSizeInBits();
7978 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007979 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007980 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007981 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007982 }
7983 break;
7984 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007985 // If this is a truncate of a logical shr, we can truncate it to a smaller
7986 // lshr iff we know that the bits we would otherwise be shifting in are
7987 // already zeros.
7988 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007989 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7990 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007991 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007992 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007993 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7994 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007995 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007996 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007997 }
7998 }
Chris Lattner46b96052006-11-29 07:18:39 +00007999 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008000 case Instruction::ZExt:
8001 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008002 case Instruction::Trunc:
8003 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008004 // can safely replace it. Note that replacing it does not reduce the number
8005 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008006 if (Opc == CastOpc)
8007 return true;
8008
8009 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008010 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008011 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008012 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008013 case Instruction::Select: {
8014 SelectInst *SI = cast<SelectInst>(I);
8015 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008016 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008017 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008018 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008019 }
Chris Lattner8114b712008-06-18 04:00:49 +00008020 case Instruction::PHI: {
8021 // We can change a phi if we can change all operands.
8022 PHINode *PN = cast<PHINode>(I);
8023 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8024 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008025 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008026 return false;
8027 return true;
8028 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008029 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008030 // TODO: Can handle more cases here.
8031 break;
8032 }
8033
8034 return false;
8035}
8036
8037/// EvaluateInDifferentType - Given an expression that
8038/// CanEvaluateInDifferentType returns true for, actually insert the code to
8039/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008040Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008041 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008042 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008043 return Context->getConstantExprIntegerCast(C, Ty,
8044 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008045
8046 // Otherwise, it must be an instruction.
8047 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008048 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008049 unsigned Opc = I->getOpcode();
8050 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008051 case Instruction::Add:
8052 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008053 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008054 case Instruction::And:
8055 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008056 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008057 case Instruction::AShr:
8058 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008059 case Instruction::Shl:
8060 case Instruction::UDiv:
8061 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008062 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008063 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008064 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008065 break;
8066 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008067 case Instruction::Trunc:
8068 case Instruction::ZExt:
8069 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008070 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008071 // just return the source. There's no need to insert it because it is not
8072 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008073 if (I->getOperand(0)->getType() == Ty)
8074 return I->getOperand(0);
8075
Chris Lattner8114b712008-06-18 04:00:49 +00008076 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008077 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008078 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008079 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008080 case Instruction::Select: {
8081 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8082 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8083 Res = SelectInst::Create(I->getOperand(0), True, False);
8084 break;
8085 }
Chris Lattner8114b712008-06-18 04:00:49 +00008086 case Instruction::PHI: {
8087 PHINode *OPN = cast<PHINode>(I);
8088 PHINode *NPN = PHINode::Create(Ty);
8089 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8090 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8091 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8092 }
8093 Res = NPN;
8094 break;
8095 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008097 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008098 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008099 break;
8100 }
8101
Chris Lattner8114b712008-06-18 04:00:49 +00008102 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008103 return InsertNewInstBefore(Res, *I);
8104}
8105
Reid Spencer3da59db2006-11-27 01:05:10 +00008106/// @brief Implement the transforms common to all CastInst visitors.
8107Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008108 Value *Src = CI.getOperand(0);
8109
Dan Gohman23d9d272007-05-11 21:10:54 +00008110 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008111 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008112 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008113 if (Instruction::CastOps opc =
8114 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8115 // The first cast (CSrc) is eliminable so we need to fix up or replace
8116 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008117 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008118 }
8119 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008120
Reid Spencer3da59db2006-11-27 01:05:10 +00008121 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008122 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8123 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8124 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008125
8126 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008127 if (isa<PHINode>(Src))
8128 if (Instruction *NV = FoldOpIntoPhi(CI))
8129 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008130
Reid Spencer3da59db2006-11-27 01:05:10 +00008131 return 0;
8132}
8133
Chris Lattner46cd5a12009-01-09 05:44:56 +00008134/// FindElementAtOffset - Given a type and a constant offset, determine whether
8135/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008136/// the specified offset. If so, fill them into NewIndices and return the
8137/// resultant element type, otherwise return null.
8138static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8139 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008140 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008141 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008142 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008143 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008144
8145 // Start with the index over the outer type. Note that the type size
8146 // might be zero (even if the offset isn't zero) if the indexed type
8147 // is something like [0 x {int, int}]
8148 const Type *IntPtrTy = TD->getIntPtrType();
8149 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008150 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008151 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008152 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008153
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008154 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008155 if (Offset < 0) {
8156 --FirstIdx;
8157 Offset += TySize;
8158 assert(Offset >= 0);
8159 }
8160 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8161 }
8162
Owen Andersond672ecb2009-07-03 00:17:18 +00008163 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008164
8165 // Index into the types. If we fail, set OrigBase to null.
8166 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008167 // Indexing into tail padding between struct/array elements.
8168 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008169 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008170
Chris Lattner46cd5a12009-01-09 05:44:56 +00008171 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8172 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008173 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8174 "Offset must stay within the indexed type");
8175
Chris Lattner46cd5a12009-01-09 05:44:56 +00008176 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008177 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008178
8179 Offset -= SL->getElementOffset(Elt);
8180 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008181 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008182 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008183 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008184 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008185 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008186 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008187 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008188 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008189 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008190 }
8191 }
8192
Chris Lattner3914f722009-01-24 01:00:13 +00008193 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008194}
8195
Chris Lattnerd3e28342007-04-27 17:44:50 +00008196/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8197Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8198 Value *Src = CI.getOperand(0);
8199
Chris Lattnerd3e28342007-04-27 17:44:50 +00008200 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008201 // If casting the result of a getelementptr instruction with no offset, turn
8202 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008203 if (GEP->hasAllZeroIndices()) {
8204 // Changing the cast operand is usually not a good idea but it is safe
8205 // here because the pointer operand is being replaced with another
8206 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008207 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008208 CI.setOperand(0, GEP->getOperand(0));
8209 return &CI;
8210 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008211
8212 // If the GEP has a single use, and the base pointer is a bitcast, and the
8213 // GEP computes a constant offset, see if we can convert these three
8214 // instructions into fewer. This typically happens with unions and other
8215 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008216 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008217 if (GEP->hasAllConstantIndices()) {
8218 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008219 ConstantInt *OffsetV =
8220 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008221 int64_t Offset = OffsetV->getSExtValue();
8222
8223 // Get the base pointer input of the bitcast, and the type it points to.
8224 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8225 const Type *GEPIdxTy =
8226 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008227 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008228 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008229 // If we were able to index down into an element, create the GEP
8230 // and bitcast the result. This eliminates one bitcast, potentially
8231 // two.
8232 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8233 NewIndices.begin(),
8234 NewIndices.end(), "");
8235 InsertNewInstBefore(NGEP, CI);
8236 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008237
Chris Lattner46cd5a12009-01-09 05:44:56 +00008238 if (isa<BitCastInst>(CI))
8239 return new BitCastInst(NGEP, CI.getType());
8240 assert(isa<PtrToIntInst>(CI));
8241 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008242 }
8243 }
8244 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008245 }
8246
8247 return commonCastTransforms(CI);
8248}
8249
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008250/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8251/// type like i42. We don't want to introduce operations on random non-legal
8252/// integer types where they don't already exist in the code. In the future,
8253/// we should consider making this based off target-data, so that 32-bit targets
8254/// won't get i64 operations etc.
8255static bool isSafeIntegerType(const Type *Ty) {
8256 switch (Ty->getPrimitiveSizeInBits()) {
8257 case 8:
8258 case 16:
8259 case 32:
8260 case 64:
8261 return true;
8262 default:
8263 return false;
8264 }
8265}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008266
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008267/// commonIntCastTransforms - This function implements the common transforms
8268/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008269Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8270 if (Instruction *Result = commonCastTransforms(CI))
8271 return Result;
8272
8273 Value *Src = CI.getOperand(0);
8274 const Type *SrcTy = Src->getType();
8275 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008276 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8277 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008278
Reid Spencer3da59db2006-11-27 01:05:10 +00008279 // See if we can simplify any instructions used by the LHS whose sole
8280 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008281 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008282 return &CI;
8283
8284 // If the source isn't an instruction or has more than one use then we
8285 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008286 Instruction *SrcI = dyn_cast<Instruction>(Src);
8287 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008288 return 0;
8289
Chris Lattnerc739cd62007-03-03 05:27:34 +00008290 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008291 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008292 // Only do this if the dest type is a simple type, don't convert the
8293 // expression tree to something weird like i93 unless the source is also
8294 // strange.
8295 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008296 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8297 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008298 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008299 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008300 // eliminates the cast, so it is always a win. If this is a zero-extension,
8301 // we need to do an AND to maintain the clear top-part of the computation,
8302 // so we require that the input have eliminated at least one cast. If this
8303 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008304 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008305 bool DoXForm = false;
8306 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008307 switch (CI.getOpcode()) {
8308 default:
8309 // All the others use floating point so we shouldn't actually
8310 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008311 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008312 case Instruction::Trunc:
8313 DoXForm = true;
8314 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008315 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008316 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008317 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008318 // If it's unnecessary to issue an AND to clear the high bits, it's
8319 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008320 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008321 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8322 if (MaskedValueIsZero(TryRes, Mask))
8323 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008324
8325 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008326 if (TryI->use_empty())
8327 EraseInstFromFunction(*TryI);
8328 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008329 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008330 }
Evan Chengf35fd542009-01-15 17:01:23 +00008331 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008332 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008333 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008334 // If we do not have to emit the truncate + sext pair, then it's always
8335 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008336 //
8337 // It's not safe to eliminate the trunc + sext pair if one of the
8338 // eliminated cast is a truncate. e.g.
8339 // t2 = trunc i32 t1 to i16
8340 // t3 = sext i16 t2 to i32
8341 // !=
8342 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008343 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008344 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8345 if (NumSignBits > (DestBitSize - SrcBitSize))
8346 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008347
8348 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008349 if (TryI->use_empty())
8350 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008351 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008352 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008353 }
Evan Chengf35fd542009-01-15 17:01:23 +00008354 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008355
8356 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008357 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8358 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008359 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8360 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008361 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008362 // Just replace this cast with the result.
8363 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008364
Reid Spencer3da59db2006-11-27 01:05:10 +00008365 assert(Res->getType() == DestTy);
8366 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008367 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008368 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008369 // Just replace this cast with the result.
8370 return ReplaceInstUsesWith(CI, Res);
8371 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008372 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008373
8374 // If the high bits are already zero, just replace this cast with the
8375 // result.
8376 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8377 if (MaskedValueIsZero(Res, Mask))
8378 return ReplaceInstUsesWith(CI, Res);
8379
8380 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008381 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008382 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008383 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008384 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008385 case Instruction::SExt: {
8386 // If the high bits are already filled with sign bit, just replace this
8387 // cast with the result.
8388 unsigned NumSignBits = ComputeNumSignBits(Res);
8389 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008390 return ReplaceInstUsesWith(CI, Res);
8391
Reid Spencer3da59db2006-11-27 01:05:10 +00008392 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008393 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008394 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8395 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008396 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008397 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008398 }
8399 }
8400
8401 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8402 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8403
8404 switch (SrcI->getOpcode()) {
8405 case Instruction::Add:
8406 case Instruction::Mul:
8407 case Instruction::And:
8408 case Instruction::Or:
8409 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008410 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008411 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8412 // Don't insert two casts unless at least one can be eliminated.
8413 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008414 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008415 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8416 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008417 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008418 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008419 }
8420 }
8421
8422 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8423 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8424 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersonb3056fa2009-07-21 18:03:38 +00008425 Op1 == Context->getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008426 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008427 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008428 return BinaryOperator::CreateXor(New,
8429 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008430 }
8431 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008432
Eli Friedman65445c52009-07-13 21:45:57 +00008433 case Instruction::Shl: {
8434 // Canonicalize trunc inside shl, if we can.
8435 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8436 if (CI && DestBitSize < SrcBitSize &&
8437 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8438 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8439 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008440 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008441 }
8442 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008443 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008444 }
8445 return 0;
8446}
8447
Chris Lattner8a9f5712007-04-11 06:57:46 +00008448Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008449 if (Instruction *Result = commonIntCastTransforms(CI))
8450 return Result;
8451
8452 Value *Src = CI.getOperand(0);
8453 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008454 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8455 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008456
8457 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008458 if (DestBitWidth == 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008459 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008460 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008461 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008462 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008463 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008464
Chris Lattner4f9797d2009-03-24 18:15:30 +00008465 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8466 ConstantInt *ShAmtV = 0;
8467 Value *ShiftOp = 0;
8468 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008469 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008470 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8471
8472 // Get a mask for the bits shifting in.
8473 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8474 if (MaskedValueIsZero(ShiftOp, Mask)) {
8475 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008476 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008477
8478 // Okay, we can shrink this. Truncate the input, then return a new
8479 // shift.
8480 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008481 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008482 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008483 }
8484 }
8485
8486 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008487}
8488
Evan Chengb98a10e2008-03-24 00:21:34 +00008489/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8490/// in order to eliminate the icmp.
8491Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8492 bool DoXform) {
8493 // If we are just checking for a icmp eq of a single bit and zext'ing it
8494 // to an integer, then shift the bit to the appropriate place and then
8495 // cast to integer to avoid the comparison.
8496 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8497 const APInt &Op1CV = Op1C->getValue();
8498
8499 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8500 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8501 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8502 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8503 if (!DoXform) return ICI;
8504
8505 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008506 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008507 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008508 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008509 In->getName()+".lobit"),
8510 CI);
8511 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008512 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008513 false/*ZExt*/, "tmp", &CI);
8514
8515 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008516 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008517 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008518 In->getName()+".not"),
8519 CI);
8520 }
8521
8522 return ReplaceInstUsesWith(CI, In);
8523 }
8524
8525
8526
8527 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8528 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8529 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8530 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8531 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8532 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8533 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8534 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8535 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8536 // This only works for EQ and NE
8537 ICI->isEquality()) {
8538 // If Op1C some other power of two, convert:
8539 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8540 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8541 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8542 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8543
8544 APInt KnownZeroMask(~KnownZero);
8545 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8546 if (!DoXform) return ICI;
8547
8548 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8549 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8550 // (X&4) == 2 --> false
8551 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008552 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8553 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008554 return ReplaceInstUsesWith(CI, Res);
8555 }
8556
8557 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8558 Value *In = ICI->getOperand(0);
8559 if (ShiftAmt) {
8560 // Perform a logical shr by shiftamt.
8561 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008562 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008563 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008564 In->getName()+".lobit"), CI);
8565 }
8566
8567 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008568 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008569 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008570 InsertNewInstBefore(cast<Instruction>(In), CI);
8571 }
8572
8573 if (CI.getType() == In->getType())
8574 return ReplaceInstUsesWith(CI, In);
8575 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008576 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008577 }
8578 }
8579 }
8580
8581 return 0;
8582}
8583
Chris Lattner8a9f5712007-04-11 06:57:46 +00008584Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008585 // If one of the common conversion will work ..
8586 if (Instruction *Result = commonIntCastTransforms(CI))
8587 return Result;
8588
8589 Value *Src = CI.getOperand(0);
8590
Chris Lattnera84f47c2009-02-17 20:47:23 +00008591 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8592 // types and if the sizes are just right we can convert this into a logical
8593 // 'and' which will be much cheaper than the pair of casts.
8594 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8595 // Get the sizes of the types involved. We know that the intermediate type
8596 // will be smaller than A or C, but don't know the relation between A and C.
8597 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008598 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8599 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8600 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008601 // If we're actually extending zero bits, then if
8602 // SrcSize < DstSize: zext(a & mask)
8603 // SrcSize == DstSize: a & mask
8604 // SrcSize > DstSize: trunc(a) & mask
8605 if (SrcSize < DstSize) {
8606 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008607 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008608 Instruction *And =
8609 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8610 InsertNewInstBefore(And, CI);
8611 return new ZExtInst(And, CI.getType());
8612 } else if (SrcSize == DstSize) {
8613 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008614 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008615 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008616 } else if (SrcSize > DstSize) {
8617 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8618 InsertNewInstBefore(Trunc, CI);
8619 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008620 return BinaryOperator::CreateAnd(Trunc,
8621 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008622 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008623 }
8624 }
8625
Evan Chengb98a10e2008-03-24 00:21:34 +00008626 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8627 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008628
Evan Chengb98a10e2008-03-24 00:21:34 +00008629 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8630 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8631 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8632 // of the (zext icmp) will be transformed.
8633 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8634 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8635 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8636 (transformZExtICmp(LHS, CI, false) ||
8637 transformZExtICmp(RHS, CI, false))) {
8638 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8639 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008640 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008641 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008642 }
8643
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008644 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008645 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8646 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8647 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8648 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008649 if (TI0->getType() == CI.getType())
8650 return
8651 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008652 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008653 }
8654
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008655 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8656 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8657 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8658 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8659 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8660 And->getOperand(1) == C)
8661 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8662 Value *TI0 = TI->getOperand(0);
8663 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008664 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008665 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8666 InsertNewInstBefore(NewAnd, *And);
8667 return BinaryOperator::CreateXor(NewAnd, ZC);
8668 }
8669 }
8670
Reid Spencer3da59db2006-11-27 01:05:10 +00008671 return 0;
8672}
8673
Chris Lattner8a9f5712007-04-11 06:57:46 +00008674Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008675 if (Instruction *I = commonIntCastTransforms(CI))
8676 return I;
8677
Chris Lattner8a9f5712007-04-11 06:57:46 +00008678 Value *Src = CI.getOperand(0);
8679
Dan Gohman1975d032008-10-30 20:40:10 +00008680 // Canonicalize sign-extend from i1 to a select.
8681 if (Src->getType() == Type::Int1Ty)
8682 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008683 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008684 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008685
8686 // See if the value being truncated is already sign extended. If so, just
8687 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008688 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008689 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008690 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8691 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8692 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008693 unsigned NumSignBits = ComputeNumSignBits(Op);
8694
8695 if (OpBits == DestBits) {
8696 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8697 // bits, it is already ready.
8698 if (NumSignBits > DestBits-MidBits)
8699 return ReplaceInstUsesWith(CI, Op);
8700 } else if (OpBits < DestBits) {
8701 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8702 // bits, just sext from i32.
8703 if (NumSignBits > OpBits-MidBits)
8704 return new SExtInst(Op, CI.getType(), "tmp");
8705 } else {
8706 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8707 // bits, just truncate to i32.
8708 if (NumSignBits > OpBits-MidBits)
8709 return new TruncInst(Op, CI.getType(), "tmp");
8710 }
8711 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008712
8713 // If the input is a shl/ashr pair of a same constant, then this is a sign
8714 // extension from a smaller value. If we could trust arbitrary bitwidth
8715 // integers, we could turn this into a truncate to the smaller bit and then
8716 // use a sext for the whole extension. Since we don't, look deeper and check
8717 // for a truncate. If the source and dest are the same type, eliminate the
8718 // trunc and extend and just do shifts. For example, turn:
8719 // %a = trunc i32 %i to i8
8720 // %b = shl i8 %a, 6
8721 // %c = ashr i8 %b, 6
8722 // %d = sext i8 %c to i32
8723 // into:
8724 // %a = shl i32 %i, 30
8725 // %d = ashr i32 %a, 30
8726 Value *A = 0;
8727 ConstantInt *BA = 0, *CA = 0;
8728 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008729 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008730 BA == CA && isa<TruncInst>(A)) {
8731 Value *I = cast<TruncInst>(A)->getOperand(0);
8732 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008733 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8734 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008735 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008736 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008737 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8738 CI.getName()), CI);
8739 return BinaryOperator::CreateAShr(I, ShAmtV);
8740 }
8741 }
8742
Chris Lattnerba417832007-04-11 06:12:58 +00008743 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008744}
8745
Chris Lattnerb7530652008-01-27 05:29:54 +00008746/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8747/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008748static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008749 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008750 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008751 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008752 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8753 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008754 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008755 return 0;
8756}
8757
8758/// LookThroughFPExtensions - If this is an fp extension instruction, look
8759/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008760static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008761 if (Instruction *I = dyn_cast<Instruction>(V))
8762 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008763 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008764
8765 // If this value is a constant, return the constant in the smallest FP type
8766 // that can accurately represent it. This allows us to turn
8767 // (float)((double)X+2.0) into x+2.0f.
8768 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8769 if (CFP->getType() == Type::PPC_FP128Ty)
8770 return V; // No constant folding of this.
8771 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008772 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008773 return V;
8774 if (CFP->getType() == Type::DoubleTy)
8775 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008776 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008777 return V;
8778 // Don't try to shrink to various long double types.
8779 }
8780
8781 return V;
8782}
8783
8784Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8785 if (Instruction *I = commonCastTransforms(CI))
8786 return I;
8787
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008788 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008789 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008790 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008791 // many builtins (sqrt, etc).
8792 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8793 if (OpI && OpI->hasOneUse()) {
8794 switch (OpI->getOpcode()) {
8795 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008796 case Instruction::FAdd:
8797 case Instruction::FSub:
8798 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008799 case Instruction::FDiv:
8800 case Instruction::FRem:
8801 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008802 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8803 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008804 if (LHSTrunc->getType() != SrcTy &&
8805 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008806 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008807 // If the source types were both smaller than the destination type of
8808 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008809 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8810 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008811 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8812 CI.getType(), CI);
8813 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8814 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008815 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008816 }
8817 }
8818 break;
8819 }
8820 }
8821 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008822}
8823
8824Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8825 return commonCastTransforms(CI);
8826}
8827
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008828Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008829 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8830 if (OpI == 0)
8831 return commonCastTransforms(FI);
8832
8833 // fptoui(uitofp(X)) --> X
8834 // fptoui(sitofp(X)) --> X
8835 // This is safe if the intermediate type has enough bits in its mantissa to
8836 // accurately represent all values of X. For example, do not do this with
8837 // i64->float->i64. This is also safe for sitofp case, because any negative
8838 // 'X' value would cause an undefined result for the fptoui.
8839 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8840 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008841 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008842 OpI->getType()->getFPMantissaWidth())
8843 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008844
8845 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008846}
8847
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008848Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008849 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8850 if (OpI == 0)
8851 return commonCastTransforms(FI);
8852
8853 // fptosi(sitofp(X)) --> X
8854 // fptosi(uitofp(X)) --> X
8855 // This is safe if the intermediate type has enough bits in its mantissa to
8856 // accurately represent all values of X. For example, do not do this with
8857 // i64->float->i64. This is also safe for sitofp case, because any negative
8858 // 'X' value would cause an undefined result for the fptoui.
8859 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8860 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008861 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008862 OpI->getType()->getFPMantissaWidth())
8863 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008864
8865 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008866}
8867
8868Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8869 return commonCastTransforms(CI);
8870}
8871
8872Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8873 return commonCastTransforms(CI);
8874}
8875
Chris Lattnera0e69692009-03-24 18:35:40 +00008876Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8877 // If the destination integer type is smaller than the intptr_t type for
8878 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8879 // trunc to be exposed to other transforms. Don't do this for extending
8880 // ptrtoint's, because we don't know if the target sign or zero extends its
8881 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008882 if (TD &&
8883 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008884 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8885 TD->getIntPtrType(),
8886 "tmp"), CI);
8887 return new TruncInst(P, CI.getType());
8888 }
8889
Chris Lattnerd3e28342007-04-27 17:44:50 +00008890 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008891}
8892
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008893Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008894 // If the source integer type is larger than the intptr_t type for
8895 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8896 // allows the trunc to be exposed to other transforms. Don't do this for
8897 // extending inttoptr's, because we don't know if the target sign or zero
8898 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008899 if (TD &&
8900 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008901 TD->getPointerSizeInBits()) {
8902 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8903 TD->getIntPtrType(),
8904 "tmp"), CI);
8905 return new IntToPtrInst(P, CI.getType());
8906 }
8907
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008908 if (Instruction *I = commonCastTransforms(CI))
8909 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008910
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008911 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008912}
8913
Chris Lattnerd3e28342007-04-27 17:44:50 +00008914Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008915 // If the operands are integer typed then apply the integer transforms,
8916 // otherwise just apply the common ones.
8917 Value *Src = CI.getOperand(0);
8918 const Type *SrcTy = Src->getType();
8919 const Type *DestTy = CI.getType();
8920
Eli Friedman7e25d452009-07-13 20:53:00 +00008921 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008922 if (Instruction *I = commonPointerCastTransforms(CI))
8923 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008924 } else {
8925 if (Instruction *Result = commonCastTransforms(CI))
8926 return Result;
8927 }
8928
8929
8930 // Get rid of casts from one type to the same type. These are useless and can
8931 // be replaced by the operand.
8932 if (DestTy == Src->getType())
8933 return ReplaceInstUsesWith(CI, Src);
8934
Reid Spencer3da59db2006-11-27 01:05:10 +00008935 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008936 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8937 const Type *DstElTy = DstPTy->getElementType();
8938 const Type *SrcElTy = SrcPTy->getElementType();
8939
Nate Begeman83ad90a2008-03-31 00:22:16 +00008940 // If the address spaces don't match, don't eliminate the bitcast, which is
8941 // required for changing types.
8942 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8943 return 0;
8944
Chris Lattnerd3e28342007-04-27 17:44:50 +00008945 // If we are casting a malloc or alloca to a pointer to a type of the same
8946 // size, rewrite the allocation instruction to allocate the "right" type.
8947 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8948 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8949 return V;
8950
Chris Lattnerd717c182007-05-05 22:32:24 +00008951 // If the source and destination are pointers, and this cast is equivalent
8952 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008953 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00008954 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008955 unsigned NumZeros = 0;
8956 while (SrcElTy != DstElTy &&
8957 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8958 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8959 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8960 ++NumZeros;
8961 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008962
Chris Lattnerd3e28342007-04-27 17:44:50 +00008963 // If we found a path from the src to dest, create the getelementptr now.
8964 if (SrcElTy == DstElTy) {
8965 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008966 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8967 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008968 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008969 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008970
Eli Friedman2451a642009-07-18 23:06:53 +00008971 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8972 if (DestVTy->getNumElements() == 1) {
8973 if (!isa<VectorType>(SrcTy)) {
8974 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8975 DestVTy->getElementType(), CI);
8976 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8977 Context->getNullValue(Type::Int32Ty));
8978 }
8979 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8980 }
8981 }
8982
8983 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8984 if (SrcVTy->getNumElements() == 1) {
8985 if (!isa<VectorType>(DestTy)) {
8986 Instruction *Elem =
8987 new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
8988 InsertNewInstBefore(Elem, CI);
8989 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8990 }
8991 }
8992 }
8993
Reid Spencer3da59db2006-11-27 01:05:10 +00008994 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8995 if (SVI->hasOneUse()) {
8996 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8997 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008998 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008999 cast<VectorType>(DestTy)->getNumElements() ==
9000 SVI->getType()->getNumElements() &&
9001 SVI->getType()->getNumElements() ==
9002 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009003 CastInst *Tmp;
9004 // If either of the operands is a cast from CI.getType(), then
9005 // evaluating the shuffle in the casted destination's type will allow
9006 // us to eliminate at least one cast.
9007 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9008 Tmp->getOperand(0)->getType() == DestTy) ||
9009 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9010 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009011 Value *LHS = InsertCastBefore(Instruction::BitCast,
9012 SVI->getOperand(0), DestTy, CI);
9013 Value *RHS = InsertCastBefore(Instruction::BitCast,
9014 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009015 // Return a new shuffle vector. Use the same element ID's, as we
9016 // know the vector types match #elts.
9017 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009018 }
9019 }
9020 }
9021 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009022 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009023}
9024
Chris Lattnere576b912004-04-09 23:46:01 +00009025/// GetSelectFoldableOperands - We want to turn code that looks like this:
9026/// %C = or %A, %B
9027/// %D = select %cond, %C, %A
9028/// into:
9029/// %C = select %cond, %B, 0
9030/// %D = or %A, %C
9031///
9032/// Assuming that the specified instruction is an operand to the select, return
9033/// a bitmask indicating which operands of this instruction are foldable if they
9034/// equal the other incoming value of the select.
9035///
9036static unsigned GetSelectFoldableOperands(Instruction *I) {
9037 switch (I->getOpcode()) {
9038 case Instruction::Add:
9039 case Instruction::Mul:
9040 case Instruction::And:
9041 case Instruction::Or:
9042 case Instruction::Xor:
9043 return 3; // Can fold through either operand.
9044 case Instruction::Sub: // Can only fold on the amount subtracted.
9045 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009046 case Instruction::LShr:
9047 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009048 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009049 default:
9050 return 0; // Cannot fold
9051 }
9052}
9053
9054/// GetSelectFoldableConstant - For the same transformation as the previous
9055/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009056static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009057 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009058 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009059 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009060 case Instruction::Add:
9061 case Instruction::Sub:
9062 case Instruction::Or:
9063 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009064 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009065 case Instruction::LShr:
9066 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009067 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009068 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009069 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009070 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009071 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009072 }
9073}
9074
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009075/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9076/// have the same opcode and only one use each. Try to simplify this.
9077Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9078 Instruction *FI) {
9079 if (TI->getNumOperands() == 1) {
9080 // If this is a non-volatile load or a cast from the same type,
9081 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009082 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009083 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9084 return 0;
9085 } else {
9086 return 0; // unknown unary op.
9087 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009088
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009089 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009090 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9091 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009092 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009093 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009094 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009095 }
9096
Reid Spencer832254e2007-02-02 02:16:23 +00009097 // Only handle binary operators here.
9098 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009099 return 0;
9100
9101 // Figure out if the operations have any operands in common.
9102 Value *MatchOp, *OtherOpT, *OtherOpF;
9103 bool MatchIsOpZero;
9104 if (TI->getOperand(0) == FI->getOperand(0)) {
9105 MatchOp = TI->getOperand(0);
9106 OtherOpT = TI->getOperand(1);
9107 OtherOpF = FI->getOperand(1);
9108 MatchIsOpZero = true;
9109 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9110 MatchOp = TI->getOperand(1);
9111 OtherOpT = TI->getOperand(0);
9112 OtherOpF = FI->getOperand(0);
9113 MatchIsOpZero = false;
9114 } else if (!TI->isCommutative()) {
9115 return 0;
9116 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9117 MatchOp = TI->getOperand(0);
9118 OtherOpT = TI->getOperand(1);
9119 OtherOpF = FI->getOperand(0);
9120 MatchIsOpZero = true;
9121 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9122 MatchOp = TI->getOperand(1);
9123 OtherOpT = TI->getOperand(0);
9124 OtherOpF = FI->getOperand(1);
9125 MatchIsOpZero = true;
9126 } else {
9127 return 0;
9128 }
9129
9130 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009131 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9132 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009133 InsertNewInstBefore(NewSI, SI);
9134
9135 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9136 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009137 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009138 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009139 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009140 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009141 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009142 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009143}
9144
Evan Chengde621922009-03-31 20:42:45 +00009145static bool isSelect01(Constant *C1, Constant *C2) {
9146 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9147 if (!C1I)
9148 return false;
9149 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9150 if (!C2I)
9151 return false;
9152 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9153}
9154
9155/// FoldSelectIntoOp - Try fold the select into one of the operands to
9156/// facilitate further optimization.
9157Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9158 Value *FalseVal) {
9159 // See the comment above GetSelectFoldableOperands for a description of the
9160 // transformation we are doing here.
9161 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9162 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9163 !isa<Constant>(FalseVal)) {
9164 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9165 unsigned OpToFold = 0;
9166 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9167 OpToFold = 1;
9168 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9169 OpToFold = 2;
9170 }
9171
9172 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009173 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009174 Value *OOp = TVI->getOperand(2-OpToFold);
9175 // Avoid creating select between 2 constants unless it's selecting
9176 // between 0 and 1.
9177 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9178 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9179 InsertNewInstBefore(NewSel, SI);
9180 NewSel->takeName(TVI);
9181 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9182 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009183 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009184 }
9185 }
9186 }
9187 }
9188 }
9189
9190 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9191 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9192 !isa<Constant>(TrueVal)) {
9193 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9194 unsigned OpToFold = 0;
9195 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9196 OpToFold = 1;
9197 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9198 OpToFold = 2;
9199 }
9200
9201 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009202 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009203 Value *OOp = FVI->getOperand(2-OpToFold);
9204 // Avoid creating select between 2 constants unless it's selecting
9205 // between 0 and 1.
9206 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9207 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9208 InsertNewInstBefore(NewSel, SI);
9209 NewSel->takeName(FVI);
9210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9211 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009212 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009213 }
9214 }
9215 }
9216 }
9217 }
9218
9219 return 0;
9220}
9221
Dan Gohman81b28ce2008-09-16 18:46:06 +00009222/// visitSelectInstWithICmp - Visit a SelectInst that has an
9223/// ICmpInst as its first operand.
9224///
9225Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9226 ICmpInst *ICI) {
9227 bool Changed = false;
9228 ICmpInst::Predicate Pred = ICI->getPredicate();
9229 Value *CmpLHS = ICI->getOperand(0);
9230 Value *CmpRHS = ICI->getOperand(1);
9231 Value *TrueVal = SI.getTrueValue();
9232 Value *FalseVal = SI.getFalseValue();
9233
9234 // Check cases where the comparison is with a constant that
9235 // can be adjusted to fit the min/max idiom. We may edit ICI in
9236 // place here, so make sure the select is the only user.
9237 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009238 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009239 switch (Pred) {
9240 default: break;
9241 case ICmpInst::ICMP_ULT:
9242 case ICmpInst::ICMP_SLT: {
9243 // X < MIN ? T : F --> F
9244 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9245 return ReplaceInstUsesWith(SI, FalseVal);
9246 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009247 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009248 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9249 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9250 Pred = ICmpInst::getSwappedPredicate(Pred);
9251 CmpRHS = AdjustedRHS;
9252 std::swap(FalseVal, TrueVal);
9253 ICI->setPredicate(Pred);
9254 ICI->setOperand(1, CmpRHS);
9255 SI.setOperand(1, TrueVal);
9256 SI.setOperand(2, FalseVal);
9257 Changed = true;
9258 }
9259 break;
9260 }
9261 case ICmpInst::ICMP_UGT:
9262 case ICmpInst::ICMP_SGT: {
9263 // X > MAX ? T : F --> F
9264 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9265 return ReplaceInstUsesWith(SI, FalseVal);
9266 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009267 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009268 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9269 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9270 Pred = ICmpInst::getSwappedPredicate(Pred);
9271 CmpRHS = AdjustedRHS;
9272 std::swap(FalseVal, TrueVal);
9273 ICI->setPredicate(Pred);
9274 ICI->setOperand(1, CmpRHS);
9275 SI.setOperand(1, TrueVal);
9276 SI.setOperand(2, FalseVal);
9277 Changed = true;
9278 }
9279 break;
9280 }
9281 }
9282
Dan Gohman1975d032008-10-30 20:40:10 +00009283 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9284 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009285 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009286 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9287 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009288 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009289 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9290 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009291 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9292
Dan Gohman1975d032008-10-30 20:40:10 +00009293 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9294 // If we are just checking for a icmp eq of a single bit and zext'ing it
9295 // to an integer, then shift the bit to the appropriate place and then
9296 // cast to integer to avoid the comparison.
9297 const APInt &Op1CV = CI->getValue();
9298
9299 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9300 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9301 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009302 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009303 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009304 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009305 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009306 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9307 In->getName()+".lobit"),
9308 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009309 if (In->getType() != SI.getType())
9310 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009311 true/*SExt*/, "tmp", ICI);
9312
9313 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009314 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009315 In->getName()+".not"), *ICI);
9316
9317 return ReplaceInstUsesWith(SI, In);
9318 }
9319 }
9320 }
9321
Dan Gohman81b28ce2008-09-16 18:46:06 +00009322 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9323 // Transform (X == Y) ? X : Y -> Y
9324 if (Pred == ICmpInst::ICMP_EQ)
9325 return ReplaceInstUsesWith(SI, FalseVal);
9326 // Transform (X != Y) ? X : Y -> X
9327 if (Pred == ICmpInst::ICMP_NE)
9328 return ReplaceInstUsesWith(SI, TrueVal);
9329 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9330
9331 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9332 // Transform (X == Y) ? Y : X -> X
9333 if (Pred == ICmpInst::ICMP_EQ)
9334 return ReplaceInstUsesWith(SI, FalseVal);
9335 // Transform (X != Y) ? Y : X -> Y
9336 if (Pred == ICmpInst::ICMP_NE)
9337 return ReplaceInstUsesWith(SI, TrueVal);
9338 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9339 }
9340
9341 /// NOTE: if we wanted to, this is where to detect integer ABS
9342
9343 return Changed ? &SI : 0;
9344}
9345
Chris Lattner3d69f462004-03-12 05:52:32 +00009346Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009347 Value *CondVal = SI.getCondition();
9348 Value *TrueVal = SI.getTrueValue();
9349 Value *FalseVal = SI.getFalseValue();
9350
9351 // select true, X, Y -> X
9352 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009353 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009354 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009355
9356 // select C, X, X -> X
9357 if (TrueVal == FalseVal)
9358 return ReplaceInstUsesWith(SI, TrueVal);
9359
Chris Lattnere87597f2004-10-16 18:11:37 +00009360 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9361 return ReplaceInstUsesWith(SI, FalseVal);
9362 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9363 return ReplaceInstUsesWith(SI, TrueVal);
9364 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9365 if (isa<Constant>(TrueVal))
9366 return ReplaceInstUsesWith(SI, TrueVal);
9367 else
9368 return ReplaceInstUsesWith(SI, FalseVal);
9369 }
9370
Reid Spencer4fe16d62007-01-11 18:21:29 +00009371 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009372 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009373 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009374 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009375 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009376 } else {
9377 // Change: A = select B, false, C --> A = and !B, C
9378 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009379 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009380 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009381 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009382 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009383 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009384 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009385 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009386 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009387 } else {
9388 // Change: A = select B, C, true --> A = or !B, C
9389 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009390 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009391 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009392 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009393 }
9394 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009395
9396 // select a, b, a -> a&b
9397 // select a, a, b -> a|b
9398 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009399 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009400 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009401 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009402 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009403
Chris Lattner2eefe512004-04-09 19:05:30 +00009404 // Selecting between two integer constants?
9405 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9406 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009407 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009408 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009409 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009410 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009411 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009412 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009413 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009414 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009415 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009416 }
Chris Lattner457dd822004-06-09 07:59:58 +00009417
Reid Spencere4d87aa2006-12-23 06:05:41 +00009418 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009419 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009420 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009421 // non-constant value, eliminate this whole mess. This corresponds to
9422 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009423 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009424 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009425 cast<Constant>(IC->getOperand(1))->isNullValue())
9426 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9427 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009428 isa<ConstantInt>(ICA->getOperand(1)) &&
9429 (ICA->getOperand(1) == TrueValC ||
9430 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009431 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9432 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009433 // know whether we have a icmp_ne or icmp_eq and whether the
9434 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009435 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009436 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009437 Value *V = ICA;
9438 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009439 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009440 Instruction::Xor, V, ICA->getOperand(1)), SI);
9441 return ReplaceInstUsesWith(SI, V);
9442 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009443 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009444 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009445
9446 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009447 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9448 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009449 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009450 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9451 // This is not safe in general for floating point:
9452 // consider X== -0, Y== +0.
9453 // It becomes safe if either operand is a nonzero constant.
9454 ConstantFP *CFPt, *CFPf;
9455 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9456 !CFPt->getValueAPF().isZero()) ||
9457 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9458 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009459 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009460 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009461 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009462 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009463 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009464 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009465
Reid Spencere4d87aa2006-12-23 06:05:41 +00009466 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009467 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009468 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9469 // This is not safe in general for floating point:
9470 // consider X== -0, Y== +0.
9471 // It becomes safe if either operand is a nonzero constant.
9472 ConstantFP *CFPt, *CFPf;
9473 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9474 !CFPt->getValueAPF().isZero()) ||
9475 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9476 !CFPf->getValueAPF().isZero()))
9477 return ReplaceInstUsesWith(SI, FalseVal);
9478 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009479 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009480 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9481 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009482 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009483 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009484 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009485 }
9486
9487 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009488 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9489 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9490 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009491
Chris Lattner87875da2005-01-13 22:52:24 +00009492 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9493 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9494 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009495 Instruction *AddOp = 0, *SubOp = 0;
9496
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009497 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9498 if (TI->getOpcode() == FI->getOpcode())
9499 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9500 return IV;
9501
9502 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9503 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009504 if ((TI->getOpcode() == Instruction::Sub &&
9505 FI->getOpcode() == Instruction::Add) ||
9506 (TI->getOpcode() == Instruction::FSub &&
9507 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009508 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009509 } else if ((FI->getOpcode() == Instruction::Sub &&
9510 TI->getOpcode() == Instruction::Add) ||
9511 (FI->getOpcode() == Instruction::FSub &&
9512 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009513 AddOp = TI; SubOp = FI;
9514 }
9515
9516 if (AddOp) {
9517 Value *OtherAddOp = 0;
9518 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9519 OtherAddOp = AddOp->getOperand(1);
9520 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9521 OtherAddOp = AddOp->getOperand(0);
9522 }
9523
9524 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009525 // So at this point we know we have (Y -> OtherAddOp):
9526 // select C, (add X, Y), (sub X, Z)
9527 Value *NegVal; // Compute -Z
9528 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009529 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009530 } else {
9531 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009532 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9533 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009534 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009535
9536 Value *NewTrueOp = OtherAddOp;
9537 Value *NewFalseOp = NegVal;
9538 if (AddOp != TI)
9539 std::swap(NewTrueOp, NewFalseOp);
9540 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009541 SelectInst::Create(CondVal, NewTrueOp,
9542 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009543
9544 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009545 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009546 }
9547 }
9548 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009549
Chris Lattnere576b912004-04-09 23:46:01 +00009550 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009551 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009552 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9553 if (FoldI)
9554 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009555 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009556
9557 if (BinaryOperator::isNot(CondVal)) {
9558 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9559 SI.setOperand(1, FalseVal);
9560 SI.setOperand(2, TrueVal);
9561 return &SI;
9562 }
9563
Chris Lattner3d69f462004-03-12 05:52:32 +00009564 return 0;
9565}
9566
Dan Gohmaneee962e2008-04-10 18:43:06 +00009567/// EnforceKnownAlignment - If the specified pointer points to an object that
9568/// we control, modify the object's alignment to PrefAlign. This isn't
9569/// often possible though. If alignment is important, a more reliable approach
9570/// is to simply align all global variables and allocation instructions to
9571/// their preferred alignment from the beginning.
9572///
9573static unsigned EnforceKnownAlignment(Value *V,
9574 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009575
Dan Gohmaneee962e2008-04-10 18:43:06 +00009576 User *U = dyn_cast<User>(V);
9577 if (!U) return Align;
9578
Dan Gohmanca178902009-07-17 20:47:02 +00009579 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009580 default: break;
9581 case Instruction::BitCast:
9582 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9583 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009584 // If all indexes are zero, it is just the alignment of the base pointer.
9585 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009586 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009587 if (!isa<Constant>(*i) ||
9588 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009589 AllZeroOperands = false;
9590 break;
9591 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009592
9593 if (AllZeroOperands) {
9594 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009595 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009596 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009597 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009598 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009599 }
9600
9601 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9602 // If there is a large requested alignment and we can, bump up the alignment
9603 // of the global.
9604 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009605 if (GV->getAlignment() >= PrefAlign)
9606 Align = GV->getAlignment();
9607 else {
9608 GV->setAlignment(PrefAlign);
9609 Align = PrefAlign;
9610 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009611 }
9612 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9613 // If there is a requested alignment and if this is an alloca, round up. We
9614 // don't do this for malloc, because some systems can't respect the request.
9615 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009616 if (AI->getAlignment() >= PrefAlign)
9617 Align = AI->getAlignment();
9618 else {
9619 AI->setAlignment(PrefAlign);
9620 Align = PrefAlign;
9621 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009622 }
9623 }
9624
9625 return Align;
9626}
9627
9628/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9629/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9630/// and it is more than the alignment of the ultimate object, see if we can
9631/// increase the alignment of the ultimate object, making this check succeed.
9632unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9633 unsigned PrefAlign) {
9634 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9635 sizeof(PrefAlign) * CHAR_BIT;
9636 APInt Mask = APInt::getAllOnesValue(BitWidth);
9637 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9638 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9639 unsigned TrailZ = KnownZero.countTrailingOnes();
9640 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9641
9642 if (PrefAlign > Align)
9643 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9644
9645 // We don't need to make any adjustment.
9646 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009647}
9648
Chris Lattnerf497b022008-01-13 23:50:23 +00009649Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009650 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009651 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009652 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009653 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009654
9655 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009656 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9657 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009658 return MI;
9659 }
9660
9661 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9662 // load/store.
9663 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9664 if (MemOpLength == 0) return 0;
9665
Chris Lattner37ac6082008-01-14 00:28:35 +00009666 // Source and destination pointer types are always "i8*" for intrinsic. See
9667 // if the size is something we can handle with a single primitive load/store.
9668 // A single load+store correctly handles overlapping memory in the memmove
9669 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009670 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009671 if (Size == 0) return MI; // Delete this mem transfer.
9672
9673 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009674 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009675
Chris Lattner37ac6082008-01-14 00:28:35 +00009676 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009677 Type *NewPtrTy =
9678 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009679
9680 // Memcpy forces the use of i8* for the source and destination. That means
9681 // that if you're using memcpy to move one double around, you'll get a cast
9682 // from double* to i8*. We'd much rather use a double load+store rather than
9683 // an i64 load+store, here because this improves the odds that the source or
9684 // dest address will be promotable. See if we can find a better type than the
9685 // integer datatype.
9686 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9687 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009688 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009689 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9690 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009691 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009692 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9693 if (STy->getNumElements() == 1)
9694 SrcETy = STy->getElementType(0);
9695 else
9696 break;
9697 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9698 if (ATy->getNumElements() == 1)
9699 SrcETy = ATy->getElementType();
9700 else
9701 break;
9702 } else
9703 break;
9704 }
9705
Dan Gohman8f8e2692008-05-23 01:52:21 +00009706 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009707 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009708 }
9709 }
9710
9711
Chris Lattnerf497b022008-01-13 23:50:23 +00009712 // If the memcpy/memmove provides better alignment info than we can
9713 // infer, use it.
9714 SrcAlign = std::max(SrcAlign, CopyAlign);
9715 DstAlign = std::max(DstAlign, CopyAlign);
9716
9717 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9718 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009719 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9720 InsertNewInstBefore(L, *MI);
9721 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9722
9723 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009724 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009725 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009726}
Chris Lattner3d69f462004-03-12 05:52:32 +00009727
Chris Lattner69ea9d22008-04-30 06:39:11 +00009728Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9729 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009730 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009731 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9732 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009733 return MI;
9734 }
9735
9736 // Extract the length and alignment and fill if they are constant.
9737 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9738 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9739 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9740 return 0;
9741 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009742 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009743
9744 // If the length is zero, this is a no-op
9745 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9746
9747 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9748 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009749 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009750
9751 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009752 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009753
9754 // Alignment 0 is identity for alignment 1 for memset, but not store.
9755 if (Alignment == 0) Alignment = 1;
9756
9757 // Extract the fill value and store.
9758 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009759 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9760 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009761
9762 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009763 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009764 return MI;
9765 }
9766
9767 return 0;
9768}
9769
9770
Chris Lattner8b0ea312006-01-13 20:11:04 +00009771/// visitCallInst - CallInst simplification. This mostly only handles folding
9772/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9773/// the heavy lifting.
9774///
Chris Lattner9fe38862003-06-19 17:00:31 +00009775Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009776 // If the caller function is nounwind, mark the call as nounwind, even if the
9777 // callee isn't.
9778 if (CI.getParent()->getParent()->doesNotThrow() &&
9779 !CI.doesNotThrow()) {
9780 CI.setDoesNotThrow();
9781 return &CI;
9782 }
9783
9784
9785
Chris Lattner8b0ea312006-01-13 20:11:04 +00009786 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9787 if (!II) return visitCallSite(&CI);
9788
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009789 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9790 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009791 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009792 bool Changed = false;
9793
9794 // memmove/cpy/set of zero bytes is a noop.
9795 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9796 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9797
Chris Lattner35b9e482004-10-12 04:52:52 +00009798 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009799 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009800 // Replace the instruction with just byte operations. We would
9801 // transform other cases to loads/stores, but we don't know if
9802 // alignment is sufficient.
9803 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009804 }
9805
Chris Lattner35b9e482004-10-12 04:52:52 +00009806 // If we have a memmove and the source operation is a constant global,
9807 // then the source and dest pointers can't alias, so we can change this
9808 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009809 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009810 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9811 if (GVSrc->isConstant()) {
9812 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009813 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9814 const Type *Tys[1];
9815 Tys[0] = CI.getOperand(3)->getType();
9816 CI.setOperand(0,
9817 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009818 Changed = true;
9819 }
Chris Lattnera935db82008-05-28 05:30:41 +00009820
9821 // memmove(x,x,size) -> noop.
9822 if (MMI->getSource() == MMI->getDest())
9823 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009824 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009825
Chris Lattner95a959d2006-03-06 20:18:44 +00009826 // If we can determine a pointer alignment that is bigger than currently
9827 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009828 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009829 if (Instruction *I = SimplifyMemTransfer(MI))
9830 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009831 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9832 if (Instruction *I = SimplifyMemSet(MSI))
9833 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009834 }
9835
Chris Lattner8b0ea312006-01-13 20:11:04 +00009836 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009837 }
9838
9839 switch (II->getIntrinsicID()) {
9840 default: break;
9841 case Intrinsic::bswap:
9842 // bswap(bswap(x)) -> x
9843 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9844 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9845 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9846 break;
9847 case Intrinsic::ppc_altivec_lvx:
9848 case Intrinsic::ppc_altivec_lvxl:
9849 case Intrinsic::x86_sse_loadu_ps:
9850 case Intrinsic::x86_sse2_loadu_pd:
9851 case Intrinsic::x86_sse2_loadu_dq:
9852 // Turn PPC lvx -> load if the pointer is known aligned.
9853 // Turn X86 loadups -> load if the pointer is known aligned.
9854 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9855 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009856 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009857 CI);
9858 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009859 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009860 break;
9861 case Intrinsic::ppc_altivec_stvx:
9862 case Intrinsic::ppc_altivec_stvxl:
9863 // Turn stvx -> store if the pointer is known aligned.
9864 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9865 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009866 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009867 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9868 return new StoreInst(II->getOperand(1), Ptr);
9869 }
9870 break;
9871 case Intrinsic::x86_sse_storeu_ps:
9872 case Intrinsic::x86_sse2_storeu_pd:
9873 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009874 // Turn X86 storeu -> store if the pointer is known aligned.
9875 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9876 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009877 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009878 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9879 return new StoreInst(II->getOperand(2), Ptr);
9880 }
9881 break;
9882
9883 case Intrinsic::x86_sse_cvttss2si: {
9884 // These intrinsics only demands the 0th element of its input vector. If
9885 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009886 unsigned VWidth =
9887 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9888 APInt DemandedElts(VWidth, 1);
9889 APInt UndefElts(VWidth, 0);
9890 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009891 UndefElts)) {
9892 II->setOperand(1, V);
9893 return II;
9894 }
9895 break;
9896 }
9897
9898 case Intrinsic::ppc_altivec_vperm:
9899 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9900 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9901 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009902
Chris Lattner0521e3c2008-06-18 04:33:20 +00009903 // Check that all of the elements are integer constants or undefs.
9904 bool AllEltsOk = true;
9905 for (unsigned i = 0; i != 16; ++i) {
9906 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9907 !isa<UndefValue>(Mask->getOperand(i))) {
9908 AllEltsOk = false;
9909 break;
9910 }
9911 }
9912
9913 if (AllEltsOk) {
9914 // Cast the input vectors to byte vectors.
9915 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9916 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009917 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009918
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 // Only extract each element once.
9920 Value *ExtractedElts[32];
9921 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9922
Chris Lattnere2ed0572006-04-06 19:19:17 +00009923 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009924 if (isa<UndefValue>(Mask->getOperand(i)))
9925 continue;
9926 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9927 Idx &= 31; // Match the hardware behavior.
9928
9929 if (ExtractedElts[Idx] == 0) {
9930 Instruction *Elt =
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009931 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9932 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009933 InsertNewInstBefore(Elt, CI);
9934 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009935 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009936
Chris Lattner0521e3c2008-06-18 04:33:20 +00009937 // Insert this value into the result vector.
9938 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009939 Context->getConstantInt(Type::Int32Ty, i, false),
9940 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009941 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009942 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009943 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009944 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009945 }
9946 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009947
Chris Lattner0521e3c2008-06-18 04:33:20 +00009948 case Intrinsic::stackrestore: {
9949 // If the save is right next to the restore, remove the restore. This can
9950 // happen when variable allocas are DCE'd.
9951 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9952 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9953 BasicBlock::iterator BI = SS;
9954 if (&*++BI == II)
9955 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009956 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009957 }
9958
9959 // Scan down this block to see if there is another stack restore in the
9960 // same block without an intervening call/alloca.
9961 BasicBlock::iterator BI = II;
9962 TerminatorInst *TI = II->getParent()->getTerminator();
9963 bool CannotRemove = false;
9964 for (++BI; &*BI != TI; ++BI) {
9965 if (isa<AllocaInst>(BI)) {
9966 CannotRemove = true;
9967 break;
9968 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009969 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9970 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9971 // If there is a stackrestore below this one, remove this one.
9972 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9973 return EraseInstFromFunction(CI);
9974 // Otherwise, ignore the intrinsic.
9975 } else {
9976 // If we found a non-intrinsic call, we can't remove the stack
9977 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009978 CannotRemove = true;
9979 break;
9980 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009981 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009982 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009983
9984 // If the stack restore is in a return/unwind block and if there are no
9985 // allocas or calls between the restore and the return, nuke the restore.
9986 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9987 return EraseInstFromFunction(CI);
9988 break;
9989 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009990 }
9991
Chris Lattner8b0ea312006-01-13 20:11:04 +00009992 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009993}
9994
9995// InvokeInst simplification
9996//
9997Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009998 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009999}
10000
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010001/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10002/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010003static bool isSafeToEliminateVarargsCast(const CallSite CS,
10004 const CastInst * const CI,
10005 const TargetData * const TD,
10006 const int ix) {
10007 if (!CI->isLosslessCast())
10008 return false;
10009
10010 // The size of ByVal arguments is derived from the type, so we
10011 // can't change to a type with a different size. If the size were
10012 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010013 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010014 return true;
10015
10016 const Type* SrcTy =
10017 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10018 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10019 if (!SrcTy->isSized() || !DstTy->isSized())
10020 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010021 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010022 return false;
10023 return true;
10024}
10025
Chris Lattnera44d8a22003-10-07 22:32:43 +000010026// visitCallSite - Improvements for call and invoke instructions.
10027//
10028Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010029 bool Changed = false;
10030
10031 // If the callee is a constexpr cast of a function, attempt to move the cast
10032 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010033 if (transformConstExprCastCall(CS)) return 0;
10034
Chris Lattner6c266db2003-10-07 22:54:13 +000010035 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010036
Chris Lattner08b22ec2005-05-13 07:09:09 +000010037 if (Function *CalleeF = dyn_cast<Function>(Callee))
10038 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10039 Instruction *OldCall = CS.getInstruction();
10040 // If the call and callee calling conventions don't match, this call must
10041 // be unreachable, as the call is undefined.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010042 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010043 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10044 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010045 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010046 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010047 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10048 return EraseInstFromFunction(*OldCall);
10049 return 0;
10050 }
10051
Chris Lattner17be6352004-10-18 02:59:09 +000010052 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10053 // This instruction is not reachable, just remove it. We insert a store to
10054 // undef so that we know that this code is not reachable, despite the fact
10055 // that we can't modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010056 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010057 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010058 CS.getInstruction());
10059
10060 if (!CS.getInstruction()->use_empty())
10061 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010062 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010063
10064 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10065 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010066 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersonb3056fa2009-07-21 18:03:38 +000010067 Context->getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010068 }
Chris Lattner17be6352004-10-18 02:59:09 +000010069 return EraseInstFromFunction(*CS.getInstruction());
10070 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010071
Duncan Sandscdb6d922007-09-17 10:26:40 +000010072 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10073 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10074 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10075 return transformCallThroughTrampoline(CS);
10076
Chris Lattner6c266db2003-10-07 22:54:13 +000010077 const PointerType *PTy = cast<PointerType>(Callee->getType());
10078 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10079 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010080 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010081 // See if we can optimize any arguments passed through the varargs area of
10082 // the call.
10083 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010084 E = CS.arg_end(); I != E; ++I, ++ix) {
10085 CastInst *CI = dyn_cast<CastInst>(*I);
10086 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10087 *I = CI->getOperand(0);
10088 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010089 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010090 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010091 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010092
Duncan Sandsf0c33542007-12-19 21:13:37 +000010093 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010094 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010095 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010096 Changed = true;
10097 }
10098
Chris Lattner6c266db2003-10-07 22:54:13 +000010099 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010100}
10101
Chris Lattner9fe38862003-06-19 17:00:31 +000010102// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10103// attempt to move the cast to the arguments of the call/invoke.
10104//
10105bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10106 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10107 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010108 if (CE->getOpcode() != Instruction::BitCast ||
10109 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010110 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010111 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010112 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010113 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010114
10115 // Okay, this is a cast from a function to a different type. Unless doing so
10116 // would cause a type conversion of one of our arguments, change this call to
10117 // be a direct call with arguments casted to the appropriate types.
10118 //
10119 const FunctionType *FT = Callee->getFunctionType();
10120 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010121 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010122
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010123 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010124 return false; // TODO: Handle multiple return values.
10125
Chris Lattnerf78616b2004-01-14 06:06:08 +000010126 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010127 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010128 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010129 // Conversion is ok if changing from one pointer type to another or from
10130 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010131 !((isa<PointerType>(OldRetTy) || !TD ||
10132 OldRetTy == TD->getIntPtrType()) &&
10133 (isa<PointerType>(NewRetTy) || !TD ||
10134 NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010135 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010136
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010137 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010138 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010139 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010140 return false; // Cannot transform this return value.
10141
Chris Lattner58d74912008-03-12 17:45:29 +000010142 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010143 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010144 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010145 return false; // Attribute not compatible with transformed value.
10146 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010147
Chris Lattnerf78616b2004-01-14 06:06:08 +000010148 // If the callsite is an invoke instruction, and the return value is used by
10149 // a PHI node in a successor, we cannot change the return type of the call
10150 // because there is no place to put the cast instruction (without breaking
10151 // the critical edge). Bail out in this case.
10152 if (!Caller->use_empty())
10153 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10154 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10155 UI != E; ++UI)
10156 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10157 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010158 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010159 return false;
10160 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010161
10162 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10163 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010164
Chris Lattner9fe38862003-06-19 17:00:31 +000010165 CallSite::arg_iterator AI = CS.arg_begin();
10166 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10167 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010168 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010169
10170 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010171 return false; // Cannot transform this parameter value.
10172
Devang Patel19c87462008-09-26 22:53:05 +000010173 if (CallerPAL.getParamAttributes(i + 1)
10174 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010175 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010176
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010177 // Converting from one pointer type to another or between a pointer and an
10178 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010179 bool isConvertible = ActTy == ParamTy ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010180 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10181 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010182 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010183 }
10184
10185 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010186 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010187 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010188
Chris Lattner58d74912008-03-12 17:45:29 +000010189 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10190 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010191 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010192 // won't be dropping them. Check that these extra arguments have attributes
10193 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010194 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10195 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010196 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010197 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010198 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010199 return false;
10200 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010201
Chris Lattner9fe38862003-06-19 17:00:31 +000010202 // Okay, we decided that this is a safe thing to do: go ahead and start
10203 // inserting cast instructions as necessary...
10204 std::vector<Value*> Args;
10205 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010206 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010207 attrVec.reserve(NumCommonArgs);
10208
10209 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010210 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010211
10212 // If the return value is not being used, the type may not be compatible
10213 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010214 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010215
10216 // Add the new return attributes.
10217 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010218 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010219
10220 AI = CS.arg_begin();
10221 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10222 const Type *ParamTy = FT->getParamType(i);
10223 if ((*AI)->getType() == ParamTy) {
10224 Args.push_back(*AI);
10225 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010226 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010227 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010228 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010229 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010230 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010231
10232 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010233 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010234 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010235 }
10236
10237 // If the function takes more arguments than the call was taking, add them
10238 // now...
10239 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010240 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010241
10242 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010243 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010244 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010245 cerr << "WARNING: While resolving call to function '"
10246 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010247 } else {
10248 // Add all of the arguments in their promoted form to the arg list...
10249 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10250 const Type *PTy = getPromotedType((*AI)->getType());
10251 if (PTy != (*AI)->getType()) {
10252 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010253 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10254 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010255 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010256 InsertNewInstBefore(Cast, *Caller);
10257 Args.push_back(Cast);
10258 } else {
10259 Args.push_back(*AI);
10260 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010261
Duncan Sandse1e520f2008-01-13 08:02:44 +000010262 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010263 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010264 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010265 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010266 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010267 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010268
Devang Patel19c87462008-09-26 22:53:05 +000010269 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10270 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10271
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010272 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010273 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010274
Devang Patel05988662008-09-25 21:00:45 +000010275 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010276
Chris Lattner9fe38862003-06-19 17:00:31 +000010277 Instruction *NC;
10278 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010279 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010280 Args.begin(), Args.end(),
10281 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010282 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010283 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010284 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010285 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10286 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010287 CallInst *CI = cast<CallInst>(Caller);
10288 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010289 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010290 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010291 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010292 }
10293
Chris Lattner6934a042007-02-11 01:23:03 +000010294 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010295 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010296 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010297 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010298 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010299 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010300 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010301
10302 // If this is an invoke instruction, we should insert it after the first
10303 // non-phi, instruction in the normal successor block.
10304 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010305 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010306 InsertNewInstBefore(NC, *I);
10307 } else {
10308 // Otherwise, it's a call, just insert cast right after the call instr
10309 InsertNewInstBefore(NC, *Caller);
10310 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010311 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010312 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010313 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010314 }
10315 }
10316
10317 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10318 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010319 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010320 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010321 return true;
10322}
10323
Duncan Sandscdb6d922007-09-17 10:26:40 +000010324// transformCallThroughTrampoline - Turn a call to a function created by the
10325// init_trampoline intrinsic into a direct call to the underlying function.
10326//
10327Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10328 Value *Callee = CS.getCalledValue();
10329 const PointerType *PTy = cast<PointerType>(Callee->getType());
10330 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010331 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010332
10333 // If the call already has the 'nest' attribute somewhere then give up -
10334 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010335 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010336 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010337
10338 IntrinsicInst *Tramp =
10339 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10340
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010341 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010342 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10343 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10344
Devang Patel05988662008-09-25 21:00:45 +000010345 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010346 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010347 unsigned NestIdx = 1;
10348 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010349 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010350
10351 // Look for a parameter marked with the 'nest' attribute.
10352 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10353 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010354 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010355 // Record the parameter type and any other attributes.
10356 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010357 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010358 break;
10359 }
10360
10361 if (NestTy) {
10362 Instruction *Caller = CS.getInstruction();
10363 std::vector<Value*> NewArgs;
10364 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10365
Devang Patel05988662008-09-25 21:00:45 +000010366 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010367 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010368
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010370 // mean appending it. Likewise for attributes.
10371
Devang Patel19c87462008-09-26 22:53:05 +000010372 // Add any result attributes.
10373 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010374 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010375
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 {
10377 unsigned Idx = 1;
10378 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10379 do {
10380 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010381 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010382 Value *NestVal = Tramp->getOperand(3);
10383 if (NestVal->getType() != NestTy)
10384 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10385 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010386 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387 }
10388
10389 if (I == E)
10390 break;
10391
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010392 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010393 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010394 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010395 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010396 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010397
10398 ++Idx, ++I;
10399 } while (1);
10400 }
10401
Devang Patel19c87462008-09-26 22:53:05 +000010402 // Add any function attributes.
10403 if (Attributes Attr = Attrs.getFnAttributes())
10404 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10405
Duncan Sandscdb6d922007-09-17 10:26:40 +000010406 // The trampoline may have been bitcast to a bogus type (FTy).
10407 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010408 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010409
Duncan Sandscdb6d922007-09-17 10:26:40 +000010410 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010411 NewTypes.reserve(FTy->getNumParams()+1);
10412
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010414 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010415 {
10416 unsigned Idx = 1;
10417 FunctionType::param_iterator I = FTy->param_begin(),
10418 E = FTy->param_end();
10419
10420 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010421 if (Idx == NestIdx)
10422 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010423 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010424
10425 if (I == E)
10426 break;
10427
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010428 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010429 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430
10431 ++Idx, ++I;
10432 } while (1);
10433 }
10434
10435 // Replace the trampoline call with a direct call. Let the generic
10436 // code sort out any function type mismatches.
10437 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010438 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10439 FTy->isVarArg());
10440 Constant *NewCallee =
10441 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10442 NestF : Context->getConstantExprBitCast(NestF,
10443 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010444 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010445
10446 Instruction *NewCaller;
10447 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010448 NewCaller = InvokeInst::Create(NewCallee,
10449 II->getNormalDest(), II->getUnwindDest(),
10450 NewArgs.begin(), NewArgs.end(),
10451 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010453 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010454 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010455 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10456 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010457 if (cast<CallInst>(Caller)->isTailCall())
10458 cast<CallInst>(NewCaller)->setTailCall();
10459 cast<CallInst>(NewCaller)->
10460 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010461 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010462 }
10463 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10464 Caller->replaceAllUsesWith(NewCaller);
10465 Caller->eraseFromParent();
10466 RemoveFromWorkList(Caller);
10467 return 0;
10468 }
10469 }
10470
10471 // Replace the trampoline call with a direct call. Since there is no 'nest'
10472 // parameter, there is no need to adjust the argument list. Let the generic
10473 // code sort out any function type mismatches.
10474 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010475 NestF->getType() == PTy ? NestF :
10476 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010477 CS.setCalledFunction(NewCallee);
10478 return CS.getInstruction();
10479}
10480
Chris Lattner7da52b22006-11-01 04:51:18 +000010481/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10482/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10483/// and a single binop.
10484Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10485 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010486 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010487 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010488 Value *LHSVal = FirstInst->getOperand(0);
10489 Value *RHSVal = FirstInst->getOperand(1);
10490
10491 const Type *LHSType = LHSVal->getType();
10492 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010493
10494 // Scan to see if all operands are the same opcode, all have one use, and all
10495 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010496 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010497 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010498 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010499 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010500 // types or GEP's with different index types.
10501 I->getOperand(0)->getType() != LHSType ||
10502 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010503 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010504
10505 // If they are CmpInst instructions, check their predicates
10506 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10507 if (cast<CmpInst>(I)->getPredicate() !=
10508 cast<CmpInst>(FirstInst)->getPredicate())
10509 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010510
10511 // Keep track of which operand needs a phi node.
10512 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10513 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010514 }
10515
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010516 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010517
Chris Lattner7da52b22006-11-01 04:51:18 +000010518 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010519 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010520 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010521 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010522 NewLHS = PHINode::Create(LHSType,
10523 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010524 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10525 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010526 InsertNewInstBefore(NewLHS, PN);
10527 LHSVal = NewLHS;
10528 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010529
10530 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010531 NewRHS = PHINode::Create(RHSType,
10532 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010533 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10534 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010535 InsertNewInstBefore(NewRHS, PN);
10536 RHSVal = NewRHS;
10537 }
10538
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010539 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010540 if (NewLHS || NewRHS) {
10541 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10542 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10543 if (NewLHS) {
10544 Value *NewInLHS = InInst->getOperand(0);
10545 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10546 }
10547 if (NewRHS) {
10548 Value *NewInRHS = InInst->getOperand(1);
10549 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10550 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010551 }
10552 }
10553
Chris Lattner7da52b22006-11-01 04:51:18 +000010554 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010555 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010556 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010557 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10558 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010559}
10560
Chris Lattner05f18922008-12-01 02:34:36 +000010561Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10562 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10563
10564 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10565 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010566 // This is true if all GEP bases are allocas and if all indices into them are
10567 // constants.
10568 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010569
10570 // Scan to see if all operands are the same opcode, all have one use, and all
10571 // kill their operands (i.e. the operands have one use).
10572 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10573 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10574 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10575 GEP->getNumOperands() != FirstInst->getNumOperands())
10576 return 0;
10577
Chris Lattner36d3e322009-02-21 00:46:50 +000010578 // Keep track of whether or not all GEPs are of alloca pointers.
10579 if (AllBasePointersAreAllocas &&
10580 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10581 !GEP->hasAllConstantIndices()))
10582 AllBasePointersAreAllocas = false;
10583
Chris Lattner05f18922008-12-01 02:34:36 +000010584 // Compare the operand lists.
10585 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10586 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10587 continue;
10588
10589 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10590 // if one of the PHIs has a constant for the index. The index may be
10591 // substantially cheaper to compute for the constants, so making it a
10592 // variable index could pessimize the path. This also handles the case
10593 // for struct indices, which must always be constant.
10594 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10595 isa<ConstantInt>(GEP->getOperand(op)))
10596 return 0;
10597
10598 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10599 return 0;
10600 FixedOperands[op] = 0; // Needs a PHI.
10601 }
10602 }
10603
Chris Lattner36d3e322009-02-21 00:46:50 +000010604 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010605 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010606 // offset calculation, but all the predecessors will have to materialize the
10607 // stack address into a register anyway. We'd actually rather *clone* the
10608 // load up into the predecessors so that we have a load of a gep of an alloca,
10609 // which can usually all be folded into the load.
10610 if (AllBasePointersAreAllocas)
10611 return 0;
10612
Chris Lattner05f18922008-12-01 02:34:36 +000010613 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10614 // that is variable.
10615 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10616
10617 bool HasAnyPHIs = false;
10618 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10619 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10620 Value *FirstOp = FirstInst->getOperand(i);
10621 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10622 FirstOp->getName()+".pn");
10623 InsertNewInstBefore(NewPN, PN);
10624
10625 NewPN->reserveOperandSpace(e);
10626 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10627 OperandPhis[i] = NewPN;
10628 FixedOperands[i] = NewPN;
10629 HasAnyPHIs = true;
10630 }
10631
10632
10633 // Add all operands to the new PHIs.
10634 if (HasAnyPHIs) {
10635 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10636 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10637 BasicBlock *InBB = PN.getIncomingBlock(i);
10638
10639 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10640 if (PHINode *OpPhi = OperandPhis[op])
10641 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10642 }
10643 }
10644
10645 Value *Base = FixedOperands[0];
10646 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10647 FixedOperands.end());
10648}
10649
10650
Chris Lattner21550882009-02-23 05:56:17 +000010651/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10652/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010653/// obvious the value of the load is not changed from the point of the load to
10654/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010655///
10656/// Finally, it is safe, but not profitable, to sink a load targetting a
10657/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10658/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010659static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010660 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10661
10662 for (++BBI; BBI != E; ++BBI)
10663 if (BBI->mayWriteToMemory())
10664 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010665
10666 // Check for non-address taken alloca. If not address-taken already, it isn't
10667 // profitable to do this xform.
10668 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10669 bool isAddressTaken = false;
10670 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10671 UI != E; ++UI) {
10672 if (isa<LoadInst>(UI)) continue;
10673 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10674 // If storing TO the alloca, then the address isn't taken.
10675 if (SI->getOperand(1) == AI) continue;
10676 }
10677 isAddressTaken = true;
10678 break;
10679 }
10680
Chris Lattner36d3e322009-02-21 00:46:50 +000010681 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010682 return false;
10683 }
10684
Chris Lattner36d3e322009-02-21 00:46:50 +000010685 // If this load is a load from a GEP with a constant offset from an alloca,
10686 // then we don't want to sink it. In its present form, it will be
10687 // load [constant stack offset]. Sinking it will cause us to have to
10688 // materialize the stack addresses in each predecessor in a register only to
10689 // do a shared load from register in the successor.
10690 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10691 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10692 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10693 return false;
10694
Chris Lattner76c73142006-11-01 07:13:54 +000010695 return true;
10696}
10697
Chris Lattner9fe38862003-06-19 17:00:31 +000010698
Chris Lattnerbac32862004-11-14 19:13:23 +000010699// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10700// operator and they all are only used by the PHI, PHI together their
10701// inputs, and do the operation once, to the result of the PHI.
10702Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10703 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10704
10705 // Scan the instruction, looking for input operations that can be folded away.
10706 // If all input operands to the phi are the same instruction (e.g. a cast from
10707 // the same type or "+42") we can pull the operation through the PHI, reducing
10708 // code size and simplifying code.
10709 Constant *ConstantOp = 0;
10710 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010711 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010712 if (isa<CastInst>(FirstInst)) {
10713 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010714 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010715 // Can fold binop, compare or shift here if the RHS is a constant,
10716 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010717 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010718 if (ConstantOp == 0)
10719 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010720 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10721 isVolatile = LI->isVolatile();
10722 // We can't sink the load if the loaded value could be modified between the
10723 // load and the PHI.
10724 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010725 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010726 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010727
10728 // If the PHI is of volatile loads and the load block has multiple
10729 // successors, sinking it would remove a load of the volatile value from
10730 // the path through the other successor.
10731 if (isVolatile &&
10732 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10733 return 0;
10734
Chris Lattner9c080502006-11-01 07:43:41 +000010735 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010736 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010737 } else {
10738 return 0; // Cannot fold this operation.
10739 }
10740
10741 // Check to see if all arguments are the same operation.
10742 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10743 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10744 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010745 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010746 return 0;
10747 if (CastSrcTy) {
10748 if (I->getOperand(0)->getType() != CastSrcTy)
10749 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010750 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010751 // We can't sink the load if the loaded value could be modified between
10752 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010753 if (LI->isVolatile() != isVolatile ||
10754 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010755 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010756 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010757
Chris Lattner71042962008-07-08 17:18:32 +000010758 // If the PHI is of volatile loads and the load block has multiple
10759 // successors, sinking it would remove a load of the volatile value from
10760 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010761 if (isVolatile &&
10762 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10763 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010764
Chris Lattnerbac32862004-11-14 19:13:23 +000010765 } else if (I->getOperand(1) != ConstantOp) {
10766 return 0;
10767 }
10768 }
10769
10770 // Okay, they are all the same operation. Create a new PHI node of the
10771 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010772 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10773 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010774 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010775
10776 Value *InVal = FirstInst->getOperand(0);
10777 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010778
10779 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010780 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10781 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10782 if (NewInVal != InVal)
10783 InVal = 0;
10784 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10785 }
10786
10787 Value *PhiVal;
10788 if (InVal) {
10789 // The new PHI unions all of the same values together. This is really
10790 // common, so we handle it intelligently here for compile-time speed.
10791 PhiVal = InVal;
10792 delete NewPN;
10793 } else {
10794 InsertNewInstBefore(NewPN, PN);
10795 PhiVal = NewPN;
10796 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010797
Chris Lattnerbac32862004-11-14 19:13:23 +000010798 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010799 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010800 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010801 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010802 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010803 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010804 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010805 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010806 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10807
10808 // If this was a volatile load that we are merging, make sure to loop through
10809 // and mark all the input loads as non-volatile. If we don't do this, we will
10810 // insert a new volatile load and the old ones will not be deletable.
10811 if (isVolatile)
10812 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10813 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10814
10815 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010816}
Chris Lattnera1be5662002-05-02 17:06:02 +000010817
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010818/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10819/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010820static bool DeadPHICycle(PHINode *PN,
10821 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010822 if (PN->use_empty()) return true;
10823 if (!PN->hasOneUse()) return false;
10824
10825 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010826 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010827 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010828
10829 // Don't scan crazily complex things.
10830 if (PotentiallyDeadPHIs.size() == 16)
10831 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010832
10833 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10834 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010835
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010836 return false;
10837}
10838
Chris Lattnercf5008a2007-11-06 21:52:06 +000010839/// PHIsEqualValue - Return true if this phi node is always equal to
10840/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10841/// z = some value; x = phi (y, z); y = phi (x, z)
10842static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10843 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10844 // See if we already saw this PHI node.
10845 if (!ValueEqualPHIs.insert(PN))
10846 return true;
10847
10848 // Don't scan crazily complex things.
10849 if (ValueEqualPHIs.size() == 16)
10850 return false;
10851
10852 // Scan the operands to see if they are either phi nodes or are equal to
10853 // the value.
10854 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10855 Value *Op = PN->getIncomingValue(i);
10856 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10857 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10858 return false;
10859 } else if (Op != NonPhiInVal)
10860 return false;
10861 }
10862
10863 return true;
10864}
10865
10866
Chris Lattner473945d2002-05-06 18:06:38 +000010867// PHINode simplification
10868//
Chris Lattner7e708292002-06-25 16:13:24 +000010869Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010870 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010871 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010872
Owen Anderson7e057142006-07-10 22:03:18 +000010873 if (Value *V = PN.hasConstantValue())
10874 return ReplaceInstUsesWith(PN, V);
10875
Owen Anderson7e057142006-07-10 22:03:18 +000010876 // If all PHI operands are the same operation, pull them through the PHI,
10877 // reducing code size.
10878 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010879 isa<Instruction>(PN.getIncomingValue(1)) &&
10880 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10881 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10882 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10883 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010884 PN.getIncomingValue(0)->hasOneUse())
10885 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10886 return Result;
10887
10888 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10889 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10890 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010891 if (PN.hasOneUse()) {
10892 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10893 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010894 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010895 PotentiallyDeadPHIs.insert(&PN);
10896 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010897 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010898 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010899
10900 // If this phi has a single use, and if that use just computes a value for
10901 // the next iteration of a loop, delete the phi. This occurs with unused
10902 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10903 // common case here is good because the only other things that catch this
10904 // are induction variable analysis (sometimes) and ADCE, which is only run
10905 // late.
10906 if (PHIUser->hasOneUse() &&
10907 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10908 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010909 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010910 }
10911 }
Owen Anderson7e057142006-07-10 22:03:18 +000010912
Chris Lattnercf5008a2007-11-06 21:52:06 +000010913 // We sometimes end up with phi cycles that non-obviously end up being the
10914 // same value, for example:
10915 // z = some value; x = phi (y, z); y = phi (x, z)
10916 // where the phi nodes don't necessarily need to be in the same block. Do a
10917 // quick check to see if the PHI node only contains a single non-phi value, if
10918 // so, scan to see if the phi cycle is actually equal to that value.
10919 {
10920 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10921 // Scan for the first non-phi operand.
10922 while (InValNo != NumOperandVals &&
10923 isa<PHINode>(PN.getIncomingValue(InValNo)))
10924 ++InValNo;
10925
10926 if (InValNo != NumOperandVals) {
10927 Value *NonPhiInVal = PN.getOperand(InValNo);
10928
10929 // Scan the rest of the operands to see if there are any conflicts, if so
10930 // there is no need to recursively scan other phis.
10931 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10932 Value *OpVal = PN.getIncomingValue(InValNo);
10933 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10934 break;
10935 }
10936
10937 // If we scanned over all operands, then we have one unique value plus
10938 // phi values. Scan PHI nodes to see if they all merge in each other or
10939 // the value.
10940 if (InValNo == NumOperandVals) {
10941 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10942 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10943 return ReplaceInstUsesWith(PN, NonPhiInVal);
10944 }
10945 }
10946 }
Chris Lattner60921c92003-12-19 05:58:40 +000010947 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010948}
10949
Reid Spencer17212df2006-12-12 09:18:51 +000010950static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10951 Instruction *InsertPoint,
10952 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010953 unsigned PtrSize = DTy->getScalarSizeInBits();
10954 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010955 // We must cast correctly to the pointer type. Ensure that we
10956 // sign extend the integer value if it is smaller as this is
10957 // used for address computation.
10958 Instruction::CastOps opcode =
10959 (VTySize < PtrSize ? Instruction::SExt :
10960 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10961 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010962}
10963
Chris Lattnera1be5662002-05-02 17:06:02 +000010964
Chris Lattner7e708292002-06-25 16:13:24 +000010965Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010966 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010967 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010968 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010969 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010970 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010971
Chris Lattnere87597f2004-10-16 18:11:37 +000010972 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000010973 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010974
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010975 bool HasZeroPointerIndex = false;
10976 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10977 HasZeroPointerIndex = C->isNullValue();
10978
10979 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010980 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010981
Chris Lattner28977af2004-04-05 01:30:19 +000010982 // Eliminate unneeded casts for indices.
10983 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010984
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010985 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010986 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10987 i != e; ++i, ++GTI) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010988 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010989 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010990 if (CI->getOpcode() == Instruction::ZExt ||
10991 CI->getOpcode() == Instruction::SExt) {
10992 const Type *SrcTy = CI->getOperand(0)->getType();
10993 // We can eliminate a cast from i32 to i64 iff the target
10994 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000010995 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010996 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010997 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010998 }
10999 }
11000 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011001 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011002 // to what we need. If narrower, sign-extend it to what we need.
11003 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011004 // insert it. This explicit cast can make subsequent optimizations more
11005 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011006 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011007 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011008 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011009 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011010 MadeChange = true;
11011 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011012 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11013 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011014 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011015 MadeChange = true;
11016 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011017 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11018 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011019 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011020 MadeChange = true;
11021 } else {
11022 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11023 GEP);
11024 *i = Op;
11025 MadeChange = true;
11026 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011027 }
Chris Lattner28977af2004-04-05 01:30:19 +000011028 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011029 }
Chris Lattner28977af2004-04-05 01:30:19 +000011030 if (MadeChange) return &GEP;
11031
Chris Lattner90ac28c2002-08-02 19:29:35 +000011032 // Combine Indices - If the source pointer to this getelementptr instruction
11033 // is a getelementptr instruction, combine the indices of the two
11034 // getelementptr instructions into a single instruction.
11035 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011036 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011037 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011038 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011039
11040 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011041 // Note that if our source is a gep chain itself that we wait for that
11042 // chain to be resolved before we perform this transformation. This
11043 // avoids us creating a TON of code in some cases.
11044 //
11045 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11046 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11047 return 0; // Wait until our source is folded to completion.
11048
Chris Lattner72588fc2007-02-15 22:48:32 +000011049 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011050
11051 // Find out whether the last index in the source GEP is a sequential idx.
11052 bool EndsWithSequential = false;
11053 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11054 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011055 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011056
Chris Lattner90ac28c2002-08-02 19:29:35 +000011057 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011058 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011059 // Replace: gep (gep %P, long B), long A, ...
11060 // With: T = long A+B; gep %P, T, ...
11061 //
Chris Lattner620ce142004-05-07 22:09:22 +000011062 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011063 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011064 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011065 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011066 Sum = SO1;
11067 } else {
11068 // If they aren't the same type, convert both to an integer of the
11069 // target's pointer size.
11070 if (SO1->getType() != GO1->getType()) {
11071 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011072 SO1 =
11073 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011074 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011075 GO1 =
11076 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011077 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011078 unsigned PS = TD->getPointerSizeInBits();
11079 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011080 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011081 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011082
Duncan Sands514ab342007-11-01 20:53:16 +000011083 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011084 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011085 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011086 } else {
11087 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011088 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11089 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011090 }
11091 }
11092 }
Chris Lattner620ce142004-05-07 22:09:22 +000011093 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011094 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11095 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011096 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011097 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011098 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011099 }
Chris Lattner28977af2004-04-05 01:30:19 +000011100 }
Chris Lattner620ce142004-05-07 22:09:22 +000011101
11102 // Recycle the GEP we already have if possible.
11103 if (SrcGEPOperands.size() == 2) {
11104 GEP.setOperand(0, SrcGEPOperands[0]);
11105 GEP.setOperand(1, Sum);
11106 return &GEP;
11107 } else {
11108 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11109 SrcGEPOperands.end()-1);
11110 Indices.push_back(Sum);
11111 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11112 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011113 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011114 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011115 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011116 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011117 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11118 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011119 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11120 }
11121
11122 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011123 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11124 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011125
Chris Lattner620ce142004-05-07 22:09:22 +000011126 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011127 // GEP of global variable. If all of the indices for this GEP are
11128 // constants, we can promote this to a constexpr instead of an instruction.
11129
11130 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011131 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011132 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11133 for (; I != E && isa<Constant>(*I); ++I)
11134 Indices.push_back(cast<Constant>(*I));
11135
11136 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011137 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011138 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011139
11140 // Replace all uses of the GEP with the new constexpr...
11141 return ReplaceInstUsesWith(GEP, CE);
11142 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011143 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011144 if (!isa<PointerType>(X->getType())) {
11145 // Not interesting. Source pointer must be a cast from pointer.
11146 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011147 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11148 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011149 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011150 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11151 // into : GEP i8* X, ...
11152 //
Chris Lattnereed48272005-09-13 00:40:14 +000011153 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011154 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11155 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011156 if (const ArrayType *CATy =
11157 dyn_cast<ArrayType>(CPTy->getElementType())) {
11158 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11159 if (CATy->getElementType() == XTy->getElementType()) {
11160 // -> GEP i8* X, ...
11161 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11162 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11163 GEP.getName());
11164 } else if (const ArrayType *XATy =
11165 dyn_cast<ArrayType>(XTy->getElementType())) {
11166 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011167 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011168 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011169 // At this point, we know that the cast source type is a pointer
11170 // to an array of the same type as the destination pointer
11171 // array. Because the array type is never stepped over (there
11172 // is a leading zero) we can fold the cast into this GEP.
11173 GEP.setOperand(0, X);
11174 return &GEP;
11175 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011176 }
11177 }
Chris Lattnereed48272005-09-13 00:40:14 +000011178 } else if (GEP.getNumOperands() == 2) {
11179 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011180 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11181 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011182 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11183 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011184 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011185 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11186 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011187 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011188 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011189 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011190 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011191 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011192 // V and GEP are both pointer types --> BitCast
11193 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011194 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011195
11196 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011197 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011198 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011199 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011200
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011201 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011202 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011203 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011204
11205 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11206 // allow either a mul, shift, or constant here.
11207 Value *NewIdx = 0;
11208 ConstantInt *Scale = 0;
11209 if (ArrayEltSize == 1) {
11210 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011211 Scale =
11212 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011213 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011214 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011215 Scale = CI;
11216 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11217 if (Inst->getOpcode() == Instruction::Shl &&
11218 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011219 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11220 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011221 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011222 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011223 NewIdx = Inst->getOperand(0);
11224 } else if (Inst->getOpcode() == Instruction::Mul &&
11225 isa<ConstantInt>(Inst->getOperand(1))) {
11226 Scale = cast<ConstantInt>(Inst->getOperand(1));
11227 NewIdx = Inst->getOperand(0);
11228 }
11229 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011230
Chris Lattner7835cdd2005-09-13 18:36:04 +000011231 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011232 // out, perform the transformation. Note, we don't know whether Scale is
11233 // signed or not. We'll use unsigned version of division/modulo
11234 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011235 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011236 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011237 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011238 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011239 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011240 Constant *C =
11241 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011242 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011243 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011244 NewIdx = InsertNewInstBefore(Sc, GEP);
11245 }
11246
11247 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011248 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011249 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011250 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011251 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011252 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011253 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11254 // The NewGEP must be pointer typed, so must the old one -> BitCast
11255 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011256 }
11257 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011258 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011259 }
Chris Lattner58407792009-01-09 04:53:57 +000011260
Chris Lattner46cd5a12009-01-09 05:44:56 +000011261 /// See if we can simplify:
11262 /// X = bitcast A to B*
11263 /// Y = gep X, <...constant indices...>
11264 /// into a gep of the original struct. This is important for SROA and alias
11265 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011266 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011267 if (TD &&
11268 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011269 // Determine how much the GEP moves the pointer. We are guaranteed to get
11270 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011271 ConstantInt *OffsetV =
11272 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011273 int64_t Offset = OffsetV->getSExtValue();
11274
11275 // If this GEP instruction doesn't move the pointer, just replace the GEP
11276 // with a bitcast of the real input to the dest type.
11277 if (Offset == 0) {
11278 // If the bitcast is of an allocation, and the allocation will be
11279 // converted to match the type of the cast, don't touch this.
11280 if (isa<AllocationInst>(BCI->getOperand(0))) {
11281 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11282 if (Instruction *I = visitBitCast(*BCI)) {
11283 if (I != BCI) {
11284 I->takeName(BCI);
11285 BCI->getParent()->getInstList().insert(BCI, I);
11286 ReplaceInstUsesWith(*BCI, I);
11287 }
11288 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011289 }
Chris Lattner58407792009-01-09 04:53:57 +000011290 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011291 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011292 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011293
11294 // Otherwise, if the offset is non-zero, we need to find out if there is a
11295 // field at Offset in 'A's type. If so, we can pull the cast through the
11296 // GEP.
11297 SmallVector<Value*, 8> NewIndices;
11298 const Type *InTy =
11299 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011300 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011301 Instruction *NGEP =
11302 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11303 NewIndices.end());
11304 if (NGEP->getType() == GEP.getType()) return NGEP;
11305 InsertNewInstBefore(NGEP, GEP);
11306 NGEP->takeName(&GEP);
11307 return new BitCastInst(NGEP, GEP.getType());
11308 }
Chris Lattner58407792009-01-09 04:53:57 +000011309 }
11310 }
11311
Chris Lattner8a2a3112001-12-14 16:52:21 +000011312 return 0;
11313}
11314
Chris Lattner0864acf2002-11-04 16:18:53 +000011315Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11316 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011317 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011318 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11319 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011320 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011321 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011322
11323 // Create and insert the replacement instruction...
11324 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011325 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011326 else {
11327 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011328 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011329 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011330
11331 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011332
Chris Lattner0864acf2002-11-04 16:18:53 +000011333 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011334 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011335 //
11336 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011337 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011338
11339 // Now that I is pointing to the first non-allocation-inst in the block,
11340 // insert our getelementptr instruction...
11341 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011342 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011343 Value *Idx[2];
11344 Idx[0] = NullIdx;
11345 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011346 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11347 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011348
11349 // Now make everything use the getelementptr instead of the original
11350 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011351 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011352 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011353 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011354 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011355 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011356
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011357 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011358 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011359 // Note that we only do this for alloca's, because malloc should allocate
11360 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011361 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011362 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011363
11364 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11365 if (AI.getAlignment() == 0)
11366 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11367 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011368
Chris Lattner0864acf2002-11-04 16:18:53 +000011369 return 0;
11370}
11371
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011372Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11373 Value *Op = FI.getOperand(0);
11374
Chris Lattner17be6352004-10-18 02:59:09 +000011375 // free undef -> unreachable.
11376 if (isa<UndefValue>(Op)) {
11377 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000011378 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000011379 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011380 return EraseInstFromFunction(FI);
11381 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011382
Chris Lattner6160e852004-02-28 04:57:37 +000011383 // If we have 'free null' delete the instruction. This can happen in stl code
11384 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011385 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011386 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011387
11388 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11389 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11390 FI.setOperand(0, CI->getOperand(0));
11391 return &FI;
11392 }
11393
11394 // Change free (gep X, 0,0,0,0) into free(X)
11395 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11396 if (GEPI->hasAllZeroIndices()) {
11397 AddToWorkList(GEPI);
11398 FI.setOperand(0, GEPI->getOperand(0));
11399 return &FI;
11400 }
11401 }
11402
11403 // Change free(malloc) into nothing, if the malloc has a single use.
11404 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11405 if (MI->hasOneUse()) {
11406 EraseInstFromFunction(FI);
11407 return EraseInstFromFunction(*MI);
11408 }
Chris Lattner6160e852004-02-28 04:57:37 +000011409
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011410 return 0;
11411}
11412
11413
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011414/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011415static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011416 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011417 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011418 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011419 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011420
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011421 if (TD) {
11422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11423 // Instead of loading constant c string, use corresponding integer value
11424 // directly if string length is small enough.
11425 std::string Str;
11426 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11427 unsigned len = Str.length();
11428 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11429 unsigned numBits = Ty->getPrimitiveSizeInBits();
11430 // Replace LI with immediate integer store.
11431 if ((numBits >> 3) == len + 1) {
11432 APInt StrVal(numBits, 0);
11433 APInt SingleChar(numBits, 0);
11434 if (TD->isLittleEndian()) {
11435 for (signed i = len-1; i >= 0; i--) {
11436 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11437 StrVal = (StrVal << 8) | SingleChar;
11438 }
11439 } else {
11440 for (unsigned i = 0; i < len; i++) {
11441 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11442 StrVal = (StrVal << 8) | SingleChar;
11443 }
11444 // Append NULL at the end.
11445 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011446 StrVal = (StrVal << 8) | SingleChar;
11447 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011448 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011449 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011450 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011451 }
11452 }
11453 }
11454
Mon P Wang6753f952009-02-07 22:19:29 +000011455 const PointerType *DestTy = cast<PointerType>(CI->getType());
11456 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011457 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011458
11459 // If the address spaces don't match, don't eliminate the cast.
11460 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11461 return 0;
11462
Chris Lattnerb89e0712004-07-13 01:49:43 +000011463 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011464
Reid Spencer42230162007-01-22 05:51:25 +000011465 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011466 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011467 // If the source is an array, the code below will not succeed. Check to
11468 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11469 // constants.
11470 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11471 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11472 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011473 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011474 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11475 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011476 SrcTy = cast<PointerType>(CastOp->getType());
11477 SrcPTy = SrcTy->getElementType();
11478 }
11479
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011480 if (IC.getTargetData() &&
11481 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011482 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011483 // Do not allow turning this into a load of an integer, which is then
11484 // casted to a pointer, this pessimizes pointer analysis a lot.
11485 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011486 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11487 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011488
Chris Lattnerf9527852005-01-31 04:50:46 +000011489 // Okay, we are casting from one integer or pointer type to another of
11490 // the same size. Instead of casting the pointer before the load, cast
11491 // the result of the loaded value.
11492 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11493 CI->getName(),
11494 LI.isVolatile()),LI);
11495 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011496 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011497 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011498 }
11499 }
11500 return 0;
11501}
11502
Chris Lattner833b8a42003-06-26 05:06:25 +000011503Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11504 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011505
Dan Gohman9941f742007-07-20 16:34:21 +000011506 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011507 if (TD) {
11508 unsigned KnownAlign =
11509 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11510 if (KnownAlign >
11511 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11512 LI.getAlignment()))
11513 LI.setAlignment(KnownAlign);
11514 }
Dan Gohman9941f742007-07-20 16:34:21 +000011515
Chris Lattner37366c12005-05-01 04:24:53 +000011516 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011517 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011518 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011519 return Res;
11520
11521 // None of the following transforms are legal for volatile loads.
11522 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011523
Dan Gohman2276a7b2008-10-15 23:19:35 +000011524 // Do really simple store-to-load forwarding and load CSE, to catch cases
11525 // where there are several consequtive memory accesses to the same location,
11526 // separated by a few arithmetic operations.
11527 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011528 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11529 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011530
Christopher Lambb15147e2007-12-29 07:56:53 +000011531 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11532 const Value *GEPI0 = GEPI->getOperand(0);
11533 // TODO: Consider a target hook for valid address spaces for this xform.
11534 if (isa<ConstantPointerNull>(GEPI0) &&
11535 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011536 // Insert a new store to null instruction before the load to indicate
11537 // that this code is not reachable. We do this instead of inserting
11538 // an unreachable instruction directly because we cannot modify the
11539 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011540 new StoreInst(Context->getUndef(LI.getType()),
11541 Context->getNullValue(Op->getType()), &LI);
11542 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011543 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011544 }
Chris Lattner37366c12005-05-01 04:24:53 +000011545
Chris Lattnere87597f2004-10-16 18:11:37 +000011546 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011547 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011548 // TODO: Consider a target hook for valid address spaces for this xform.
11549 if (isa<UndefValue>(C) || (C->isNullValue() &&
11550 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011551 // Insert a new store to null instruction before the load to indicate that
11552 // this code is not reachable. We do this instead of inserting an
11553 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011554 new StoreInst(Context->getUndef(LI.getType()),
11555 Context->getNullValue(Op->getType()), &LI);
11556 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011557 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011558
Chris Lattnere87597f2004-10-16 18:11:37 +000011559 // Instcombine load (constant global) into the value loaded.
11560 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011561 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011562 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011563
Chris Lattnere87597f2004-10-16 18:11:37 +000011564 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011565 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011566 if (CE->getOpcode() == Instruction::GetElementPtr) {
11567 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011568 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011569 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011570 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011571 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011572 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011573 if (CE->getOperand(0)->isNullValue()) {
11574 // Insert a new store to null instruction before the load to indicate
11575 // that this code is not reachable. We do this instead of inserting
11576 // an unreachable instruction directly because we cannot modify the
11577 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011578 new StoreInst(Context->getUndef(LI.getType()),
11579 Context->getNullValue(Op->getType()), &LI);
11580 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011581 }
11582
Reid Spencer3da59db2006-11-27 01:05:10 +000011583 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011584 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011585 return Res;
11586 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011587 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011588 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011589
11590 // If this load comes from anywhere in a constant global, and if the global
11591 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011592 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011593 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011594 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011595 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011596 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011597 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011598 }
11599 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011600
Chris Lattner37366c12005-05-01 04:24:53 +000011601 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011602 // Change select and PHI nodes to select values instead of addresses: this
11603 // helps alias analysis out a lot, allows many others simplifications, and
11604 // exposes redundancy in the code.
11605 //
11606 // Note that we cannot do the transformation unless we know that the
11607 // introduced loads cannot trap! Something like this is valid as long as
11608 // the condition is always false: load (select bool %C, int* null, int* %G),
11609 // but it would not be valid if we transformed it to load from null
11610 // unconditionally.
11611 //
11612 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11613 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011614 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11615 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011616 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011617 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011618 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011619 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011620 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011621 }
11622
Chris Lattner684fe212004-09-23 15:46:00 +000011623 // load (select (cond, null, P)) -> load P
11624 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11625 if (C->isNullValue()) {
11626 LI.setOperand(0, SI->getOperand(2));
11627 return &LI;
11628 }
11629
11630 // load (select (cond, P, null)) -> load P
11631 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11632 if (C->isNullValue()) {
11633 LI.setOperand(0, SI->getOperand(1));
11634 return &LI;
11635 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011636 }
11637 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011638 return 0;
11639}
11640
Reid Spencer55af2b52007-01-19 21:20:31 +000011641/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011642/// when possible. This makes it generally easy to do alias analysis and/or
11643/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011644static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11645 User *CI = cast<User>(SI.getOperand(1));
11646 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011647 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011648
11649 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011650 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11651 if (SrcTy == 0) return 0;
11652
11653 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011654
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011655 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11656 return 0;
11657
Chris Lattner3914f722009-01-24 01:00:13 +000011658 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11659 /// to its first element. This allows us to handle things like:
11660 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11661 /// on 32-bit hosts.
11662 SmallVector<Value*, 4> NewGEPIndices;
11663
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011664 // If the source is an array, the code below will not succeed. Check to
11665 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11666 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011667 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11668 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011669 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011670 NewGEPIndices.push_back(Zero);
11671
11672 while (1) {
11673 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011674 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011675 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011676 NewGEPIndices.push_back(Zero);
11677 SrcPTy = STy->getElementType(0);
11678 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11679 NewGEPIndices.push_back(Zero);
11680 SrcPTy = ATy->getElementType();
11681 } else {
11682 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011683 }
Chris Lattner3914f722009-01-24 01:00:13 +000011684 }
11685
Owen Andersond672ecb2009-07-03 00:17:18 +000011686 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011687 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011688
11689 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11690 return 0;
11691
Chris Lattner71759c42009-01-16 20:12:52 +000011692 // If the pointers point into different address spaces or if they point to
11693 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011694 if (!IC.getTargetData() ||
11695 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011696 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011697 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11698 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011699 return 0;
11700
11701 // Okay, we are casting from one integer or pointer type to another of
11702 // the same size. Instead of casting the pointer before
11703 // the store, cast the value to be stored.
11704 Value *NewCast;
11705 Value *SIOp0 = SI.getOperand(0);
11706 Instruction::CastOps opcode = Instruction::BitCast;
11707 const Type* CastSrcTy = SIOp0->getType();
11708 const Type* CastDstTy = SrcPTy;
11709 if (isa<PointerType>(CastDstTy)) {
11710 if (CastSrcTy->isInteger())
11711 opcode = Instruction::IntToPtr;
11712 } else if (isa<IntegerType>(CastDstTy)) {
11713 if (isa<PointerType>(SIOp0->getType()))
11714 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011715 }
Chris Lattner3914f722009-01-24 01:00:13 +000011716
11717 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11718 // emit a GEP to index into its first field.
11719 if (!NewGEPIndices.empty()) {
11720 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011721 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011722 NewGEPIndices.size());
11723 else
11724 CastOp = IC.InsertNewInstBefore(
11725 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11726 NewGEPIndices.end()), SI);
11727 }
11728
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011729 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011730 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011731 else
11732 NewCast = IC.InsertNewInstBefore(
11733 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11734 SI);
11735 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011736}
11737
Chris Lattner4aebaee2008-11-27 08:56:30 +000011738/// equivalentAddressValues - Test if A and B will obviously have the same
11739/// value. This includes recognizing that %t0 and %t1 will have the same
11740/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011741/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011742/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011743/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011744/// %t2 = load i32* %t1
11745///
11746static bool equivalentAddressValues(Value *A, Value *B) {
11747 // Test if the values are trivially equivalent.
11748 if (A == B) return true;
11749
11750 // Test if the values come form identical arithmetic instructions.
11751 if (isa<BinaryOperator>(A) ||
11752 isa<CastInst>(A) ||
11753 isa<PHINode>(A) ||
11754 isa<GetElementPtrInst>(A))
11755 if (Instruction *BI = dyn_cast<Instruction>(B))
11756 if (cast<Instruction>(A)->isIdenticalTo(BI))
11757 return true;
11758
11759 // Otherwise they may not be equivalent.
11760 return false;
11761}
11762
Dale Johannesen4945c652009-03-03 21:26:39 +000011763// If this instruction has two uses, one of which is a llvm.dbg.declare,
11764// return the llvm.dbg.declare.
11765DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11766 if (!V->hasNUses(2))
11767 return 0;
11768 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11769 UI != E; ++UI) {
11770 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11771 return DI;
11772 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11773 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11774 return DI;
11775 }
11776 }
11777 return 0;
11778}
11779
Chris Lattner2f503e62005-01-31 05:36:43 +000011780Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11781 Value *Val = SI.getOperand(0);
11782 Value *Ptr = SI.getOperand(1);
11783
11784 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011785 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011786 ++NumCombined;
11787 return 0;
11788 }
Chris Lattner836692d2007-01-15 06:51:56 +000011789
11790 // If the RHS is an alloca with a single use, zapify the store, making the
11791 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011792 // If the RHS is an alloca with a two uses, the other one being a
11793 // llvm.dbg.declare, zapify the store and the declare, making the
11794 // alloca dead. We must do this to prevent declare's from affecting
11795 // codegen.
11796 if (!SI.isVolatile()) {
11797 if (Ptr->hasOneUse()) {
11798 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011799 EraseInstFromFunction(SI);
11800 ++NumCombined;
11801 return 0;
11802 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011803 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11804 if (isa<AllocaInst>(GEP->getOperand(0))) {
11805 if (GEP->getOperand(0)->hasOneUse()) {
11806 EraseInstFromFunction(SI);
11807 ++NumCombined;
11808 return 0;
11809 }
11810 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11811 EraseInstFromFunction(*DI);
11812 EraseInstFromFunction(SI);
11813 ++NumCombined;
11814 return 0;
11815 }
11816 }
11817 }
11818 }
11819 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11820 EraseInstFromFunction(*DI);
11821 EraseInstFromFunction(SI);
11822 ++NumCombined;
11823 return 0;
11824 }
Chris Lattner836692d2007-01-15 06:51:56 +000011825 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011826
Dan Gohman9941f742007-07-20 16:34:21 +000011827 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011828 if (TD) {
11829 unsigned KnownAlign =
11830 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11831 if (KnownAlign >
11832 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11833 SI.getAlignment()))
11834 SI.setAlignment(KnownAlign);
11835 }
Dan Gohman9941f742007-07-20 16:34:21 +000011836
Dale Johannesenacb51a32009-03-03 01:43:03 +000011837 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011838 // stores to the same location, separated by a few arithmetic operations. This
11839 // situation often occurs with bitfield accesses.
11840 BasicBlock::iterator BBI = &SI;
11841 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11842 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011843 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011844 // Don't count debug info directives, lest they affect codegen,
11845 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11846 // It is necessary for correctness to skip those that feed into a
11847 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011848 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011849 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011850 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011851 continue;
11852 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011853
11854 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11855 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011856 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11857 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011858 ++NumDeadStore;
11859 ++BBI;
11860 EraseInstFromFunction(*PrevSI);
11861 continue;
11862 }
11863 break;
11864 }
11865
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011866 // If this is a load, we have to stop. However, if the loaded value is from
11867 // the pointer we're loading and is producing the pointer we're storing,
11868 // then *this* store is dead (X = load P; store X -> P).
11869 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011870 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11871 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011872 EraseInstFromFunction(SI);
11873 ++NumCombined;
11874 return 0;
11875 }
11876 // Otherwise, this is a load from some other location. Stores before it
11877 // may not be dead.
11878 break;
11879 }
11880
Chris Lattner9ca96412006-02-08 03:25:32 +000011881 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011882 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011883 break;
11884 }
11885
11886
11887 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011888
11889 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011890 if (isa<ConstantPointerNull>(Ptr) &&
11891 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011892 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011893 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011894 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011895 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011896 ++NumCombined;
11897 }
11898 return 0; // Do not modify these!
11899 }
11900
11901 // store undef, Ptr -> noop
11902 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011903 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011904 ++NumCombined;
11905 return 0;
11906 }
11907
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011908 // If the pointer destination is a cast, see if we can fold the cast into the
11909 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011910 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011911 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11912 return Res;
11913 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011914 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011915 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11916 return Res;
11917
Chris Lattner408902b2005-09-12 23:23:25 +000011918
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011919 // If this store is the last instruction in the basic block (possibly
11920 // excepting debug info instructions and the pointer bitcasts that feed
11921 // into them), and if the block ends with an unconditional branch, try
11922 // to move it to the successor block.
11923 BBI = &SI;
11924 do {
11925 ++BBI;
11926 } while (isa<DbgInfoIntrinsic>(BBI) ||
11927 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011928 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011929 if (BI->isUnconditional())
11930 if (SimplifyStoreAtEndOfBlock(SI))
11931 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011932
Chris Lattner2f503e62005-01-31 05:36:43 +000011933 return 0;
11934}
11935
Chris Lattner3284d1f2007-04-15 00:07:55 +000011936/// SimplifyStoreAtEndOfBlock - Turn things like:
11937/// if () { *P = v1; } else { *P = v2 }
11938/// into a phi node with a store in the successor.
11939///
Chris Lattner31755a02007-04-15 01:02:18 +000011940/// Simplify things like:
11941/// *P = v1; if () { *P = v2; }
11942/// into a phi node with a store in the successor.
11943///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011944bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11945 BasicBlock *StoreBB = SI.getParent();
11946
11947 // Check to see if the successor block has exactly two incoming edges. If
11948 // so, see if the other predecessor contains a store to the same location.
11949 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011950 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011951
11952 // Determine whether Dest has exactly two predecessors and, if so, compute
11953 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011954 pred_iterator PI = pred_begin(DestBB);
11955 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011956 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011957 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011958 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011959 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011960 return false;
11961
11962 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011963 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011964 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011965 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011966 }
Chris Lattner31755a02007-04-15 01:02:18 +000011967 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011968 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011969
11970 // Bail out if all the relevant blocks aren't distinct (this can happen,
11971 // for example, if SI is in an infinite loop)
11972 if (StoreBB == DestBB || OtherBB == DestBB)
11973 return false;
11974
Chris Lattner31755a02007-04-15 01:02:18 +000011975 // Verify that the other block ends in a branch and is not otherwise empty.
11976 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011977 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011978 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011979 return false;
11980
Chris Lattner31755a02007-04-15 01:02:18 +000011981 // If the other block ends in an unconditional branch, check for the 'if then
11982 // else' case. there is an instruction before the branch.
11983 StoreInst *OtherStore = 0;
11984 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011985 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011986 // Skip over debugging info.
11987 while (isa<DbgInfoIntrinsic>(BBI) ||
11988 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11989 if (BBI==OtherBB->begin())
11990 return false;
11991 --BBI;
11992 }
11993 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011994 OtherStore = dyn_cast<StoreInst>(BBI);
11995 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11996 return false;
11997 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011998 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011999 // destinations is StoreBB, then we have the if/then case.
12000 if (OtherBr->getSuccessor(0) != StoreBB &&
12001 OtherBr->getSuccessor(1) != StoreBB)
12002 return false;
12003
12004 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012005 // if/then triangle. See if there is a store to the same ptr as SI that
12006 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012007 for (;; --BBI) {
12008 // Check to see if we find the matching store.
12009 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12010 if (OtherStore->getOperand(1) != SI.getOperand(1))
12011 return false;
12012 break;
12013 }
Eli Friedman6903a242008-06-13 22:02:12 +000012014 // If we find something that may be using or overwriting the stored
12015 // value, or if we run out of instructions, we can't do the xform.
12016 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012017 BBI == OtherBB->begin())
12018 return false;
12019 }
12020
12021 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012022 // make sure nothing reads or overwrites the stored value in
12023 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012024 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12025 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012026 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012027 return false;
12028 }
12029 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012030
Chris Lattner31755a02007-04-15 01:02:18 +000012031 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012032 Value *MergedVal = OtherStore->getOperand(0);
12033 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012034 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012035 PN->reserveOperandSpace(2);
12036 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012037 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12038 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012039 }
12040
12041 // Advance to a place where it is safe to insert the new store and
12042 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012043 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012044 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12045 OtherStore->isVolatile()), *BBI);
12046
12047 // Nuke the old stores.
12048 EraseInstFromFunction(SI);
12049 EraseInstFromFunction(*OtherStore);
12050 ++NumCombined;
12051 return true;
12052}
12053
Chris Lattner2f503e62005-01-31 05:36:43 +000012054
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012055Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12056 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012057 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012058 BasicBlock *TrueDest;
12059 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012060 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012061 !isa<Constant>(X)) {
12062 // Swap Destinations and condition...
12063 BI.setCondition(X);
12064 BI.setSuccessor(0, FalseDest);
12065 BI.setSuccessor(1, TrueDest);
12066 return &BI;
12067 }
12068
Reid Spencere4d87aa2006-12-23 06:05:41 +000012069 // Cannonicalize fcmp_one -> fcmp_oeq
12070 FCmpInst::Predicate FPred; Value *Y;
12071 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012072 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012073 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12074 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12075 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012076 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012077 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012078 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012079 // Swap Destinations and condition...
12080 BI.setCondition(NewSCC);
12081 BI.setSuccessor(0, FalseDest);
12082 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012083 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012084 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012085 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012086 return &BI;
12087 }
12088
12089 // Cannonicalize icmp_ne -> icmp_eq
12090 ICmpInst::Predicate IPred;
12091 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012092 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012093 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12094 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12095 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12096 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012097 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012098 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012099 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012100 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012101 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012102 BI.setSuccessor(0, FalseDest);
12103 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012104 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012105 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012106 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012107 return &BI;
12108 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012109
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012110 return 0;
12111}
Chris Lattner0864acf2002-11-04 16:18:53 +000012112
Chris Lattner46238a62004-07-03 00:26:11 +000012113Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12114 Value *Cond = SI.getCondition();
12115 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12116 if (I->getOpcode() == Instruction::Add)
12117 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12118 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12119 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012120 SI.setOperand(i,
12121 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012122 AddRHS));
12123 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012124 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012125 return &SI;
12126 }
12127 }
12128 return 0;
12129}
12130
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012131Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012132 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012133
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012134 if (!EV.hasIndices())
12135 return ReplaceInstUsesWith(EV, Agg);
12136
12137 if (Constant *C = dyn_cast<Constant>(Agg)) {
12138 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012139 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012140
12141 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012142 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012143
12144 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12145 // Extract the element indexed by the first index out of the constant
12146 Value *V = C->getOperand(*EV.idx_begin());
12147 if (EV.getNumIndices() > 1)
12148 // Extract the remaining indices out of the constant indexed by the
12149 // first index
12150 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12151 else
12152 return ReplaceInstUsesWith(EV, V);
12153 }
12154 return 0; // Can't handle other constants
12155 }
12156 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12157 // We're extracting from an insertvalue instruction, compare the indices
12158 const unsigned *exti, *exte, *insi, *inse;
12159 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12160 exte = EV.idx_end(), inse = IV->idx_end();
12161 exti != exte && insi != inse;
12162 ++exti, ++insi) {
12163 if (*insi != *exti)
12164 // The insert and extract both reference distinctly different elements.
12165 // This means the extract is not influenced by the insert, and we can
12166 // replace the aggregate operand of the extract with the aggregate
12167 // operand of the insert. i.e., replace
12168 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12169 // %E = extractvalue { i32, { i32 } } %I, 0
12170 // with
12171 // %E = extractvalue { i32, { i32 } } %A, 0
12172 return ExtractValueInst::Create(IV->getAggregateOperand(),
12173 EV.idx_begin(), EV.idx_end());
12174 }
12175 if (exti == exte && insi == inse)
12176 // Both iterators are at the end: Index lists are identical. Replace
12177 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12178 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12179 // with "i32 42"
12180 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12181 if (exti == exte) {
12182 // The extract list is a prefix of the insert list. i.e. replace
12183 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12184 // %E = extractvalue { i32, { i32 } } %I, 1
12185 // with
12186 // %X = extractvalue { i32, { i32 } } %A, 1
12187 // %E = insertvalue { i32 } %X, i32 42, 0
12188 // by switching the order of the insert and extract (though the
12189 // insertvalue should be left in, since it may have other uses).
12190 Value *NewEV = InsertNewInstBefore(
12191 ExtractValueInst::Create(IV->getAggregateOperand(),
12192 EV.idx_begin(), EV.idx_end()),
12193 EV);
12194 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12195 insi, inse);
12196 }
12197 if (insi == inse)
12198 // The insert list is a prefix of the extract list
12199 // We can simply remove the common indices from the extract and make it
12200 // operate on the inserted value instead of the insertvalue result.
12201 // i.e., replace
12202 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12203 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12204 // with
12205 // %E extractvalue { i32 } { i32 42 }, 0
12206 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12207 exti, exte);
12208 }
12209 // Can't simplify extracts from other values. Note that nested extracts are
12210 // already simplified implicitely by the above (extract ( extract (insert) )
12211 // will be translated into extract ( insert ( extract ) ) first and then just
12212 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012213 return 0;
12214}
12215
Chris Lattner220b0cf2006-03-05 00:22:33 +000012216/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12217/// is to leave as a vector operation.
12218static bool CheapToScalarize(Value *V, bool isConstant) {
12219 if (isa<ConstantAggregateZero>(V))
12220 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012221 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012222 if (isConstant) return true;
12223 // If all elts are the same, we can extract.
12224 Constant *Op0 = C->getOperand(0);
12225 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12226 if (C->getOperand(i) != Op0)
12227 return false;
12228 return true;
12229 }
12230 Instruction *I = dyn_cast<Instruction>(V);
12231 if (!I) return false;
12232
12233 // Insert element gets simplified to the inserted element or is deleted if
12234 // this is constant idx extract element and its a constant idx insertelt.
12235 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12236 isa<ConstantInt>(I->getOperand(2)))
12237 return true;
12238 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12239 return true;
12240 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12241 if (BO->hasOneUse() &&
12242 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12243 CheapToScalarize(BO->getOperand(1), isConstant)))
12244 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012245 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12246 if (CI->hasOneUse() &&
12247 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12248 CheapToScalarize(CI->getOperand(1), isConstant)))
12249 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012250
12251 return false;
12252}
12253
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012254/// Read and decode a shufflevector mask.
12255///
12256/// It turns undef elements into values that are larger than the number of
12257/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012258static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12259 unsigned NElts = SVI->getType()->getNumElements();
12260 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12261 return std::vector<unsigned>(NElts, 0);
12262 if (isa<UndefValue>(SVI->getOperand(2)))
12263 return std::vector<unsigned>(NElts, 2*NElts);
12264
12265 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012266 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012267 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12268 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012269 Result.push_back(NElts*2); // undef -> 8
12270 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012271 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012272 return Result;
12273}
12274
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012275/// FindScalarElement - Given a vector and an element number, see if the scalar
12276/// value is already around as a register, for example if it were inserted then
12277/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012278static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012279 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012280 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12281 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012282 unsigned Width = PTy->getNumElements();
12283 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012284 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012285
12286 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012287 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012288 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012289 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012290 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012291 return CP->getOperand(EltNo);
12292 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12293 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012294 if (!isa<ConstantInt>(III->getOperand(2)))
12295 return 0;
12296 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012297
12298 // If this is an insert to the element we are looking for, return the
12299 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012300 if (EltNo == IIElt)
12301 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012302
12303 // Otherwise, the insertelement doesn't modify the value, recurse on its
12304 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012305 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012306 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012307 unsigned LHSWidth =
12308 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012309 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012310 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012311 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012312 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012313 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012314 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012315 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012316 }
12317
12318 // Otherwise, we don't know.
12319 return 0;
12320}
12321
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012322Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012323 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012324 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012325 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012326
Dan Gohman07a96762007-07-16 14:29:03 +000012327 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012328 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012329 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012330
Reid Spencer9d6565a2007-02-15 02:26:10 +000012331 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012332 // If vector val is constant with all elements the same, replace EI with
12333 // that element. When the elements are not identical, we cannot replace yet
12334 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012335 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012336 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012337 if (C->getOperand(i) != op0) {
12338 op0 = 0;
12339 break;
12340 }
12341 if (op0)
12342 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012343 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012344
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012345 // If extracting a specified index from the vector, see if we can recursively
12346 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012347 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012348 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012349 unsigned VectorWidth =
12350 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012351
12352 // If this is extracting an invalid index, turn this into undef, to avoid
12353 // crashing the code below.
12354 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012355 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012356
Chris Lattner867b99f2006-10-05 06:55:50 +000012357 // This instruction only demands the single element from the input vector.
12358 // If the input vector has a single use, simplify it based on this use
12359 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012360 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012361 APInt UndefElts(VectorWidth, 0);
12362 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012363 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012364 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012365 EI.setOperand(0, V);
12366 return &EI;
12367 }
12368 }
12369
Owen Andersond672ecb2009-07-03 00:17:18 +000012370 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012371 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012372
12373 // If the this extractelement is directly using a bitcast from a vector of
12374 // the same number of elements, see if we can find the source element from
12375 // it. In this case, we will end up needing to bitcast the scalars.
12376 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12377 if (const VectorType *VT =
12378 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12379 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012380 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12381 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012382 return new BitCastInst(Elt, EI.getType());
12383 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012384 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012385
Chris Lattner73fa49d2006-05-25 22:53:38 +000012386 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012387 if (I->hasOneUse()) {
12388 // Push extractelement into predecessor operation if legal and
12389 // profitable to do so
12390 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012391 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12392 if (CheapToScalarize(BO, isConstantElt)) {
12393 ExtractElementInst *newEI0 =
12394 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12395 EI.getName()+".lhs");
12396 ExtractElementInst *newEI1 =
12397 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12398 EI.getName()+".rhs");
12399 InsertNewInstBefore(newEI0, EI);
12400 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012401 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012402 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012403 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012404 unsigned AS =
12405 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012406 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012407 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012408 GetElementPtrInst *GEP =
12409 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012410 InsertNewInstBefore(GEP, EI);
12411 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012412 }
12413 }
12414 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12415 // Extracting the inserted element?
12416 if (IE->getOperand(2) == EI.getOperand(1))
12417 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12418 // If the inserted and extracted elements are constants, they must not
12419 // be the same value, extract from the pre-inserted value instead.
12420 if (isa<Constant>(IE->getOperand(2)) &&
12421 isa<Constant>(EI.getOperand(1))) {
12422 AddUsesToWorkList(EI);
12423 EI.setOperand(0, IE->getOperand(0));
12424 return &EI;
12425 }
12426 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12427 // If this is extracting an element from a shufflevector, figure out where
12428 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012429 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12430 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012431 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012432 unsigned LHSWidth =
12433 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12434
12435 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012436 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012437 else if (SrcIdx < LHSWidth*2) {
12438 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012439 Src = SVI->getOperand(1);
12440 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012441 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012442 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000012443 return new ExtractElementInst(Src,
12444 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012445 }
12446 }
Eli Friedman2451a642009-07-18 23:06:53 +000012447 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012448 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012449 return 0;
12450}
12451
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012452/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12453/// elements from either LHS or RHS, return the shuffle mask and true.
12454/// Otherwise, return false.
12455static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012456 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012457 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012458 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12459 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012460 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012461
12462 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012463 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012464 return true;
12465 } else if (V == LHS) {
12466 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012467 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012468 return true;
12469 } else if (V == RHS) {
12470 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012471 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012472 return true;
12473 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12474 // If this is an insert of an extract from some other vector, include it.
12475 Value *VecOp = IEI->getOperand(0);
12476 Value *ScalarOp = IEI->getOperand(1);
12477 Value *IdxOp = IEI->getOperand(2);
12478
Chris Lattnerd929f062006-04-27 21:14:21 +000012479 if (!isa<ConstantInt>(IdxOp))
12480 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012481 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012482
12483 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12484 // Okay, we can handle this if the vector we are insertinting into is
12485 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012486 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012487 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012488 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012489 return true;
12490 }
12491 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12492 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012493 EI->getOperand(0)->getType() == V->getType()) {
12494 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012495 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012496
12497 // This must be extracting from either LHS or RHS.
12498 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12499 // Okay, we can handle this if the vector we are insertinting into is
12500 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012501 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012502 // If so, update the mask to reflect the inserted value.
12503 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012504 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012505 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012506 } else {
12507 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012508 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012509 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012510
12511 }
12512 return true;
12513 }
12514 }
12515 }
12516 }
12517 }
12518 // TODO: Handle shufflevector here!
12519
12520 return false;
12521}
12522
12523/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12524/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12525/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012526static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012527 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012528 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012529 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012530 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012531 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012532
12533 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012534 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012535 return V;
12536 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012537 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012538 return V;
12539 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12540 // If this is an insert of an extract from some other vector, include it.
12541 Value *VecOp = IEI->getOperand(0);
12542 Value *ScalarOp = IEI->getOperand(1);
12543 Value *IdxOp = IEI->getOperand(2);
12544
12545 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12546 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12547 EI->getOperand(0)->getType() == V->getType()) {
12548 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012549 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12550 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012551
12552 // Either the extracted from or inserted into vector must be RHSVec,
12553 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012554 if (EI->getOperand(0) == RHS || RHS == 0) {
12555 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012556 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012557 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012558 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012559 return V;
12560 }
12561
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012562 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012563 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12564 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012565 // Everything but the extracted element is replaced with the RHS.
12566 for (unsigned i = 0; i != NumElts; ++i) {
12567 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012568 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012569 }
12570 return V;
12571 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012572
12573 // If this insertelement is a chain that comes from exactly these two
12574 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012575 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12576 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012577 return EI->getOperand(0);
12578
Chris Lattnerefb47352006-04-15 01:39:45 +000012579 }
12580 }
12581 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012582 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012583
12584 // Otherwise, can't do anything fancy. Return an identity vector.
12585 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012586 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012587 return V;
12588}
12589
12590Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12591 Value *VecOp = IE.getOperand(0);
12592 Value *ScalarOp = IE.getOperand(1);
12593 Value *IdxOp = IE.getOperand(2);
12594
Chris Lattner599ded12007-04-09 01:11:16 +000012595 // Inserting an undef or into an undefined place, remove this.
12596 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12597 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012598
Chris Lattnerefb47352006-04-15 01:39:45 +000012599 // If the inserted element was extracted from some other vector, and if the
12600 // indexes are constant, try to turn this into a shufflevector operation.
12601 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12602 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12603 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012604 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012605 unsigned ExtractedIdx =
12606 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012607 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012608
12609 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12610 return ReplaceInstUsesWith(IE, VecOp);
12611
12612 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012613 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012614
12615 // If we are extracting a value from a vector, then inserting it right
12616 // back into the same place, just use the input vector.
12617 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12618 return ReplaceInstUsesWith(IE, VecOp);
12619
12620 // We could theoretically do this for ANY input. However, doing so could
12621 // turn chains of insertelement instructions into a chain of shufflevector
12622 // instructions, and right now we do not merge shufflevectors. As such,
12623 // only do this in a situation where it is clear that there is benefit.
12624 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12625 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12626 // the values of VecOp, except then one read from EIOp0.
12627 // Build a new shuffle mask.
12628 std::vector<Constant*> Mask;
12629 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012630 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012631 else {
12632 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012633 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012634 NumVectorElts));
12635 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012636 Mask[InsertedIdx] =
12637 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012638 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012639 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012640 }
12641
12642 // If this insertelement isn't used by some other insertelement, turn it
12643 // (and any insertelements it points to), into one big shuffle.
12644 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12645 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012646 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012647 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12648 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012649 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012650 return new ShuffleVectorInst(LHS, RHS,
12651 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012652 }
12653 }
12654 }
12655
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012656 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12657 APInt UndefElts(VWidth, 0);
12658 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12659 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12660 return &IE;
12661
Chris Lattnerefb47352006-04-15 01:39:45 +000012662 return 0;
12663}
12664
12665
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012666Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12667 Value *LHS = SVI.getOperand(0);
12668 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012669 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012670
12671 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012672
Chris Lattner867b99f2006-10-05 06:55:50 +000012673 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012674 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012675 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012676
Dan Gohman488fbfc2008-09-09 18:11:14 +000012677 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012678
12679 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12680 return 0;
12681
Evan Cheng388df622009-02-03 10:05:09 +000012682 APInt UndefElts(VWidth, 0);
12683 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12684 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012685 LHS = SVI.getOperand(0);
12686 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012687 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012688 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012689
Chris Lattner863bcff2006-05-25 23:48:38 +000012690 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12691 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12692 if (LHS == RHS || isa<UndefValue>(LHS)) {
12693 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012694 // shuffle(undef,undef,mask) -> undef.
12695 return ReplaceInstUsesWith(SVI, LHS);
12696 }
12697
Chris Lattner863bcff2006-05-25 23:48:38 +000012698 // Remap any references to RHS to use LHS.
12699 std::vector<Constant*> Elts;
12700 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012701 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012702 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012703 else {
12704 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012705 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012706 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012707 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012708 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012709 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012710 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012711 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012712 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012713 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012714 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012715 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12716 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012717 LHS = SVI.getOperand(0);
12718 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012719 MadeChange = true;
12720 }
12721
Chris Lattner7b2e27922006-05-26 00:29:06 +000012722 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012723 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012724
Chris Lattner863bcff2006-05-25 23:48:38 +000012725 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12726 if (Mask[i] >= e*2) continue; // Ignore undef values.
12727 // Is this an identity shuffle of the LHS value?
12728 isLHSID &= (Mask[i] == i);
12729
12730 // Is this an identity shuffle of the RHS value?
12731 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012732 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012733
Chris Lattner863bcff2006-05-25 23:48:38 +000012734 // Eliminate identity shuffles.
12735 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12736 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012737
Chris Lattner7b2e27922006-05-26 00:29:06 +000012738 // If the LHS is a shufflevector itself, see if we can combine it with this
12739 // one without producing an unusual shuffle. Here we are really conservative:
12740 // we are absolutely afraid of producing a shuffle mask not in the input
12741 // program, because the code gen may not be smart enough to turn a merged
12742 // shuffle into two specific shuffles: it may produce worse code. As such,
12743 // we only merge two shuffles if the result is one of the two input shuffle
12744 // masks. In this case, merging the shuffles just removes one instruction,
12745 // which we know is safe. This is good for things like turning:
12746 // (splat(splat)) -> splat.
12747 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12748 if (isa<UndefValue>(RHS)) {
12749 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12750
12751 std::vector<unsigned> NewMask;
12752 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12753 if (Mask[i] >= 2*e)
12754 NewMask.push_back(2*e);
12755 else
12756 NewMask.push_back(LHSMask[Mask[i]]);
12757
12758 // If the result mask is equal to the src shuffle or this shuffle mask, do
12759 // the replacement.
12760 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012761 unsigned LHSInNElts =
12762 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012763 std::vector<Constant*> Elts;
12764 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012765 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012766 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012767 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012768 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012769 }
12770 }
12771 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12772 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012773 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012774 }
12775 }
12776 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012777
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012778 return MadeChange ? &SVI : 0;
12779}
12780
12781
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012782
Chris Lattnerea1c4542004-12-08 23:43:58 +000012783
12784/// TryToSinkInstruction - Try to move the specified instruction from its
12785/// current block into the beginning of DestBlock, which can only happen if it's
12786/// safe to move the instruction past all of the instructions between it and the
12787/// end of its block.
12788static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12789 assert(I->hasOneUse() && "Invariants didn't hold!");
12790
Chris Lattner108e9022005-10-27 17:13:11 +000012791 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012792 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012793 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012794
Chris Lattnerea1c4542004-12-08 23:43:58 +000012795 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012796 if (isa<AllocaInst>(I) && I->getParent() ==
12797 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012798 return false;
12799
Chris Lattner96a52a62004-12-09 07:14:34 +000012800 // We can only sink load instructions if there is nothing between the load and
12801 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012802 if (I->mayReadFromMemory()) {
12803 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012804 Scan != E; ++Scan)
12805 if (Scan->mayWriteToMemory())
12806 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012807 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012808
Dan Gohman02dea8b2008-05-23 21:05:58 +000012809 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012810
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012811 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012812 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012813 ++NumSunkInst;
12814 return true;
12815}
12816
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012817
12818/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12819/// all reachable code to the worklist.
12820///
12821/// This has a couple of tricks to make the code faster and more powerful. In
12822/// particular, we constant fold and DCE instructions as we go, to avoid adding
12823/// them to the worklist (this significantly speeds up instcombine on code where
12824/// many instructions are dead or constant). Additionally, if we find a branch
12825/// whose condition is a known constant, we only visit the reachable successors.
12826///
12827static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012828 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012829 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012830 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012831 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012832 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012833
Chris Lattner2c7718a2007-03-23 19:17:18 +000012834 while (!Worklist.empty()) {
12835 BB = Worklist.back();
12836 Worklist.pop_back();
12837
12838 // We have now visited this block! If we've already been here, ignore it.
12839 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012840
12841 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012842 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12843 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012844
Chris Lattner2c7718a2007-03-23 19:17:18 +000012845 // DCE instruction if trivially dead.
12846 if (isInstructionTriviallyDead(Inst)) {
12847 ++NumDeadInst;
12848 DOUT << "IC: DCE: " << *Inst;
12849 Inst->eraseFromParent();
12850 continue;
12851 }
12852
12853 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012854 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012855 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12856 Inst->replaceAllUsesWith(C);
12857 ++NumConstProp;
12858 Inst->eraseFromParent();
12859 continue;
12860 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012861
Devang Patel7fe1dec2008-11-19 18:56:50 +000012862 // If there are two consecutive llvm.dbg.stoppoint calls then
12863 // it is likely that the optimizer deleted code in between these
12864 // two intrinsics.
12865 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12866 if (DBI_Next) {
12867 if (DBI_Prev
12868 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12869 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12870 IC.RemoveFromWorkList(DBI_Prev);
12871 DBI_Prev->eraseFromParent();
12872 }
12873 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012874 } else {
12875 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012876 }
12877
Chris Lattner2c7718a2007-03-23 19:17:18 +000012878 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012879 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012880
12881 // Recursively visit successors. If this is a branch or switch on a
12882 // constant, only visit the reachable successor.
12883 TerminatorInst *TI = BB->getTerminator();
12884 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12885 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12886 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012887 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012888 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012889 continue;
12890 }
12891 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12892 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12893 // See if this is an explicit destination.
12894 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12895 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012896 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012897 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012898 continue;
12899 }
12900
12901 // Otherwise it is the default destination.
12902 Worklist.push_back(SI->getSuccessor(0));
12903 continue;
12904 }
12905 }
12906
12907 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12908 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012909 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012910}
12911
Chris Lattnerec9c3582007-03-03 02:04:50 +000012912bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012913 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012914 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012915
12916 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12917 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012918
Chris Lattnerb3d59702005-07-07 20:40:38 +000012919 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012920 // Do a depth-first traversal of the function, populate the worklist with
12921 // the reachable instructions. Ignore blocks that are not reachable. Keep
12922 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012923 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012924 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012925
Chris Lattnerb3d59702005-07-07 20:40:38 +000012926 // Do a quick scan over the function. If we find any blocks that are
12927 // unreachable, remove any instructions inside of them. This prevents
12928 // the instcombine code from having to deal with some bad special cases.
12929 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12930 if (!Visited.count(BB)) {
12931 Instruction *Term = BB->getTerminator();
12932 while (Term != BB->begin()) { // Remove instrs bottom-up
12933 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012934
Bill Wendlingb7427032006-11-26 09:46:52 +000012935 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012936 // A debug intrinsic shouldn't force another iteration if we weren't
12937 // going to do one without it.
12938 if (!isa<DbgInfoIntrinsic>(I)) {
12939 ++NumDeadInst;
12940 Changed = true;
12941 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012942 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012943 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012944 I->eraseFromParent();
12945 }
12946 }
12947 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012948
Chris Lattnerdbab3862007-03-02 21:28:56 +000012949 while (!Worklist.empty()) {
12950 Instruction *I = RemoveOneFromWorkList();
12951 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012952
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012953 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012954 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012955 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012956 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012957 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012958 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012959
Bill Wendlingb7427032006-11-26 09:46:52 +000012960 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012961
12962 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012963 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012964 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012965 continue;
12966 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012967
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012968 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012969 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012970 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012971
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012972 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012973 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012974 ReplaceInstUsesWith(*I, C);
12975
Chris Lattner62b14df2002-09-02 04:59:56 +000012976 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012977 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012978 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012979 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012980 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012981 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012982
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012983 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012984 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012985 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12986 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012987 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12988 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012989 if (NewC != CE) {
12990 i->set(NewC);
12991 Changed = true;
12992 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012993 }
12994
Chris Lattnerea1c4542004-12-08 23:43:58 +000012995 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012996 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012997 BasicBlock *BB = I->getParent();
12998 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12999 if (UserParent != BB) {
13000 bool UserIsSuccessor = false;
13001 // See if the user is one of our successors.
13002 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13003 if (*SI == UserParent) {
13004 UserIsSuccessor = true;
13005 break;
13006 }
13007
13008 // If the user is one of our immediate successors, and if that successor
13009 // only has us as a predecessors (we'd have to split the critical edge
13010 // otherwise), we can keep going.
13011 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13012 next(pred_begin(UserParent)) == pred_end(UserParent))
13013 // Okay, the CFG is simple enough, try to sink this instruction.
13014 Changed |= TryToSinkInstruction(I, UserParent);
13015 }
13016 }
13017
Chris Lattner8a2a3112001-12-14 16:52:21 +000013018 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013019#ifndef NDEBUG
13020 std::string OrigI;
13021#endif
13022 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013023 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013024 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013025 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013026 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013027 DOUT << "IC: Old = " << *I
13028 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013029
Chris Lattnerf523d062004-06-09 05:08:07 +000013030 // Everything uses the new instruction now.
13031 I->replaceAllUsesWith(Result);
13032
13033 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013034 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013035 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013036
Chris Lattner6934a042007-02-11 01:23:03 +000013037 // Move the name to the new instruction first.
13038 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013039
13040 // Insert the new instruction into the basic block...
13041 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013042 BasicBlock::iterator InsertPos = I;
13043
13044 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13045 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13046 ++InsertPos;
13047
13048 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013049
Chris Lattner00d51312004-05-01 23:27:23 +000013050 // Make sure that we reprocess all operands now that we reduced their
13051 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013052 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013053
Chris Lattnerf523d062004-06-09 05:08:07 +000013054 // Instructions can end up on the worklist more than once. Make sure
13055 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013056 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013057
13058 // Erase the old instruction.
13059 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013060 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013061#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013062 DOUT << "IC: Mod = " << OrigI
13063 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013064#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013065
Chris Lattner90ac28c2002-08-02 19:29:35 +000013066 // If the instruction was modified, it's possible that it is now dead.
13067 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013068 if (isInstructionTriviallyDead(I)) {
13069 // Make sure we process all operands now that we are reducing their
13070 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013071 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013072
Chris Lattner00d51312004-05-01 23:27:23 +000013073 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013074 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013075 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013076 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013077 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013078 AddToWorkList(I);
13079 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013080 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013081 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013082 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013083 }
13084 }
13085
Chris Lattnerec9c3582007-03-03 02:04:50 +000013086 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013087
13088 // Do an explicit clear, this shrinks the map if needed.
13089 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013090 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013091}
13092
Chris Lattnerec9c3582007-03-03 02:04:50 +000013093
13094bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013095 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013096 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000013097
Chris Lattnerec9c3582007-03-03 02:04:50 +000013098 bool EverMadeChange = false;
13099
13100 // Iterate while there is work to do.
13101 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013102 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013103 EverMadeChange = true;
13104 return EverMadeChange;
13105}
13106
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013107FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013108 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013109}