blob: f52bb8626e5f26bf26fb1e22f71589bd704985e0 [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 Anderson07cf79e2009-07-06 23:00:19 +000088 LLVMContext *getContext() { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +000089
Chris Lattnerdbab3862007-03-02 21:28:56 +000090 /// AddToWorkList - Add the specified instruction to the worklist if it
91 /// isn't already in it.
92 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000093 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000094 Worklist.push_back(I);
95 }
96
97 // RemoveFromWorkList - remove I from the worklist if it exists.
98 void RemoveFromWorkList(Instruction *I) {
99 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
100 if (It == WorklistMap.end()) return; // Not in worklist.
101
102 // Don't bother moving everything down, just null out the slot.
103 Worklist[It->second] = 0;
104
105 WorklistMap.erase(It);
106 }
107
108 Instruction *RemoveOneFromWorkList() {
109 Instruction *I = Worklist.back();
110 Worklist.pop_back();
111 WorklistMap.erase(I);
112 return I;
113 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000114
Chris Lattnerdbab3862007-03-02 21:28:56 +0000115
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000116 /// AddUsersToWorkList - When an instruction is simplified, add all users of
117 /// the instruction to the work lists because they might get more simplified
118 /// now.
119 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000120 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000121 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000122 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000123 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 }
125
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000126 /// AddUsesToWorkList - When an instruction is simplified, add operands to
127 /// the work lists because they might get more simplified now.
128 ///
129 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000130 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
131 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000132 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000133 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000134
135 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
136 /// dead. Add all of its operands to the worklist, turning them into
137 /// undef's to reduce the number of uses of those instructions.
138 ///
139 /// Return the specified operand before it is turned into an undef.
140 ///
141 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
142 Value *R = I.getOperand(op);
143
Gabor Greif177dd3f2008-06-12 21:37:33 +0000144 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
145 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000146 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000147 // Set the operand to undef to drop the use.
Owen Andersond672ecb2009-07-03 00:17:18 +0000148 *i = Context->getUndef(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000149 }
150
151 return R;
152 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000153
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000154 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000155 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000156
157 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000158
Chris Lattner97e52e42002-04-28 21:27:06 +0000159 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000160 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000161 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000162 }
163
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000164 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000165
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // Visitation implementation - Implement instruction combining for different
167 // instruction types. The semantics are as follows:
168 // Return Value:
169 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000170 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000171 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000172 //
Chris Lattner7e708292002-06-25 16:13:24 +0000173 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000174 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000175 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000176 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000177 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000178 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000179 Instruction *visitURem(BinaryOperator &I);
180 Instruction *visitSRem(BinaryOperator &I);
181 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000182 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000183 Instruction *commonRemTransforms(BinaryOperator &I);
184 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000185 Instruction *commonDivTransforms(BinaryOperator &I);
186 Instruction *commonIDivTransforms(BinaryOperator &I);
187 Instruction *visitUDiv(BinaryOperator &I);
188 Instruction *visitSDiv(BinaryOperator &I);
189 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000190 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000191 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000192 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000193 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000194 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000195 Instruction *visitOr (BinaryOperator &I);
196 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000197 Instruction *visitShl(BinaryOperator &I);
198 Instruction *visitAShr(BinaryOperator &I);
199 Instruction *visitLShr(BinaryOperator &I);
200 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000201 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000203 Instruction *visitFCmpInst(FCmpInst &I);
204 Instruction *visitICmpInst(ICmpInst &I);
205 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000206 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207 Instruction *LHS,
208 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000209 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000211
Reid Spencere4d87aa2006-12-23 06:05:41 +0000212 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000214 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000215 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *commonCastTransforms(CastInst &CI);
217 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000218 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000219 Instruction *visitTrunc(TruncInst &CI);
220 Instruction *visitZExt(ZExtInst &CI);
221 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000222 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000223 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000224 Instruction *visitFPToUI(FPToUIInst &FI);
225 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000226 Instruction *visitUIToFP(CastInst &CI);
227 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000228 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000229 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000230 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000231 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000233 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000234 Instruction *visitSelectInst(SelectInst &SI);
235 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 Instruction *visitCallInst(CallInst &CI);
237 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitPHINode(PHINode &PN);
239 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000240 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000241 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000242 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000243 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000244 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000245 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000246 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000247 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000248 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000249 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000250
251 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000252 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000253
Chris Lattner9fe38862003-06-19 17:00:31 +0000254 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000255 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000256 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000257 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000258 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000260 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000261 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
Chris Lattner9fe38862003-06-19 17:00:31 +0000263
Chris Lattner28977af2004-04-05 01:30:19 +0000264 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000265 // InsertNewInstBefore - insert an instruction New before instruction Old
266 // in the program. Add the new instruction to the worklist.
267 //
Chris Lattner955f3312004-09-28 21:48:02 +0000268 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000269 assert(New && New->getParent() == 0 &&
270 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000271 BasicBlock *BB = Old.getParent();
272 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000273 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000274 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000275 }
276
Chris Lattner0c967662004-09-24 15:21:34 +0000277 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278 /// This also adds the cast to the worklist. Finally, this returns the
279 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000280 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000282 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000283
Chris Lattnere2ed0572006-04-06 19:19:17 +0000284 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000285 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000286
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000287 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000288 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000289 return C;
290 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000291
292 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294 }
295
Chris Lattner0c967662004-09-24 15:21:34 +0000296
Chris Lattner8b170942002-08-09 23:47:40 +0000297 // ReplaceInstUsesWith - This method is to be used when an instruction is
298 // found to be dead, replacable with another preexisting expression. Here
299 // we add all uses of I to the worklist, replace all uses of I with the new
300 // value, then return I, so that the inst combiner will know that I was
301 // modified.
302 //
303 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000304 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000305 if (&I != V) {
306 I.replaceAllUsesWith(V);
307 return &I;
308 } else {
309 // If we are replacing the instruction with itself, this must be in a
310 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000311 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000312 return &I;
313 }
Chris Lattner8b170942002-08-09 23:47:40 +0000314 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315
316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
319 // this function.
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000323 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000324 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000325 return 0; // Don't do anything with FI
326 }
Chris Lattner173234a2008-06-02 01:18:21 +0000327
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331 }
332
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 }
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000340
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000341 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000342
Reid Spencere4d87aa2006-12-23 06:05:41 +0000343 /// SimplifyCommutative - This performs a few simplifications for
344 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000345 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000346
Reid Spencere4d87aa2006-12-23 06:05:41 +0000347 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348 /// most-complex to least-complex order.
349 bool SimplifyCompare(CmpInst &I);
350
Chris Lattner886ab6c2009-01-31 08:15:18 +0000351 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352 /// based on the demanded bits.
353 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
354 APInt& KnownZero, APInt& KnownOne,
355 unsigned Depth);
356 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000357 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000358 unsigned Depth=0);
359
360 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361 /// SimplifyDemandedBits knows about. See if the instruction has any
362 /// properties that allow us to simplify its operands.
363 bool SimplifyDemandedInstructionBits(Instruction &Inst);
364
Evan Cheng388df622009-02-03 10:05:09 +0000365 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000367
Chris Lattner4e998b22004-09-29 05:07:12 +0000368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
Chris Lattnerbac32862004-11-14 19:13:23 +0000373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000378 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
Chris Lattner7da52b22006-11-01 04:51:18 +0000380
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000383
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000385 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000387 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000389 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000393
Chris Lattnerafe91a52006-06-15 19:07:26 +0000394
Reid Spencerc55b2432006-12-13 18:21:21 +0000395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396
Dan Gohman6de29f82009-06-15 22:12:54 +0000397 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000398 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000401
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000402 };
403}
404
Dan Gohman844731a2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Chris Lattner4f98c562003-03-10 21:43:22 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000411static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000412 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000413 if (BinaryOperator::isNeg(V) ||
414 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000415 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000416 return 3;
417 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000418 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000419 if (isa<Argument>(V)) return 3;
420 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000421}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000422
Chris Lattnerc8802d22003-03-11 00:12:48 +0000423// isOnlyUse - Return true if this instruction will be deleted if we stop using
424// it.
425static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000426 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000427}
428
Chris Lattner4cb170c2004-02-23 06:38:22 +0000429// getPromotedType - Return the specified type promoted as it would be to pass
430// though a va_arg area...
431static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000432 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433 if (ITy->getBitWidth() < 32)
434 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000435 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000436 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000437}
438
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000439/// getBitCastOperand - If the specified operand is a CastInst, a constant
440/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
441/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000442static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000443 if (Operator *O = dyn_cast<Operator>(V)) {
444 if (O->getOpcode() == Instruction::BitCast)
445 return O->getOperand(0);
446 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
447 if (GEP->hasAllZeroIndices())
448 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000449 }
Chris Lattnereed48272005-09-13 00:40:14 +0000450 return 0;
451}
452
Reid Spencer3da59db2006-11-27 01:05:10 +0000453/// This function is a wrapper around CastInst::isEliminableCastPair. It
454/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000455static Instruction::CastOps
456isEliminableCastPair(
457 const CastInst *CI, ///< The first cast instruction
458 unsigned opcode, ///< The opcode of the second cast instruction
459 const Type *DstTy, ///< The target type for the second cast instruction
460 TargetData *TD ///< The target data for pointer size
461) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000462
Reid Spencer3da59db2006-11-27 01:05:10 +0000463 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
464 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000465
Reid Spencer3da59db2006-11-27 01:05:10 +0000466 // Get the opcodes of the two Cast instructions
467 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
468 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000469
Chris Lattnera0e69692009-03-24 18:35:40 +0000470 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000471 DstTy,
472 TD ? TD->getIntPtrType() : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000473
474 // We don't want to form an inttoptr or ptrtoint that converts to an integer
475 // type that differs from the pointer size.
476 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
477 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
478 Res = 0;
479
480 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000481}
482
483/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
484/// in any code being generated. It does not require codegen if V is simple
485/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000486static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
487 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000488 if (V->getType() == Ty || isa<Constant>(V)) return false;
489
Chris Lattner01575b72006-05-25 23:24:33 +0000490 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000491 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000492 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000493 return false;
494 return true;
495}
496
Chris Lattner4f98c562003-03-10 21:43:22 +0000497// SimplifyCommutative - This performs a few simplifications for commutative
498// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000499//
Chris Lattner4f98c562003-03-10 21:43:22 +0000500// 1. Order operands such that they are listed from right (least complex) to
501// left (most complex). This puts constants before unary operators before
502// binary operators.
503//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
505// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000506//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000508 bool Changed = false;
Owen Anderson0a5372e2009-07-13 04:09:18 +0000509 if (getComplexity(Context, I.getOperand(0)) <
510 getComplexity(Context, I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000512
Chris Lattner4f98c562003-03-10 21:43:22 +0000513 if (!I.isAssociative()) return Changed;
514 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517 if (isa<Constant>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000518 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000519 cast<Constant>(I.getOperand(1)),
520 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 I.setOperand(0, Op->getOperand(0));
522 I.setOperand(1, Folded);
523 return true;
524 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526 isOnlyUse(Op) && isOnlyUse(Op1)) {
527 Constant *C1 = cast<Constant>(Op->getOperand(1));
528 Constant *C2 = cast<Constant>(Op1->getOperand(1));
529
530 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersond672ecb2009-07-03 00:17:18 +0000531 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000532 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000533 Op1->getOperand(0),
534 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000535 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536 I.setOperand(0, New);
537 I.setOperand(1, Folded);
538 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000539 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000540 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000541 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000542}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000543
Reid Spencere4d87aa2006-12-23 06:05:41 +0000544/// SimplifyCompare - For a CmpInst this function just orders the operands
545/// so that theyare listed from right (least complex) to left (most complex).
546/// This puts constants before unary operators before binary operators.
547bool InstCombiner::SimplifyCompare(CmpInst &I) {
Owen Anderson0a5372e2009-07-13 04:09:18 +0000548 if (getComplexity(Context, I.getOperand(0)) >=
549 getComplexity(Context, I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000550 return false;
551 I.swapOperands();
552 // Compare instructions are not associative so there's nothing else we can do.
553 return true;
554}
555
Chris Lattner8d969642003-03-10 23:06:50 +0000556// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000558//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000559static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000560 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000561 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000562
Chris Lattner0ce85802004-12-14 20:08:06 +0000563 // Constants can be considered to be negated values if they can be folded.
564 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000565 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000566
567 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568 if (C->getType()->getElementType()->isInteger())
Owen Andersond672ecb2009-07-03 00:17:18 +0000569 return Context->getConstantExprNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000570
Chris Lattner8d969642003-03-10 23:06:50 +0000571 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000572}
573
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000574// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
575// instruction if the LHS is a constant negative zero (which is the 'negate'
576// form).
577//
Owen Anderson07cf79e2009-07-06 23:00:19 +0000578static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000579 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000580 return BinaryOperator::getFNegArgument(V);
581
582 // Constants can be considered to be negated values if they can be folded.
583 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000584 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000585
586 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
587 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersond672ecb2009-07-03 00:17:18 +0000588 return Context->getConstantExprFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589
590 return 0;
591}
592
Owen Anderson07cf79e2009-07-06 23:00:19 +0000593static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Chris Lattner8d969642003-03-10 23:06:50 +0000594 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000595 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000596
597 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000598 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000599 return Context->getConstantInt(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000600 return 0;
601}
602
Chris Lattnerc8802d22003-03-11 00:12:48 +0000603// dyn_castFoldableMul - If this value is a multiply that can be folded into
604// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000605// non-constant operand of the multiply, and set CST to point to the multiplier.
606// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000607//
Owen Andersond672ecb2009-07-03 00:17:18 +0000608static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000609 LLVMContext *Context) {
Chris Lattner42a75512007-01-15 02:27:26 +0000610 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000611 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000612 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000613 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000614 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000615 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000616 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000617 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000618 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000619 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Andersond672ecb2009-07-03 00:17:18 +0000620 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000621 return I->getOperand(0);
622 }
623 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000624 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000625}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000626
Chris Lattner574da9b2005-01-13 20:14:25 +0000627/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
628/// expression, return it.
629static User *dyn_castGetElementPtr(Value *V) {
630 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
631 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
632 if (CE->getOpcode() == Instruction::GetElementPtr)
633 return cast<User>(V);
634 return false;
635}
636
Reid Spencer7177c3a2007-03-25 05:33:51 +0000637/// AddOne - Add one to a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000638static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000639 return Context->getConstantExprAdd(C,
640 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000641}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000642/// SubOne - Subtract one from a ConstantInt
Owen Anderson07cf79e2009-07-06 23:00:19 +0000643static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +0000644 return Context->getConstantExprSub(C,
645 Context->getConstantInt(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000646}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000647/// MultiplyOverflows - True if the multiply can not be expressed in an int
648/// this size.
Owen Andersond672ecb2009-07-03 00:17:18 +0000649static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000650 LLVMContext *Context) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000651 uint32_t W = C1->getBitWidth();
652 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
653 if (sign) {
654 LHSExt.sext(W * 2);
655 RHSExt.sext(W * 2);
656 } else {
657 LHSExt.zext(W * 2);
658 RHSExt.zext(W * 2);
659 }
660
661 APInt MulExt = LHSExt * RHSExt;
662
663 if (sign) {
664 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
665 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
666 return MulExt.slt(Min) || MulExt.sgt(Max);
667 } else
668 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
669}
Chris Lattner955f3312004-09-28 21:48:02 +0000670
Reid Spencere7816b52007-03-08 01:52:58 +0000671
Chris Lattner255d8912006-02-11 09:31:47 +0000672/// ShrinkDemandedConstant - Check to see if the specified operand of the
673/// specified instruction is a constant integer. If so, check to see if there
674/// are any bits set in the constant that are not demanded. If so, shrink the
675/// constant and return true.
676static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +0000677 APInt Demanded, LLVMContext *Context) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000678 assert(I && "No instruction?");
679 assert(OpNo < I->getNumOperands() && "Operand index too large");
680
681 // If the operand is not a constant integer, nothing to do.
682 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
683 if (!OpC) return false;
684
685 // If there are no bits set that aren't demanded, nothing to do.
686 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
687 if ((~Demanded & OpC->getValue()) == 0)
688 return false;
689
690 // This instruction is producing bits that are not demanded. Shrink the RHS.
691 Demanded &= OpC->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +0000692 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000693 return true;
694}
695
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000696// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
697// set of known zero and one bits, compute the maximum and minimum values that
698// could have the specified known zero and known one bits, returning them in
699// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000700static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000701 const APInt& KnownOne,
702 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000703 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
704 KnownZero.getBitWidth() == Min.getBitWidth() &&
705 KnownZero.getBitWidth() == Max.getBitWidth() &&
706 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000707 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000708
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000709 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
710 // bit if it is unknown.
711 Min = KnownOne;
712 Max = KnownOne|UnknownBits;
713
Dan Gohman1c8491e2009-04-25 17:12:48 +0000714 if (UnknownBits.isNegative()) { // Sign bit is unknown
715 Min.set(Min.getBitWidth()-1);
716 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000718}
719
720// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
721// a set of known zero and one bits, compute the maximum and minimum values that
722// could have the specified known zero and known one bits, returning them in
723// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000724static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000725 const APInt &KnownOne,
726 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000727 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
728 KnownZero.getBitWidth() == Min.getBitWidth() &&
729 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000730 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000731 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000732
733 // The minimum value is when the unknown bits are all zeros.
734 Min = KnownOne;
735 // The maximum value is when the unknown bits are all ones.
736 Max = KnownOne|UnknownBits;
737}
Chris Lattner255d8912006-02-11 09:31:47 +0000738
Chris Lattner886ab6c2009-01-31 08:15:18 +0000739/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
740/// SimplifyDemandedBits knows about. See if the instruction has any
741/// properties that allow us to simplify its operands.
742bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000743 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000744 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
745 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
746
747 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
748 KnownZero, KnownOne, 0);
749 if (V == 0) return false;
750 if (V == &Inst) return true;
751 ReplaceInstUsesWith(Inst, V);
752 return true;
753}
754
755/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
756/// specified instruction operand if possible, updating it in place. It returns
757/// true if it made any change and false otherwise.
758bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
759 APInt &KnownZero, APInt &KnownOne,
760 unsigned Depth) {
761 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
762 KnownZero, KnownOne, Depth);
763 if (NewVal == 0) return false;
764 U.set(NewVal);
765 return true;
766}
767
768
769/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
770/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000771/// that only the bits set in DemandedMask of the result of V are ever used
772/// downstream. Consequently, depending on the mask and V, it may be possible
773/// to replace V with a constant or one of its operands. In such cases, this
774/// function does the replacement and returns true. In all other cases, it
775/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000776/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000777/// to be zero in the expression. These are provided to potentially allow the
778/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
779/// the expression. KnownOne and KnownZero always follow the invariant that
780/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
781/// the bits in KnownOne and KnownZero may only be accurate for those bits set
782/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
783/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000784///
785/// This returns null if it did not change anything and it permits no
786/// simplification. This returns V itself if it did some simplification of V's
787/// operands based on the information about what bits are demanded. This returns
788/// some other non-null value if it found out that V is equal to another value
789/// in the context where the specified bits are demanded, but not for all users.
790Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
791 APInt &KnownZero, APInt &KnownOne,
792 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000793 assert(V != 0 && "Null pointer of Value???");
794 assert(Depth <= 6 && "Limit Search Depth");
795 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000796 const Type *VTy = V->getType();
797 assert((TD || !isa<PointerType>(VTy)) &&
798 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000799 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
800 (!VTy->isIntOrIntVector() ||
801 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000802 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000803 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000804 "Value *V, DemandedMask, KnownZero and KnownOne "
805 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000806 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
807 // We know all of the bits for a constant!
808 KnownOne = CI->getValue() & DemandedMask;
809 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000810 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000811 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000812 if (isa<ConstantPointerNull>(V)) {
813 // We know all of the bits for a constant!
814 KnownOne.clear();
815 KnownZero = DemandedMask;
816 return 0;
817 }
818
Chris Lattner08d2cc72009-01-31 07:26:06 +0000819 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000820 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000821 if (DemandedMask == 0) { // Not demanding any bits from V.
822 if (isa<UndefValue>(V))
823 return 0;
Owen Andersond672ecb2009-07-03 00:17:18 +0000824 return Context->getUndef(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 }
826
Chris Lattner4598c942009-01-31 08:24:16 +0000827 if (Depth == 6) // Limit search depth.
828 return 0;
829
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000830 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
831 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
832
Dan Gohman1c8491e2009-04-25 17:12:48 +0000833 Instruction *I = dyn_cast<Instruction>(V);
834 if (!I) {
835 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
836 return 0; // Only analyze instructions.
837 }
838
Chris Lattner4598c942009-01-31 08:24:16 +0000839 // If there are multiple uses of this value and we aren't at the root, then
840 // we can't do any simplifications of the operands, because DemandedMask
841 // only reflects the bits demanded by *one* of the users.
842 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000843 // Despite the fact that we can't simplify this instruction in all User's
844 // context, we can at least compute the knownzero/knownone bits, and we can
845 // do simplifications that apply to *just* the one user if we know that
846 // this instruction has a simpler value in that context.
847 if (I->getOpcode() == Instruction::And) {
848 // If either the LHS or the RHS are Zero, the result is zero.
849 ComputeMaskedBits(I->getOperand(1), DemandedMask,
850 RHSKnownZero, RHSKnownOne, Depth+1);
851 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
852 LHSKnownZero, LHSKnownOne, Depth+1);
853
854 // If all of the demanded bits are known 1 on one side, return the other.
855 // These bits cannot contribute to the result of the 'and' in this
856 // context.
857 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
858 (DemandedMask & ~LHSKnownZero))
859 return I->getOperand(0);
860 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
861 (DemandedMask & ~RHSKnownZero))
862 return I->getOperand(1);
863
864 // If all of the demanded bits in the inputs are known zeros, return zero.
865 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000866 return Context->getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000867
868 } else if (I->getOpcode() == Instruction::Or) {
869 // We can simplify (X|Y) -> X or Y in the user's context if we know that
870 // only bits from X or Y are demanded.
871
872 // If either the LHS or the RHS are One, the result is One.
873 ComputeMaskedBits(I->getOperand(1), DemandedMask,
874 RHSKnownZero, RHSKnownOne, Depth+1);
875 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
876 LHSKnownZero, LHSKnownOne, Depth+1);
877
878 // If all of the demanded bits are known zero on one side, return the
879 // other. These bits cannot contribute to the result of the 'or' in this
880 // context.
881 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
882 (DemandedMask & ~LHSKnownOne))
883 return I->getOperand(0);
884 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
885 (DemandedMask & ~RHSKnownOne))
886 return I->getOperand(1);
887
888 // If all of the potentially set bits on one side are known to be set on
889 // the other side, just use the 'other' side.
890 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
891 (DemandedMask & (~RHSKnownZero)))
892 return I->getOperand(0);
893 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
894 (DemandedMask & (~LHSKnownZero)))
895 return I->getOperand(1);
896 }
897
Chris Lattner4598c942009-01-31 08:24:16 +0000898 // Compute the KnownZero/KnownOne bits to simplify things downstream.
899 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
900 return 0;
901 }
902
903 // If this is the root being simplified, allow it to have multiple uses,
904 // just set the DemandedMask to all bits so that we can try to simplify the
905 // operands. This allows visitTruncInst (for example) to simplify the
906 // operand of a trunc without duplicating all the logic below.
907 if (Depth == 0 && !V->hasOneUse())
908 DemandedMask = APInt::getAllOnesValue(BitWidth);
909
Reid Spencer8cb68342007-03-12 17:25:59 +0000910 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000911 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000913 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000914 case Instruction::And:
915 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000916 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
917 RHSKnownZero, RHSKnownOne, Depth+1) ||
918 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000919 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 return I;
921 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
922 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000923
924 // If all of the demanded bits are known 1 on one side, return the other.
925 // These bits cannot contribute to the result of the 'and'.
926 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
927 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000928 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000929 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
930 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000932
933 // If all of the demanded bits in the inputs are known zeros, return zero.
934 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersond672ecb2009-07-03 00:17:18 +0000935 return Context->getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000936
937 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000938 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000940
941 // Output known-1 bits are only known if set in both the LHS & RHS.
942 RHSKnownOne &= LHSKnownOne;
943 // Output known-0 are known to be clear if zero in either the LHS | RHS.
944 RHSKnownZero |= LHSKnownZero;
945 break;
946 case Instruction::Or:
947 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
949 RHSKnownZero, RHSKnownOne, Depth+1) ||
950 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000951 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I;
953 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
954 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000955
956 // If all of the demanded bits are known zero on one side, return the other.
957 // These bits cannot contribute to the result of the 'or'.
958 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
959 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000961 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
962 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000963 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964
965 // If all of the potentially set bits on one side are known to be set on
966 // the other side, just use the 'other' side.
967 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
968 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000970 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
971 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000973
974 // If the RHS is a constant, see if we can simplify it.
Owen Andersond672ecb2009-07-03 00:17:18 +0000975 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000977
978 // Output known-0 bits are only known if clear in both the LHS & RHS.
979 RHSKnownZero &= LHSKnownZero;
980 // Output known-1 are known to be set if set in either the LHS | RHS.
981 RHSKnownOne |= LHSKnownOne;
982 break;
983 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
985 RHSKnownZero, RHSKnownOne, Depth+1) ||
986 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000987 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I;
989 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
990 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000991
992 // If all of the demanded bits are known zero on one side, return the other.
993 // These bits cannot contribute to the result of the 'xor'.
994 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000995 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000996 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000998
999 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1000 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1001 (RHSKnownOne & LHSKnownOne);
1002 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1003 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1004 (RHSKnownOne & LHSKnownZero);
1005
1006 // If all of the demanded bits are known to be zero on one side or the
1007 // other, turn this into an *inclusive* or.
1008 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1009 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1010 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001011 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001012 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001013 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 }
1015
1016 // If all of the demanded bits on one side are known, and all of the set
1017 // bits on that side are also known to be set on the other side, turn this
1018 // into an AND, as we know the bits will be cleared.
1019 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1020 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1021 // all known
1022 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001023 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001024 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001025 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001026 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001027 }
1028 }
1029
1030 // If the RHS is a constant, see if we can simplify it.
1031 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Andersond672ecb2009-07-03 00:17:18 +00001032 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001033 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001034
1035 RHSKnownZero = KnownZeroOut;
1036 RHSKnownOne = KnownOneOut;
1037 break;
1038 }
1039 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001040 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1041 RHSKnownZero, RHSKnownOne, Depth+1) ||
1042 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001044 return I;
1045 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1046 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001047
1048 // If the operands are constants, see if we can simplify them.
Owen Andersond672ecb2009-07-03 00:17:18 +00001049 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1050 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001052
1053 // Only known if known in both the LHS and RHS.
1054 RHSKnownOne &= LHSKnownOne;
1055 RHSKnownZero &= LHSKnownZero;
1056 break;
1057 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001058 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001059 DemandedMask.zext(truncBf);
1060 RHSKnownZero.zext(truncBf);
1061 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001062 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001063 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001065 DemandedMask.trunc(BitWidth);
1066 RHSKnownZero.trunc(BitWidth);
1067 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001069 break;
1070 }
1071 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001072 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001074
1075 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1076 if (const VectorType *SrcVTy =
1077 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1078 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1079 // Don't touch a bitcast between vectors of different element counts.
1080 return false;
1081 } else
1082 // Don't touch a scalar-to-vector bitcast.
1083 return false;
1084 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1085 // Don't touch a vector-to-scalar bitcast.
1086 return false;
1087
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001089 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 return I;
1091 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001092 break;
1093 case Instruction::ZExt: {
1094 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001095 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001096
Zhou Shengd48653a2007-03-29 04:45:55 +00001097 DemandedMask.trunc(SrcBitWidth);
1098 RHSKnownZero.trunc(SrcBitWidth);
1099 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001101 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001103 DemandedMask.zext(BitWidth);
1104 RHSKnownZero.zext(BitWidth);
1105 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001106 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001108 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 break;
1110 }
1111 case Instruction::SExt: {
1112 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001113 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001114
Reid Spencer8cb68342007-03-12 17:25:59 +00001115 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001116 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001117
Zhou Sheng01542f32007-03-29 02:26:30 +00001118 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 // If any of the sign extended bits are demanded, we know that the sign
1120 // bit is demanded.
1121 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001122 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001123
Zhou Shengd48653a2007-03-29 04:45:55 +00001124 InputDemandedBits.trunc(SrcBitWidth);
1125 RHSKnownZero.trunc(SrcBitWidth);
1126 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 InputDemandedBits.zext(BitWidth);
1131 RHSKnownZero.zext(BitWidth);
1132 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
1135 // If the sign bit of the input is known set or clear, then we know the
1136 // top bits of the result.
1137
1138 // If the input sign bit is known zero, or if the NewBits are not demanded
1139 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001140 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001141 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001142 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1143 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001144 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001145 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 }
1147 break;
1148 }
1149 case Instruction::Add: {
1150 // Figure out what the input bits are. If the top bits of the and result
1151 // are not demanded, then the add doesn't demand them from its input
1152 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // If there is a constant on the RHS, there are a variety of xformations
1156 // we can do.
1157 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1158 // If null, this should be simplified elsewhere. Some of the xforms here
1159 // won't work if the RHS is zero.
1160 if (RHS->isZero())
1161 break;
1162
1163 // If the top bit of the output is demanded, demand everything from the
1164 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001165 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001166
1167 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001168 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001169 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001171
1172 // If the RHS of the add has bits set that can't affect the input, reduce
1173 // the constant.
Owen Andersond672ecb2009-07-03 00:17:18 +00001174 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001175 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
1177 // Avoid excess work.
1178 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1179 break;
1180
1181 // Turn it into OR if input bits are zero.
1182 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1183 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001184 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 }
1188
1189 // We can say something about the output known-zero and known-one bits,
1190 // depending on potential carries from the input constant and the
1191 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1192 // bits set and the RHS constant is 0x01001, then we know we have a known
1193 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1194
1195 // To compute this, we first compute the potential carry bits. These are
1196 // the bits which may be modified. I'm not aware of a better way to do
1197 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001198 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001199 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001200
1201 // Now that we know which bits have carries, compute the known-1/0 sets.
1202
1203 // Bits are known one if they are known zero in one operand and one in the
1204 // other, and there is no input carry.
1205 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1206 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1207
1208 // Bits are known zero if they are known zero in both operands and there
1209 // is no input carry.
1210 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1211 } else {
1212 // If the high-bits of this ADD are not demanded, then it does not demand
1213 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001214 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001215 // Right fill the mask of bits for this ADD to demand the most
1216 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001217 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001218 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1219 LHSKnownZero, LHSKnownOne, Depth+1) ||
1220 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001221 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001222 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 }
1224 }
1225 break;
1226 }
1227 case Instruction::Sub:
1228 // If the high-bits of this SUB are not demanded, then it does not demand
1229 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 // Right fill the mask of bits for this SUB to demand the most
1232 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001233 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001234 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001235 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1236 LHSKnownZero, LHSKnownOne, Depth+1) ||
1237 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001241 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1242 // the known zeros and ones.
1243 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 break;
1245 case Instruction::Shl:
1246 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001247 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001248 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001251 return I;
1252 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001253 RHSKnownZero <<= ShiftAmt;
1254 RHSKnownOne <<= ShiftAmt;
1255 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001256 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001257 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 }
1259 break;
1260 case Instruction::LShr:
1261 // For a logical shift right
1262 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001263 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001264
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001266 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 return I;
1270 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1272 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001273 if (ShiftAmt) {
1274 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001276 RHSKnownZero |= HighBits; // high bits known zero.
1277 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 }
1279 break;
1280 case Instruction::AShr:
1281 // If this is an arithmetic shift right and only the low-bit is set, we can
1282 // always convert this into a logical shr, even if the shift amount is
1283 // variable. The low bit of the shift cannot be an input sign bit unless
1284 // the shift amount is >= the size of the datatype, which is undefined.
1285 if (DemandedMask == 1) {
1286 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001287 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001291
1292 // If the sign bit is the only bit demanded by this ashr, then there is no
1293 // need to do it, the shift doesn't change the high bit.
1294 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001295 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001296
1297 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001298 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001299
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001301 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001302 // If any of the "high bits" are demanded, we should set the sign bit as
1303 // demanded.
1304 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1305 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 return I;
1309 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001311 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1313 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1314
1315 // Handle the sign bits.
1316 APInt SignBit(APInt::getSignBit(BitWidth));
1317 // Adjust to where it is now in the mask.
1318 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1319
1320 // If the input sign bit is known to be zero, or if none of the top bits
1321 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001322 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 (HighBits & ~DemandedMask) == HighBits) {
1324 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001325 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001327 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1329 RHSKnownOne |= HighBits;
1330 }
1331 }
1332 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001333 case Instruction::SRem:
1334 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001335 APInt RA = Rem->getValue().abs();
1336 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001337 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001338 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001339
Nick Lewycky8e394322008-11-02 02:41:50 +00001340 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001341 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001343 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001344 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001345
1346 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1347 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001348
1349 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001352 }
1353 }
1354 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001355 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001356 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1357 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001358 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1359 KnownZero2, KnownOne2, Depth+1) ||
1360 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001361 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001363
Chris Lattner455e9ab2009-01-21 18:09:24 +00001364 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001365 Leaders = std::max(Leaders,
1366 KnownZero2.countLeadingOnes());
1367 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001369 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001370 case Instruction::Call:
1371 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1372 switch (II->getIntrinsicID()) {
1373 default: break;
1374 case Intrinsic::bswap: {
1375 // If the only bits demanded come from one byte of the bswap result,
1376 // just shift the input byte into position to eliminate the bswap.
1377 unsigned NLZ = DemandedMask.countLeadingZeros();
1378 unsigned NTZ = DemandedMask.countTrailingZeros();
1379
1380 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1381 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1382 // have 14 leading zeros, round to 8.
1383 NLZ &= ~7;
1384 NTZ &= ~7;
1385 // If we need exactly one byte, we can do this transformation.
1386 if (BitWidth-NLZ-NTZ == 8) {
1387 unsigned ResultBit = NTZ;
1388 unsigned InputBit = BitWidth-NTZ-8;
1389
1390 // Replace this with either a left or right shift to get the byte into
1391 // the right place.
1392 Instruction *NewVal;
1393 if (InputBit > ResultBit)
1394 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001395 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001396 else
1397 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00001398 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001399 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001400 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001401 }
1402
1403 // TODO: Could compute known zero/one bits based on the input.
1404 break;
1405 }
1406 }
1407 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001408 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001409 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001410 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001411
1412 // If the client is only demanding bits that we know, return the known
1413 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001414 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001415 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman1c8491e2009-04-25 17:12:48 +00001416 if (isa<PointerType>(V->getType()))
Owen Andersond672ecb2009-07-03 00:17:18 +00001417 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman1c8491e2009-04-25 17:12:48 +00001418 return C;
1419 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001420 return false;
1421}
1422
Chris Lattner867b99f2006-10-05 06:55:50 +00001423
Mon P Wangaeb06d22008-11-10 04:46:22 +00001424/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001425/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001426/// actually used by the caller. This method analyzes which elements of the
1427/// operand are undef and returns that information in UndefElts.
1428///
1429/// If the information about demanded elements can be used to simplify the
1430/// operation, the operation is simplified, then the resultant value is
1431/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001432Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1433 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001434 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001435 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001436 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001437 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001438
1439 if (isa<UndefValue>(V)) {
1440 // If the entire vector is undefined, just return this info.
1441 UndefElts = EltMask;
1442 return 0;
1443 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1444 UndefElts = EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001445 return Context->getUndef(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001446 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001447
Chris Lattner867b99f2006-10-05 06:55:50 +00001448 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001449 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1450 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001451 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001452
1453 std::vector<Constant*> Elts;
1454 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001455 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001456 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001457 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1459 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001460 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 } else { // Otherwise, defined.
1462 Elts.push_back(CP->getOperand(i));
1463 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001464
Chris Lattner867b99f2006-10-05 06:55:50 +00001465 // If we changed the constant, return it.
Owen Andersond672ecb2009-07-03 00:17:18 +00001466 Constant *NewCP = Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 return NewCP != CP ? NewCP : 0;
1468 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001469 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001470 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001471
1472 // Check if this is identity. If so, return 0 since we are not simplifying
1473 // anything.
1474 if (DemandedElts == ((1ULL << VWidth) -1))
1475 return 0;
1476
Reid Spencer9d6565a2007-02-15 02:26:10 +00001477 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +00001478 Constant *Zero = Context->getNullValue(EltTy);
1479 Constant *Undef = Context->getUndef(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001480 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001481 for (unsigned i = 0; i != VWidth; ++i) {
1482 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1483 Elts.push_back(Elt);
1484 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001485 UndefElts = DemandedElts ^ EltMask;
Owen Andersond672ecb2009-07-03 00:17:18 +00001486 return Context->getConstantVector(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 }
1488
Dan Gohman488fbfc2008-09-09 18:11:14 +00001489 // Limit search depth.
1490 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001491 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001492
1493 // If multiple users are using the root value, procede with
1494 // simplification conservatively assuming that all elements
1495 // are needed.
1496 if (!V->hasOneUse()) {
1497 // Quit if we find multiple users of a non-root value though.
1498 // They'll be handled when it's their turn to be visited by
1499 // the main instcombine process.
1500 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001501 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001502 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001503
1504 // Conservatively assume that all elements are needed.
1505 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001506 }
1507
1508 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001509 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001510
1511 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001512 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001513 Value *TmpV;
1514 switch (I->getOpcode()) {
1515 default: break;
1516
1517 case Instruction::InsertElement: {
1518 // If this is a variable index, we don't know which element it overwrites.
1519 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001520 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001521 if (Idx == 0) {
1522 // Note that we can't propagate undef elt info, because we don't know
1523 // which elt is getting updated.
1524 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1525 UndefElts2, Depth+1);
1526 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1527 break;
1528 }
1529
1530 // If this is inserting an element that isn't demanded, remove this
1531 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001532 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001533 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001534 return AddSoonDeadInstToWorklist(*I, 0);
1535
1536 // Otherwise, the element inserted overwrites whatever was there, so the
1537 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001538 APInt DemandedElts2 = DemandedElts;
1539 DemandedElts2.clear(IdxNo);
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001541 UndefElts, Depth+1);
1542 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543
1544 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001545 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001546 break;
1547 }
1548 case Instruction::ShuffleVector: {
1549 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001550 uint64_t LHSVWidth =
1551 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001552 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001553 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001554 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001555 unsigned MaskVal = Shuffle->getMaskValue(i);
1556 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001557 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001559 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001560 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001561 else
Evan Cheng388df622009-02-03 10:05:09 +00001562 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 }
1564 }
1565 }
1566
Nate Begeman7b254672009-02-11 22:36:25 +00001567 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001568 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001569 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571
Nate Begeman7b254672009-02-11 22:36:25 +00001572 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1574 UndefElts3, Depth+1);
1575 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1576
1577 bool NewUndefElts = false;
1578 for (unsigned i = 0; i < VWidth; i++) {
1579 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001580 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001581 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001582 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001583 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001584 NewUndefElts = true;
1585 UndefElts.set(i);
1586 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001587 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001588 if (UndefElts3[MaskVal - LHSVWidth]) {
1589 NewUndefElts = true;
1590 UndefElts.set(i);
1591 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001592 }
1593 }
1594
1595 if (NewUndefElts) {
1596 // Add additional discovered undefs.
1597 std::vector<Constant*> Elts;
1598 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001599 if (UndefElts[i])
Owen Andersond672ecb2009-07-03 00:17:18 +00001600 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001601 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001602 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohman488fbfc2008-09-09 18:11:14 +00001603 Shuffle->getMaskValue(i)));
1604 }
Owen Andersond672ecb2009-07-03 00:17:18 +00001605 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001606 MadeChange = true;
1607 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001608 break;
1609 }
Chris Lattner69878332007-04-14 22:29:23 +00001610 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001611 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001612 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1613 if (!VTy) break;
1614 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001615 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001616 unsigned Ratio;
1617
1618 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001619 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001620 // elements as are demanded of us.
1621 Ratio = 1;
1622 InputDemandedElts = DemandedElts;
1623 } else if (VWidth > InVWidth) {
1624 // Untested so far.
1625 break;
1626
1627 // If there are more elements in the result than there are in the source,
1628 // then an input element is live if any of the corresponding output
1629 // elements are live.
1630 Ratio = VWidth/InVWidth;
1631 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001632 if (DemandedElts[OutIdx])
1633 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001634 }
1635 } else {
1636 // Untested so far.
1637 break;
1638
1639 // If there are more elements in the source than there are in the result,
1640 // then an input element is live if the corresponding output element is
1641 // live.
1642 Ratio = InVWidth/VWidth;
1643 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001644 if (DemandedElts[InIdx/Ratio])
1645 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001646 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001647
Chris Lattner69878332007-04-14 22:29:23 +00001648 // div/rem demand all inputs, because they don't want divide by zero.
1649 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1650 UndefElts2, Depth+1);
1651 if (TmpV) {
1652 I->setOperand(0, TmpV);
1653 MadeChange = true;
1654 }
1655
1656 UndefElts = UndefElts2;
1657 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001658 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001659 // If there are more elements in the result than there are in the source,
1660 // then an output element is undef if the corresponding input element is
1661 // undef.
1662 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001663 if (UndefElts2[OutIdx/Ratio])
1664 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001665 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001666 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001667 // If there are more elements in the source than there are in the result,
1668 // then a result element is undef if all of the corresponding input
1669 // elements are undef.
1670 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1671 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001672 if (!UndefElts2[InIdx]) // Not undef?
1673 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001674 }
1675 break;
1676 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001677 case Instruction::And:
1678 case Instruction::Or:
1679 case Instruction::Xor:
1680 case Instruction::Add:
1681 case Instruction::Sub:
1682 case Instruction::Mul:
1683 // div/rem demand all inputs, because they don't want divide by zero.
1684 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685 UndefElts, Depth+1);
1686 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1688 UndefElts2, Depth+1);
1689 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1690
1691 // Output elements are undefined if both are undefined. Consider things
1692 // like undef&0. The result is known zero, not undef.
1693 UndefElts &= UndefElts2;
1694 break;
1695
1696 case Instruction::Call: {
1697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1698 if (!II) break;
1699 switch (II->getIntrinsicID()) {
1700 default: break;
1701
1702 // Binary vector operations that work column-wise. A dest element is a
1703 // function of the corresponding input elements from the two inputs.
1704 case Intrinsic::x86_sse_sub_ss:
1705 case Intrinsic::x86_sse_mul_ss:
1706 case Intrinsic::x86_sse_min_ss:
1707 case Intrinsic::x86_sse_max_ss:
1708 case Intrinsic::x86_sse2_sub_sd:
1709 case Intrinsic::x86_sse2_mul_sd:
1710 case Intrinsic::x86_sse2_min_sd:
1711 case Intrinsic::x86_sse2_max_sd:
1712 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1713 UndefElts, Depth+1);
1714 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1715 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1716 UndefElts2, Depth+1);
1717 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1718
1719 // If only the low elt is demanded and this is a scalarizable intrinsic,
1720 // scalarize it now.
1721 if (DemandedElts == 1) {
1722 switch (II->getIntrinsicID()) {
1723 default: break;
1724 case Intrinsic::x86_sse_sub_ss:
1725 case Intrinsic::x86_sse_mul_ss:
1726 case Intrinsic::x86_sse2_sub_sd:
1727 case Intrinsic::x86_sse2_mul_sd:
1728 // TODO: Lower MIN/MAX/ABS/etc
1729 Value *LHS = II->getOperand(1);
1730 Value *RHS = II->getOperand(2);
1731 // Extract the element as scalars.
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001732 LHS = InsertNewInstBefore(new ExtractElementInst(LHS,
1733 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
1734 RHS = InsertNewInstBefore(new ExtractElementInst(RHS,
1735 Context->getConstantInt(Type::Int32Ty, 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001736
1737 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001738 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001739 case Intrinsic::x86_sse_sub_ss:
1740 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001741 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001742 II->getName()), *II);
1743 break;
1744 case Intrinsic::x86_sse_mul_ss:
1745 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001746 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001747 II->getName()), *II);
1748 break;
1749 }
1750
1751 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001752 InsertElementInst::Create(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00001753 Context->getUndef(II->getType()), TmpV,
1754 Context->getConstantInt(Type::Int32Ty, 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001755 InsertNewInstBefore(New, *II);
1756 AddSoonDeadInstToWorklist(*II, 0);
1757 return New;
1758 }
1759 }
1760
1761 // Output elements are undefined if both are undefined. Consider things
1762 // like undef&0. The result is known zero, not undef.
1763 UndefElts &= UndefElts2;
1764 break;
1765 }
1766 break;
1767 }
1768 }
1769 return MadeChange ? I : 0;
1770}
1771
Dan Gohman45b4e482008-05-19 22:14:15 +00001772
Chris Lattner564a7272003-08-13 19:01:45 +00001773/// AssociativeOpt - Perform an optimization on an associative operator. This
1774/// function is designed to check a chain of associative operators for a
1775/// potential to apply a certain optimization. Since the optimization may be
1776/// applicable if the expression was reassociated, this checks the chain, then
1777/// reassociates the expression as necessary to expose the optimization
1778/// opportunity. This makes use of a special Functor, which must define
1779/// 'shouldApply' and 'apply' methods.
1780///
1781template<typename Functor>
Owen Andersond672ecb2009-07-03 00:17:18 +00001782static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001783 LLVMContext *Context) {
Chris Lattner564a7272003-08-13 19:01:45 +00001784 unsigned Opcode = Root.getOpcode();
1785 Value *LHS = Root.getOperand(0);
1786
1787 // Quick check, see if the immediate LHS matches...
1788 if (F.shouldApply(LHS))
1789 return F.apply(Root);
1790
1791 // Otherwise, if the LHS is not of the same opcode as the root, return.
1792 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001793 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001794 // Should we apply this transform to the RHS?
1795 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1796
1797 // If not to the RHS, check to see if we should apply to the LHS...
1798 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1799 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1800 ShouldApply = true;
1801 }
1802
1803 // If the functor wants to apply the optimization to the RHS of LHSI,
1804 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1805 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001806 // Now all of the instructions are in the current basic block, go ahead
1807 // and perform the reassociation.
1808 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1809
1810 // First move the selected RHS to the LHS of the root...
1811 Root.setOperand(0, LHSI->getOperand(1));
1812
1813 // Make what used to be the LHS of the root be the user of the root...
1814 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001815 if (&Root == TmpLHSI) {
Owen Andersond672ecb2009-07-03 00:17:18 +00001816 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001817 return 0;
1818 }
Chris Lattner65725312004-04-16 18:08:07 +00001819 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001820 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001821 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001822 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001823 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001824
1825 // Now propagate the ExtraOperand down the chain of instructions until we
1826 // get to LHSI.
1827 while (TmpLHSI != LHSI) {
1828 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001829 // Move the instruction to immediately before the chain we are
1830 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001831 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001832 ARI = NextLHSI;
1833
Chris Lattner564a7272003-08-13 19:01:45 +00001834 Value *NextOp = NextLHSI->getOperand(1);
1835 NextLHSI->setOperand(1, ExtraOperand);
1836 TmpLHSI = NextLHSI;
1837 ExtraOperand = NextOp;
1838 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001839
Chris Lattner564a7272003-08-13 19:01:45 +00001840 // Now that the instructions are reassociated, have the functor perform
1841 // the transformation...
1842 return F.apply(Root);
1843 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001844
Chris Lattner564a7272003-08-13 19:01:45 +00001845 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1846 }
1847 return 0;
1848}
1849
Dan Gohman844731a2008-05-13 00:00:25 +00001850namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001851
Nick Lewycky02d639f2008-05-23 04:34:58 +00001852// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001853struct AddRHS {
1854 Value *RHS;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001855 LLVMContext *Context;
1856 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001857 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1858 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001859 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00001860 Context->getConstantInt(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001861 }
1862};
1863
1864// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1865// iff C1&C2 == 0
1866struct AddMaskingAnd {
1867 Constant *C2;
Owen Anderson07cf79e2009-07-06 23:00:19 +00001868 LLVMContext *Context;
1869 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001870 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001871 ConstantInt *C1;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00001872 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Andersond672ecb2009-07-03 00:17:18 +00001873 Context->getConstantExprAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001874 }
1875 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001876 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001877 }
1878};
1879
Dan Gohman844731a2008-05-13 00:00:25 +00001880}
1881
Chris Lattner6e7ba452005-01-01 16:22:27 +00001882static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001883 InstCombiner *IC) {
Owen Anderson07cf79e2009-07-06 23:00:19 +00001884 LLVMContext *Context = IC->getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00001885
Reid Spencer3da59db2006-11-27 01:05:10 +00001886 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001887 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001888 }
1889
Chris Lattner2eefe512004-04-09 19:05:30 +00001890 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001891 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1892 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001893
Chris Lattner2eefe512004-04-09 19:05:30 +00001894 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1895 if (ConstIsRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00001896 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1897 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001898 }
1899
1900 Value *Op0 = SO, *Op1 = ConstOperand;
1901 if (!ConstIsRHS)
1902 std::swap(Op0, Op1);
1903 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001905 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001906 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001907 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1908 Op0, Op1, SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001909 else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001910 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001911 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001912 return IC->InsertNewInstBefore(New, I);
1913}
1914
1915// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1916// constant as the other operand, try to fold the binary operator into the
1917// select arguments. This also works for Cast instructions, which obviously do
1918// not have a second operand.
1919static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1920 InstCombiner *IC) {
1921 // Don't modify shared select instructions
1922 if (!SI->hasOneUse()) return 0;
1923 Value *TV = SI->getOperand(1);
1924 Value *FV = SI->getOperand(2);
1925
1926 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001927 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001928 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001929
Chris Lattner6e7ba452005-01-01 16:22:27 +00001930 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1931 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1932
Gabor Greif051a9502008-04-06 20:25:17 +00001933 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1934 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001935 }
1936 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001937}
1938
Chris Lattner4e998b22004-09-29 05:07:12 +00001939
1940/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1941/// node as operand #0, see if we can fold the instruction into the PHI (which
1942/// is only possible if all operands to the PHI are constants).
1943Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1944 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001945 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001946 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001947
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001948 // Check to see if all of the operands of the PHI are constants. If there is
1949 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001950 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001951 BasicBlock *NonConstBB = 0;
1952 for (unsigned i = 0; i != NumPHIValues; ++i)
1953 if (!isa<Constant>(PN->getIncomingValue(i))) {
1954 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001955 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001956 NonConstBB = PN->getIncomingBlock(i);
1957
1958 // If the incoming non-constant value is in I's block, we have an infinite
1959 // loop.
1960 if (NonConstBB == I.getParent())
1961 return 0;
1962 }
1963
1964 // If there is exactly one non-constant value, we can insert a copy of the
1965 // operation in that block. However, if this is a critical edge, we would be
1966 // inserting the computation one some other paths (e.g. inside a loop). Only
1967 // do this if the pred block is unconditionally branching into the phi block.
1968 if (NonConstBB) {
1969 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1970 if (!BI || !BI->isUnconditional()) return 0;
1971 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001972
1973 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001974 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001975 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001976 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001977 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001978
1979 // Next, add all of the operands to the PHI.
1980 if (I.getNumOperands() == 2) {
1981 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001982 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001983 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001984 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001985 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersond672ecb2009-07-03 00:17:18 +00001986 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001987 else
Owen Andersond672ecb2009-07-03 00:17:18 +00001988 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001989 } else {
1990 assert(PN->getIncomingBlock(i) == NonConstBB);
1991 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001992 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001993 PN->getIncomingValue(i), C, "phitmp",
1994 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001995 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson333c4002009-07-09 23:48:35 +00001996 InV = CmpInst::Create(*Context, CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001997 CI->getPredicate(),
1998 PN->getIncomingValue(i), C, "phitmp",
1999 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002000 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002001 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002
Chris Lattnerdbab3862007-03-02 21:28:56 +00002003 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002004 }
2005 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002006 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002007 } else {
2008 CastInst *CI = cast<CastInst>(&I);
2009 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002010 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002011 Value *InV;
2012 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002013 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002014 } else {
2015 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002016 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002017 I.getType(), "phitmp",
2018 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002019 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002020 }
2021 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002022 }
2023 }
2024 return ReplaceInstUsesWith(I, NewPN);
2025}
2026
Chris Lattner2454a2e2008-01-29 06:52:45 +00002027
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002028/// WillNotOverflowSignedAdd - Return true if we can prove that:
2029/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2030/// This basically requires proving that the add in the original type would not
2031/// overflow to change the sign bit or have a carry out.
2032bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2033 // There are different heuristics we can use for this. Here are some simple
2034 // ones.
2035
2036 // Add has the property that adding any two 2's complement numbers can only
2037 // have one carry bit which can change a sign. As such, if LHS and RHS each
2038 // have at least two sign bits, we know that the addition of the two values will
2039 // sign extend fine.
2040 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2041 return true;
2042
2043
2044 // If one of the operands only has one non-zero bit, and if the other operand
2045 // has a known-zero bit in a more significant place than it (not including the
2046 // sign bit) the ripple may go up to and fill the zero, but won't change the
2047 // sign. For example, (X & ~4) + 1.
2048
2049 // TODO: Implement.
2050
2051 return false;
2052}
2053
Chris Lattner2454a2e2008-01-29 06:52:45 +00002054
Chris Lattner7e708292002-06-25 16:13:24 +00002055Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002056 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002057 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002058
Chris Lattner66331a42004-04-10 22:01:55 +00002059 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002060 // X + undef -> undef
2061 if (isa<UndefValue>(RHS))
2062 return ReplaceInstUsesWith(I, RHS);
2063
Chris Lattner66331a42004-04-10 22:01:55 +00002064 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002065 if (RHSC->isNullValue())
2066 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002067
Chris Lattner66331a42004-04-10 22:01:55 +00002068 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002069 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002070 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002071 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002072 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002073 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002074
2075 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2076 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002077 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002078 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002079
Eli Friedman709b33d2009-07-13 22:27:52 +00002080 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002081 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Eli Friedman709b33d2009-07-13 22:27:52 +00002082 if (ZI->getSrcTy() == Type::Int1Ty)
2083 return SelectInst::Create(ZI->getOperand(0), AddOne(CI, Context), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002084 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002085
2086 if (isa<PHINode>(LHS))
2087 if (Instruction *NV = FoldOpIntoPhi(I))
2088 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002089
Chris Lattner4f637d42006-01-06 17:59:59 +00002090 ConstantInt *XorRHS = 0;
2091 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002092 if (isa<ConstantInt>(RHSC) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002093 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002094 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002095 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002096
Zhou Sheng4351c642007-04-02 08:20:41 +00002097 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002098 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2099 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002100 do {
2101 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002102 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2103 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002104 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2105 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002106 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002107 if (!MaskedValueIsZero(XorLHS,
2108 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002109 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002110 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002111 }
2112 }
2113 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002114 C0080Val = APIntOps::lshr(C0080Val, Size);
2115 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2116 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002117
Reid Spencer35c38852007-03-28 01:36:16 +00002118 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002119 // with funny bit widths then this switch statement should be removed. It
2120 // is just here to get the size of the "middle" type back up to something
2121 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002122 const Type *MiddleType = 0;
2123 switch (Size) {
2124 default: break;
2125 case 32: MiddleType = Type::Int32Ty; break;
2126 case 16: MiddleType = Type::Int16Ty; break;
2127 case 8: MiddleType = Type::Int8Ty; break;
2128 }
2129 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002130 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002131 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002132 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002133 }
2134 }
Chris Lattner66331a42004-04-10 22:01:55 +00002135 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002136
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002137 if (I.getType() == Type::Int1Ty)
2138 return BinaryOperator::CreateXor(LHS, RHS);
2139
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002140 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002141 if (I.getType()->isInteger()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002142 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2143 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002144
2145 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2146 if (RHSI->getOpcode() == Instruction::Sub)
2147 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2148 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2149 }
2150 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2151 if (LHSI->getOpcode() == Instruction::Sub)
2152 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2153 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2154 }
Robert Bocchino71698282004-07-27 21:02:21 +00002155 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002156
Chris Lattner5c4afb92002-05-08 22:46:53 +00002157 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002158 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002159 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002160 if (LHS->getType()->isIntOrIntVector()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002161 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002162 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002163 InsertNewInstBefore(NewAdd, I);
Owen Anderson0a5372e2009-07-13 04:09:18 +00002164 return BinaryOperator::CreateNeg(*Context, NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002165 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002166 }
2167
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002168 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002169 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002170
2171 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002172 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002173 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002174 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002175
Misha Brukmanfd939082005-04-21 23:48:37 +00002176
Chris Lattner50af16a2004-11-13 19:50:12 +00002177 ConstantInt *C2;
Owen Andersond672ecb2009-07-03 00:17:18 +00002178 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002179 if (X == RHS) // X*C + X --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002180 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002181
2182 // X*C1 + X*C2 --> X * (C1+C2)
2183 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002184 if (X == dyn_castFoldableMul(RHS, C1, Context))
2185 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002186 }
2187
2188 // X + X*C --> X * (C+1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002189 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2190 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Chris Lattner50af16a2004-11-13 19:50:12 +00002191
Chris Lattnere617c9e2007-01-05 02:17:46 +00002192 // X + ~X --> -1 since ~X = -X-1
Owen Andersond672ecb2009-07-03 00:17:18 +00002193 if (dyn_castNotVal(LHS, Context) == RHS ||
2194 dyn_castNotVal(RHS, Context) == LHS)
2195 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002196
Chris Lattnerad3448c2003-02-18 19:57:07 +00002197
Chris Lattner564a7272003-08-13 19:01:45 +00002198 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002199 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002200 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002201 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002202
2203 // A+B --> A|B iff A and B have no bits set in common.
2204 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2205 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2206 APInt LHSKnownOne(IT->getBitWidth(), 0);
2207 APInt LHSKnownZero(IT->getBitWidth(), 0);
2208 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2209 if (LHSKnownZero != 0) {
2210 APInt RHSKnownOne(IT->getBitWidth(), 0);
2211 APInt RHSKnownZero(IT->getBitWidth(), 0);
2212 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2213
2214 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002215 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002216 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002217 }
2218 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002219
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002220 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002221 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002222 Value *W, *X, *Y, *Z;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002223 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2224 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002225 if (W != Y) {
2226 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002227 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002228 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002229 std::swap(W, X);
2230 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002231 std::swap(Y, Z);
2232 std::swap(W, X);
2233 }
2234 }
2235
2236 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002237 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002238 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002239 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002240 }
2241 }
2242 }
2243
Chris Lattner6b032052003-10-02 15:11:26 +00002244 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002245 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002246 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Andersond672ecb2009-07-03 00:17:18 +00002247 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002248
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002249 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002250 if (LHS->hasOneUse() &&
2251 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002252 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002253 if (Anded == CRHS) {
2254 // See if all bits from the first bit set in the Add RHS up are included
2255 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002256 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002257
2258 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002259 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002260
2261 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002262 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002263
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002264 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2265 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002266 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002267 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002268 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002269 }
2270 }
2271 }
2272
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002273 // Try to fold constant add into select arguments.
2274 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002275 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002276 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002277 }
2278
Chris Lattner42790482007-12-20 01:56:58 +00002279 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002280 {
2281 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002282 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002283 if (!SI) {
2284 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002285 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002286 }
Chris Lattner42790482007-12-20 01:56:58 +00002287 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002288 Value *TV = SI->getTrueValue();
2289 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002290 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002291
2292 // Can we fold the add into the argument of the select?
2293 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002294 if (match(FV, m_Zero(), *Context) &&
2295 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002296 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002297 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002298 if (match(TV, m_Zero(), *Context) &&
2299 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002300 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002301 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002302 }
2303 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002304
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002305 // Check for (add (sext x), y), see if we can merge this into an
2306 // integer add followed by a sext.
2307 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2308 // (add (sext x), cst) --> (sext (add x, cst'))
2309 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2310 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002311 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002312 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002313 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002314 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2315 // Insert the new, smaller add.
2316 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2317 CI, "addconv");
2318 InsertNewInstBefore(NewAdd, I);
2319 return new SExtInst(NewAdd, I.getType());
2320 }
2321 }
2322
2323 // (add (sext x), (sext y)) --> (sext (add int x, y))
2324 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2325 // Only do this if x/y have the same type, if at last one of them has a
2326 // single use (so we don't increase the number of sexts), and if the
2327 // integer add will not overflow.
2328 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2329 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2330 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2331 RHSConv->getOperand(0))) {
2332 // Insert the new integer add.
2333 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2334 RHSConv->getOperand(0),
2335 "addconv");
2336 InsertNewInstBefore(NewAdd, I);
2337 return new SExtInst(NewAdd, I.getType());
2338 }
2339 }
2340 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002341
2342 return Changed ? &I : 0;
2343}
2344
2345Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2346 bool Changed = SimplifyCommutative(I);
2347 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2348
2349 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2350 // X + 0 --> X
2351 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002352 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002353 (I.getType())->getValueAPF()))
2354 return ReplaceInstUsesWith(I, LHS);
2355 }
2356
2357 if (isa<PHINode>(LHS))
2358 if (Instruction *NV = FoldOpIntoPhi(I))
2359 return NV;
2360 }
2361
2362 // -A + B --> B - A
2363 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002364 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002365 return BinaryOperator::CreateFSub(RHS, LHSV);
2366
2367 // A + -B --> A - B
2368 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002369 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002370 return BinaryOperator::CreateFSub(LHS, V);
2371
2372 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2373 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2374 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2375 return ReplaceInstUsesWith(I, LHS);
2376
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002377 // Check for (add double (sitofp x), y), see if we can merge this into an
2378 // integer add followed by a promotion.
2379 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2380 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2381 // ... if the constant fits in the integer value. This is useful for things
2382 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2383 // requires a constant pool load, and generally allows the add to be better
2384 // instcombined.
2385 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2386 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002387 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002388 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002389 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002390 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2391 // Insert the new integer add.
2392 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2393 CI, "addconv");
2394 InsertNewInstBefore(NewAdd, I);
2395 return new SIToFPInst(NewAdd, I.getType());
2396 }
2397 }
2398
2399 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2400 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2401 // Only do this if x/y have the same type, if at last one of them has a
2402 // single use (so we don't increase the number of int->fp conversions),
2403 // and if the integer add will not overflow.
2404 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2405 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2406 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2407 RHSConv->getOperand(0))) {
2408 // Insert the new integer add.
2409 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2410 RHSConv->getOperand(0),
2411 "addconv");
2412 InsertNewInstBefore(NewAdd, I);
2413 return new SIToFPInst(NewAdd, I.getType());
2414 }
2415 }
2416 }
2417
Chris Lattner7e708292002-06-25 16:13:24 +00002418 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002419}
2420
Chris Lattner7e708292002-06-25 16:13:24 +00002421Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002422 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002423
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002424 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002425 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002426
Chris Lattner233f7dc2002-08-12 21:17:25 +00002427 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002428 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002429 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002430
Chris Lattnere87597f2004-10-16 18:11:37 +00002431 if (isa<UndefValue>(Op0))
2432 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2433 if (isa<UndefValue>(Op1))
2434 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2435
Chris Lattnerd65460f2003-11-05 01:06:05 +00002436 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2437 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002438 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002439 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002440
Chris Lattnerd65460f2003-11-05 01:06:05 +00002441 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002442 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002443 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002444 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002445
Chris Lattner76b7a062007-01-15 07:02:54 +00002446 // -(X >>u 31) -> (X >>s 31)
2447 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002448 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002449 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002450 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002451 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002452 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002453 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002454 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002455 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002456 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002457 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002458 }
2459 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002460 }
2461 else if (SI->getOpcode() == Instruction::AShr) {
2462 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2463 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002464 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002465 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002466 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002467 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002468 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002469 }
2470 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002471 }
2472 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002473 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002474
2475 // Try to fold constant sub into select arguments.
2476 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002477 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002478 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002479
2480 // C - zext(bool) -> bool ? C - 1 : C
2481 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2482 if (ZI->getSrcTy() == Type::Int1Ty)
2483 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002484 }
2485
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002486 if (I.getType() == Type::Int1Ty)
2487 return BinaryOperator::CreateXor(Op0, Op1);
2488
Chris Lattner43d84d62005-04-07 16:15:25 +00002489 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002490 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002491 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002492 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2493 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002494 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002495 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2496 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002497 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2498 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2499 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002500 return BinaryOperator::CreateSub(
2501 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002502 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002503 }
2504
Chris Lattnerfd059242003-10-15 16:48:29 +00002505 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002506 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2507 // is not used by anyone else...
2508 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002509 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002510 // Swap the two operands of the subexpr...
2511 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2512 Op1I->setOperand(0, IIOp1);
2513 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002514
Chris Lattnera2881962003-02-18 19:28:33 +00002515 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002516 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002517 }
2518
2519 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2520 //
2521 if (Op1I->getOpcode() == Instruction::And &&
2522 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2523 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2524
Chris Lattnerf523d062004-06-09 05:08:07 +00002525 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002526 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2527 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002528 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002529 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002530
Reid Spencerac5209e2006-10-16 23:08:08 +00002531 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002532 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002533 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002534 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002535 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002536 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002537 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002538
Chris Lattnerad3448c2003-02-18 19:57:07 +00002539 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002540 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002541 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2542 Constant *CP1 =
2543 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002544 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002545 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002546 }
Chris Lattner40371712002-05-09 01:29:19 +00002547 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002548 }
Chris Lattnera2881962003-02-18 19:28:33 +00002549
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002550 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2551 if (Op0I->getOpcode() == Instruction::Add) {
2552 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2553 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2554 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2555 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2556 } else if (Op0I->getOpcode() == Instruction::Sub) {
2557 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002558 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2559 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002560 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002561 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002562
Chris Lattner50af16a2004-11-13 19:50:12 +00002563 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002564 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002565 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002566 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002567
Chris Lattner50af16a2004-11-13 19:50:12 +00002568 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002569 if (X == dyn_castFoldableMul(Op1, C2, Context))
2570 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002571 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002572 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002573}
2574
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002575Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2577
2578 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002579 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580 return BinaryOperator::CreateFAdd(Op0, V);
2581
2582 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2583 if (Op1I->getOpcode() == Instruction::FAdd) {
2584 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002585 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2586 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002587 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002588 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2589 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002590 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002591 }
2592
2593 return 0;
2594}
2595
Chris Lattnera0141b92007-07-15 20:42:37 +00002596/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2597/// comparison only checks the sign bit. If it only checks the sign bit, set
2598/// TrueIfSigned if the result of the comparison is true when the input value is
2599/// signed.
2600static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2601 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002602 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002603 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2604 TrueIfSigned = true;
2605 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002606 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2607 TrueIfSigned = true;
2608 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002609 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2610 TrueIfSigned = false;
2611 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002612 case ICmpInst::ICMP_UGT:
2613 // True if LHS u> RHS and RHS == high-bit-mask - 1
2614 TrueIfSigned = true;
2615 return RHS->getValue() ==
2616 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2617 case ICmpInst::ICMP_UGE:
2618 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2619 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002620 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002621 default:
2622 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002623 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002624}
2625
Chris Lattner7e708292002-06-25 16:13:24 +00002626Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002627 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002628 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002629
Eli Friedman1694e092009-07-18 09:12:15 +00002630 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002631 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002632
Chris Lattner233f7dc2002-08-12 21:17:25 +00002633 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002634 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2635 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002636
2637 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002638 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002639 if (SI->getOpcode() == Instruction::Shl)
2640 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002641 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002642 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002643
Zhou Sheng843f07672007-04-19 05:39:12 +00002644 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002645 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2646 if (CI->equalsInt(1)) // X * 1 == X
2647 return ReplaceInstUsesWith(I, Op0);
2648 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002649 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002650
Zhou Sheng97b52c22007-03-29 01:57:21 +00002651 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002652 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002653 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002654 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002655 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002656 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002657 if (Op1->isNullValue())
2658 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002659
2660 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2661 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002662 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002663
2664 // As above, vector X*splat(1.0) -> X in all defined cases.
2665 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002666 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2667 if (CI->equalsInt(1))
2668 return ReplaceInstUsesWith(I, Op0);
2669 }
2670 }
Chris Lattnera2881962003-02-18 19:28:33 +00002671 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002672
2673 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2674 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002675 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002676 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002677 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002678 Op1, "tmp");
2679 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002680 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002681 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002682 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002683
2684 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002685
2686 // Try to fold constant mul into select arguments.
2687 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002688 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002689 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002690
2691 if (isa<PHINode>(Op0))
2692 if (Instruction *NV = FoldOpIntoPhi(I))
2693 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002694 }
2695
Owen Andersond672ecb2009-07-03 00:17:18 +00002696 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2697 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002698 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002699
Nick Lewycky0c730792008-11-21 07:33:58 +00002700 // (X / Y) * Y = X - (X % Y)
2701 // (X / Y) * -Y = (X % Y) - X
2702 {
2703 Value *Op1 = I.getOperand(1);
2704 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2705 if (!BO ||
2706 (BO->getOpcode() != Instruction::UDiv &&
2707 BO->getOpcode() != Instruction::SDiv)) {
2708 Op1 = Op0;
2709 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2710 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002711 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002712 if (BO && BO->hasOneUse() &&
2713 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2714 (BO->getOpcode() == Instruction::UDiv ||
2715 BO->getOpcode() == Instruction::SDiv)) {
2716 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2717
2718 Instruction *Rem;
2719 if (BO->getOpcode() == Instruction::UDiv)
2720 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2721 else
2722 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2723
2724 InsertNewInstBefore(Rem, I);
2725 Rem->takeName(BO);
2726
2727 if (Op1BO == Op1)
2728 return BinaryOperator::CreateSub(Op0BO, Rem);
2729 else
2730 return BinaryOperator::CreateSub(Rem, Op0BO);
2731 }
2732 }
2733
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002734 if (I.getType() == Type::Int1Ty)
2735 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2736
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002737 // If one of the operands of the multiply is a cast from a boolean value, then
2738 // we know the bool is either zero or one, so this is a 'masking' multiply.
2739 // See if we can simplify things based on how the boolean was originally
2740 // formed.
2741 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002742 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002743 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002744 BoolCast = CI;
2745 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002746 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002747 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002748 BoolCast = CI;
2749 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002750 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002751 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2752 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002753 bool TIS = false;
2754
Reid Spencere4d87aa2006-12-23 06:05:41 +00002755 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002756 // multiply into a shift/and combination.
2757 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002758 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2759 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002760 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002761 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002762 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002763 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002764 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002765 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002766 BoolCast->getOperand(0)->getName()+
2767 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002768
2769 // If the multiply type is not the same as the source type, sign extend
2770 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002771 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002772 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2773 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002774 Instruction::CastOps opcode =
2775 (SrcBits == DstBits ? Instruction::BitCast :
2776 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2777 V = InsertCastBefore(opcode, V, I.getType(), I);
2778 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002779
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002780 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002781 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002782 }
2783 }
2784 }
2785
Chris Lattner7e708292002-06-25 16:13:24 +00002786 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002787}
2788
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002789Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2790 bool Changed = SimplifyCommutative(I);
2791 Value *Op0 = I.getOperand(0);
2792
2793 // Simplify mul instructions with a constant RHS...
2794 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2795 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2796 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2797 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2798 if (Op1F->isExactlyValue(1.0))
2799 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2800 } else if (isa<VectorType>(Op1->getType())) {
2801 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2802 // As above, vector X*splat(1.0) -> X in all defined cases.
2803 if (Constant *Splat = Op1V->getSplatValue()) {
2804 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2805 if (F->isExactlyValue(1.0))
2806 return ReplaceInstUsesWith(I, Op0);
2807 }
2808 }
2809 }
2810
2811 // Try to fold constant mul into select arguments.
2812 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2813 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2814 return R;
2815
2816 if (isa<PHINode>(Op0))
2817 if (Instruction *NV = FoldOpIntoPhi(I))
2818 return NV;
2819 }
2820
Owen Andersond672ecb2009-07-03 00:17:18 +00002821 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2822 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002823 return BinaryOperator::CreateFMul(Op0v, Op1v);
2824
2825 return Changed ? &I : 0;
2826}
2827
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002828/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2829/// instruction.
2830bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2831 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2832
2833 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2834 int NonNullOperand = -1;
2835 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2836 if (ST->isNullValue())
2837 NonNullOperand = 2;
2838 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2839 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2840 if (ST->isNullValue())
2841 NonNullOperand = 1;
2842
2843 if (NonNullOperand == -1)
2844 return false;
2845
2846 Value *SelectCond = SI->getOperand(0);
2847
2848 // Change the div/rem to use 'Y' instead of the select.
2849 I.setOperand(1, SI->getOperand(NonNullOperand));
2850
2851 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2852 // problem. However, the select, or the condition of the select may have
2853 // multiple uses. Based on our knowledge that the operand must be non-zero,
2854 // propagate the known value for the select into other uses of it, and
2855 // propagate a known value of the condition into its other users.
2856
2857 // If the select and condition only have a single use, don't bother with this,
2858 // early exit.
2859 if (SI->use_empty() && SelectCond->hasOneUse())
2860 return true;
2861
2862 // Scan the current block backward, looking for other uses of SI.
2863 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2864
2865 while (BBI != BBFront) {
2866 --BBI;
2867 // If we found a call to a function, we can't assume it will return, so
2868 // information from below it cannot be propagated above it.
2869 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2870 break;
2871
2872 // Replace uses of the select or its condition with the known values.
2873 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2874 I != E; ++I) {
2875 if (*I == SI) {
2876 *I = SI->getOperand(NonNullOperand);
2877 AddToWorkList(BBI);
2878 } else if (*I == SelectCond) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00002879 *I = NonNullOperand == 1 ? Context->getTrue() :
2880 Context->getFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002881 AddToWorkList(BBI);
2882 }
2883 }
2884
2885 // If we past the instruction, quit looking for it.
2886 if (&*BBI == SI)
2887 SI = 0;
2888 if (&*BBI == SelectCond)
2889 SelectCond = 0;
2890
2891 // If we ran out of things to eliminate, break out of the loop.
2892 if (SelectCond == 0 && SI == 0)
2893 break;
2894
2895 }
2896 return true;
2897}
2898
2899
Reid Spencer1628cec2006-10-26 06:15:43 +00002900/// This function implements the transforms on div instructions that work
2901/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2902/// used by the visitors to those instructions.
2903/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002904Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002905 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002906
Chris Lattner50b2ca42008-02-19 06:12:18 +00002907 // undef / X -> 0 for integer.
2908 // undef / X -> undef for FP (the undef could be a snan).
2909 if (isa<UndefValue>(Op0)) {
2910 if (Op0->getType()->isFPOrFPVector())
2911 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002912 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002913 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002914
2915 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002916 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002917 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002918
Reid Spencer1628cec2006-10-26 06:15:43 +00002919 return 0;
2920}
Misha Brukmanfd939082005-04-21 23:48:37 +00002921
Reid Spencer1628cec2006-10-26 06:15:43 +00002922/// This function implements the transforms common to both integer division
2923/// instructions (udiv and sdiv). It is called by the visitors to those integer
2924/// division instructions.
2925/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002926Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002927 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2928
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002929 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002930 if (Op0 == Op1) {
2931 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002932 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002933 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002934 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002935 }
2936
Owen Andersond672ecb2009-07-03 00:17:18 +00002937 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002938 return ReplaceInstUsesWith(I, CI);
2939 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002940
Reid Spencer1628cec2006-10-26 06:15:43 +00002941 if (Instruction *Common = commonDivTransforms(I))
2942 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002943
2944 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2945 // This does not apply for fdiv.
2946 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2947 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002948
2949 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2950 // div X, 1 == X
2951 if (RHS->equalsInt(1))
2952 return ReplaceInstUsesWith(I, Op0);
2953
2954 // (X / C1) / C2 -> X / (C1*C2)
2955 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2956 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2957 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002958 if (MultiplyOverflows(RHS, LHSRHS,
2959 I.getOpcode()==Instruction::SDiv, Context))
2960 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002961 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002962 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002963 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002964 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002965
Reid Spencerbca0e382007-03-23 20:05:17 +00002966 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002967 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2968 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2969 return R;
2970 if (isa<PHINode>(Op0))
2971 if (Instruction *NV = FoldOpIntoPhi(I))
2972 return NV;
2973 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002974 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002975
Chris Lattnera2881962003-02-18 19:28:33 +00002976 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002977 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002978 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00002979 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002980
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002981 // It can't be division by zero, hence it must be division by one.
2982 if (I.getType() == Type::Int1Ty)
2983 return ReplaceInstUsesWith(I, Op0);
2984
Nick Lewycky895f0852008-11-27 20:21:08 +00002985 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2986 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2987 // div X, 1 == X
2988 if (X->isOne())
2989 return ReplaceInstUsesWith(I, Op0);
2990 }
2991
Reid Spencer1628cec2006-10-26 06:15:43 +00002992 return 0;
2993}
2994
2995Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2996 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2997
2998 // Handle the integer div common cases
2999 if (Instruction *Common = commonIDivTransforms(I))
3000 return Common;
3001
Reid Spencer1628cec2006-10-26 06:15:43 +00003002 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003003 // X udiv C^2 -> X >> C
3004 // Check to see if this is an unsigned division with an exact power of 2,
3005 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003006 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003007 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003008 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003009
3010 // X udiv C, where C >= signbit
3011 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003012 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3013 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003014 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003015 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3016 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003017 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003018 }
3019
3020 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003021 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003022 if (RHSI->getOpcode() == Instruction::Shl &&
3023 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003024 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003025 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003026 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003027 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003028 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003029 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003030 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003031 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003032 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003033 }
3034 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003035 }
3036
Reid Spencer1628cec2006-10-26 06:15:43 +00003037 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3038 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003039 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003040 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003042 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003043 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003044 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003045 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003047 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003048 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003049 Op0, TC, SI->getName()+".t");
3050 TSI = InsertNewInstBefore(TSI, I);
3051
3052 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003053 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003054 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003055 Op0, FC, SI->getName()+".f");
3056 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003057
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003058 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003059 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003060 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003061 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003062 return 0;
3063}
3064
Reid Spencer1628cec2006-10-26 06:15:43 +00003065Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3066 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067
3068 // Handle the integer div common cases
3069 if (Instruction *Common = commonIDivTransforms(I))
3070 return Common;
3071
3072 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3073 // sdiv X, -1 == -X
3074 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003075 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003076 }
3077
3078 // If the sign bits of both operands are zero (i.e. we can prove they are
3079 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003080 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003081 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003082 if (MaskedValueIsZero(Op0, Mask)) {
3083 if (MaskedValueIsZero(Op1, Mask)) {
3084 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3085 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3086 }
3087 ConstantInt *ShiftedInt;
3088 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value()), *Context) &&
3089 ShiftedInt->getValue().isPowerOf2()) {
3090 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3091 // Safe because the only negative value (1 << Y) can take on is
3092 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3093 // the sign bit set.
3094 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3095 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003096 }
Eli Friedman8be17392009-07-18 09:53:21 +00003097 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003098
3099 return 0;
3100}
3101
3102Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3103 return commonDivTransforms(I);
3104}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003105
Reid Spencer0a783f72006-11-02 01:53:59 +00003106/// This function implements the transforms on rem instructions that work
3107/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3108/// is used by the visitors to those instructions.
3109/// @brief Transforms common to all three rem instructions
3110Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003112
Chris Lattner50b2ca42008-02-19 06:12:18 +00003113 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3114 if (I.getType()->isFPOrFPVector())
3115 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003116 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003117 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003118 if (isa<UndefValue>(Op1))
3119 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003120
3121 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003122 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3123 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003124
Reid Spencer0a783f72006-11-02 01:53:59 +00003125 return 0;
3126}
3127
3128/// This function implements the transforms common to both integer remainder
3129/// instructions (urem and srem). It is called by the visitors to those integer
3130/// remainder instructions.
3131/// @brief Common integer remainder transforms
3132Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3134
3135 if (Instruction *common = commonRemTransforms(I))
3136 return common;
3137
Dale Johannesened6af242009-01-21 00:35:19 +00003138 // 0 % X == 0 for integer, we don't need to preserve faults!
3139 if (Constant *LHS = dyn_cast<Constant>(Op0))
3140 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003141 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003142
Chris Lattner857e8cd2004-12-12 21:48:58 +00003143 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003144 // X % 0 == undef, we don't need to preserve faults!
3145 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003146 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003147
Chris Lattnera2881962003-02-18 19:28:33 +00003148 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003149 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003150
Chris Lattner97943922006-02-28 05:49:21 +00003151 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3152 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3153 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3154 return R;
3155 } else if (isa<PHINode>(Op0I)) {
3156 if (Instruction *NV = FoldOpIntoPhi(I))
3157 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003158 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003159
3160 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003161 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003162 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003163 }
Chris Lattnera2881962003-02-18 19:28:33 +00003164 }
3165
Reid Spencer0a783f72006-11-02 01:53:59 +00003166 return 0;
3167}
3168
3169Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3171
3172 if (Instruction *common = commonIRemTransforms(I))
3173 return common;
3174
3175 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176 // X urem C^2 -> X and C
3177 // Check to see if this is an unsigned remainder with an exact power of 2,
3178 // if so, convert to a bitwise and.
3179 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003180 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003181 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003182 }
3183
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003184 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003185 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3186 if (RHSI->getOpcode() == Instruction::Shl &&
3187 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003188 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003189 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003190 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003191 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003192 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003193 }
3194 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003195 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003196
Reid Spencer0a783f72006-11-02 01:53:59 +00003197 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3198 // where C1&C2 are powers of two.
3199 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3200 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3201 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3202 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003203 if ((STO->getValue().isPowerOf2()) &&
3204 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003205 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003206 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3207 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003208 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003209 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3210 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003211 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003212 }
3213 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003214 }
3215
Chris Lattner3f5b8772002-05-06 16:14:14 +00003216 return 0;
3217}
3218
Reid Spencer0a783f72006-11-02 01:53:59 +00003219Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3221
Dan Gohmancff55092007-11-05 23:16:33 +00003222 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003223 if (Instruction *common = commonIRemTransforms(I))
3224 return common;
3225
Owen Andersond672ecb2009-07-03 00:17:18 +00003226 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003227 if (!isa<Constant>(RHSNeg) ||
3228 (isa<ConstantInt>(RHSNeg) &&
3229 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003230 // X % -Y -> X % Y
3231 AddUsesToWorkList(I);
3232 I.setOperand(1, RHSNeg);
3233 return &I;
3234 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003235
Dan Gohmancff55092007-11-05 23:16:33 +00003236 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003237 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003238 if (I.getType()->isInteger()) {
3239 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3240 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3241 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003242 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003243 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003244 }
3245
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003246 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003247 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3248 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003249
Nick Lewycky9dce8732008-12-20 16:48:00 +00003250 bool hasNegative = false;
3251 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3252 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3253 if (RHS->getValue().isNegative())
3254 hasNegative = true;
3255
3256 if (hasNegative) {
3257 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003258 for (unsigned i = 0; i != VWidth; ++i) {
3259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3260 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003261 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003262 else
3263 Elts[i] = RHS;
3264 }
3265 }
3266
Owen Andersond672ecb2009-07-03 00:17:18 +00003267 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003268 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003269 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270 I.setOperand(1, NewRHSV);
3271 return &I;
3272 }
3273 }
3274 }
3275
Reid Spencer0a783f72006-11-02 01:53:59 +00003276 return 0;
3277}
3278
3279Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003280 return commonRemTransforms(I);
3281}
3282
Chris Lattner457dd822004-06-09 07:59:58 +00003283// isOneBitSet - Return true if there is exactly one bit set in the specified
3284// constant.
3285static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003286 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003287}
3288
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003289// isHighOnes - Return true if the constant is of the form 1+0+.
3290// This is the same as lowones(~X).
3291static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003292 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003293}
3294
Reid Spencere4d87aa2006-12-23 06:05:41 +00003295/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003296/// are carefully arranged to allow folding of expressions such as:
3297///
3298/// (A < B) | (A > B) --> (A != B)
3299///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003300/// Note that this is only valid if the first and second predicates have the
3301/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003302///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003303/// Three bits are used to represent the condition, as follows:
3304/// 0 A > B
3305/// 1 A == B
3306/// 2 A < B
3307///
3308/// <=> Value Definition
3309/// 000 0 Always false
3310/// 001 1 A > B
3311/// 010 2 A == B
3312/// 011 3 A >= B
3313/// 100 4 A < B
3314/// 101 5 A != B
3315/// 110 6 A <= B
3316/// 111 7 Always true
3317///
3318static unsigned getICmpCode(const ICmpInst *ICI) {
3319 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003320 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003321 case ICmpInst::ICMP_UGT: return 1; // 001
3322 case ICmpInst::ICMP_SGT: return 1; // 001
3323 case ICmpInst::ICMP_EQ: return 2; // 010
3324 case ICmpInst::ICMP_UGE: return 3; // 011
3325 case ICmpInst::ICMP_SGE: return 3; // 011
3326 case ICmpInst::ICMP_ULT: return 4; // 100
3327 case ICmpInst::ICMP_SLT: return 4; // 100
3328 case ICmpInst::ICMP_NE: return 5; // 101
3329 case ICmpInst::ICMP_ULE: return 6; // 110
3330 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003331 // True -> 7
3332 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003333 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003334 return 0;
3335 }
3336}
3337
Evan Cheng8db90722008-10-14 17:15:11 +00003338/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3339/// predicate into a three bit mask. It also returns whether it is an ordered
3340/// predicate by reference.
3341static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3342 isOrdered = false;
3343 switch (CC) {
3344 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3345 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003346 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3347 case FCmpInst::FCMP_UGT: return 1; // 001
3348 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3349 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003350 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3351 case FCmpInst::FCMP_UGE: return 3; // 011
3352 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3353 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003354 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3355 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003356 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3357 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003358 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003359 default:
3360 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003361 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003362 return 0;
3363 }
3364}
3365
Reid Spencere4d87aa2006-12-23 06:05:41 +00003366/// getICmpValue - This is the complement of getICmpCode, which turns an
3367/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003368/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003369/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003370static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003371 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003372 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003373 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersonb3056fa2009-07-21 18:03:38 +00003374 case 0: return Context->getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003375 case 1:
3376 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003377 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003378 else
Owen Anderson333c4002009-07-09 23:48:35 +00003379 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3380 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003381 case 3:
3382 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003383 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384 else
Owen Anderson333c4002009-07-09 23:48:35 +00003385 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 case 4:
3387 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003388 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 else
Owen Anderson333c4002009-07-09 23:48:35 +00003390 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3391 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392 case 6:
3393 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003394 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 else
Owen Anderson333c4002009-07-09 23:48:35 +00003396 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003397 case 7: return Context->getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003398 }
3399}
3400
Evan Cheng8db90722008-10-14 17:15:11 +00003401/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3402/// opcode and two operands into either a FCmp instruction. isordered is passed
3403/// in to determine which kind of predicate to use in the new fcmp instruction.
3404static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003405 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003406 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003407 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003408 case 0:
3409 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003411 else
Owen Anderson333c4002009-07-09 23:48:35 +00003412 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003413 case 1:
3414 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003415 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003416 else
Owen Anderson333c4002009-07-09 23:48:35 +00003417 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003418 case 2:
3419 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003420 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003421 else
Owen Anderson333c4002009-07-09 23:48:35 +00003422 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003423 case 3:
3424 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003425 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003426 else
Owen Anderson333c4002009-07-09 23:48:35 +00003427 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003428 case 4:
3429 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003430 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003431 else
Owen Anderson333c4002009-07-09 23:48:35 +00003432 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 case 5:
3434 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003436 else
Owen Anderson333c4002009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003438 case 6:
3439 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003440 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003441 else
Owen Anderson333c4002009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersonb3056fa2009-07-21 18:03:38 +00003443 case 7: return Context->getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003444 }
3445}
3446
Chris Lattnerb9553d62008-11-16 04:55:20 +00003447/// PredicatesFoldable - Return true if both predicates match sign or if at
3448/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003449static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3450 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003451 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3452 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453}
3454
3455namespace {
3456// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3457struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003458 InstCombiner &IC;
3459 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003460 ICmpInst::Predicate pred;
3461 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3462 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3463 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003464 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3466 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003467 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3468 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003469 return false;
3470 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003471 Instruction *apply(Instruction &Log) const {
3472 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3473 if (ICI->getOperand(0) != LHS) {
3474 assert(ICI->getOperand(1) == LHS);
3475 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003476 }
3477
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003478 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003480 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003481 unsigned Code;
3482 switch (Log.getOpcode()) {
3483 case Instruction::And: Code = LHSCode & RHSCode; break;
3484 case Instruction::Or: Code = LHSCode | RHSCode; break;
3485 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003486 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003487 }
3488
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003489 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3490 ICmpInst::isSignedPredicate(ICI->getPredicate());
3491
Owen Andersond672ecb2009-07-03 00:17:18 +00003492 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003493 if (Instruction *I = dyn_cast<Instruction>(RV))
3494 return I;
3495 // Otherwise, it's a constant boolean value...
3496 return IC.ReplaceInstUsesWith(Log, RV);
3497 }
3498};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003499} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003500
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003501// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3502// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003503// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003504Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003505 ConstantInt *OpRHS,
3506 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003507 BinaryOperator &TheAnd) {
3508 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003509 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003510 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003511 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003512
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003513 switch (Op->getOpcode()) {
3514 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003515 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003517 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003519 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003520 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 }
3522 break;
3523 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003524 if (Together == AndRHS) // (X | C) & C --> C
3525 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003526
Chris Lattner6e7ba452005-01-01 16:22:27 +00003527 if (Op->hasOneUse() && Together != OpRHS) {
3528 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003529 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003530 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003531 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003532 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003533 }
3534 break;
3535 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003536 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 // Adding a one to a single bit bit-field should be turned into an XOR
3538 // of the bit. First thing to check is to see if this AND is with a
3539 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003540 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003541
3542 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003543 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 // Ok, at this point, we know that we are masking the result of the
3545 // ADD down to exactly one bit. If the constant we are adding has
3546 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003547 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003548
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // Check to see if any bits below the one bit set in AndRHSV are set.
3550 if ((AddRHS & (AndRHSV-1)) == 0) {
3551 // If not, the only thing that can effect the output of the AND is
3552 // the bit specified by AndRHSV. If that bit is set, the effect of
3553 // the XOR is to toggle the bit. If it is clear, then the ADD has
3554 // no effect.
3555 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3556 TheAnd.setOperand(0, X);
3557 return &TheAnd;
3558 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003559 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003560 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003562 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003563 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003564 }
3565 }
3566 }
3567 }
3568 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003569
3570 case Instruction::Shl: {
3571 // We know that the AND will not produce any of the bits shifted in, so if
3572 // the anded constant includes them, clear them now!
3573 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003574 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003575 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003576 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003577 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003578
Zhou Sheng290bec52007-03-29 08:15:12 +00003579 if (CI->getValue() == ShlMask) {
3580 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003581 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3582 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003583 TheAnd.setOperand(1, CI);
3584 return &TheAnd;
3585 }
3586 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003587 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003588 case Instruction::LShr:
3589 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003590 // We know that the AND will not produce any of the bits shifted in, so if
3591 // the anded constant includes them, clear them now! This only applies to
3592 // unsigned shifts, because a signed shr may bring in set bits!
3593 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003594 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003595 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003596 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003597 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003598
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 if (CI->getValue() == ShrMask) {
3600 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003601 return ReplaceInstUsesWith(TheAnd, Op);
3602 } else if (CI != AndRHS) {
3603 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3604 return &TheAnd;
3605 }
3606 break;
3607 }
3608 case Instruction::AShr:
3609 // Signed shr.
3610 // See if this is shifting in some sign extension, then masking it out
3611 // with an and.
3612 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003613 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003614 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003615 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003616 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003617 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003618 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003619 // Make the argument unsigned.
3620 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003621 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003622 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003623 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003624 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003625 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003626 }
3627 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003628 }
3629 return 0;
3630}
3631
Chris Lattner8b170942002-08-09 23:47:40 +00003632
Chris Lattnera96879a2004-09-29 17:40:11 +00003633/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3634/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3636/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003637/// insert new instructions.
3638Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 bool isSigned, bool Inside,
3640 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003641 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003642 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003643 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644
Chris Lattnera96879a2004-09-29 17:40:11 +00003645 if (Inside) {
3646 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003647 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003648
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003650 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003651 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003653 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 }
3655
3656 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003657 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003658 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003659 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003660 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003661 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003662 }
3663
3664 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003665 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003666
Reid Spencere4e40032007-03-21 23:19:50 +00003667 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003668 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003669 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670 ICmpInst::Predicate pred = (isSigned ?
3671 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003672 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003674
Reid Spencere4e40032007-03-21 23:19:50 +00003675 // Emit V-Lo >u Hi-1-Lo
3676 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003677 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003678 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003679 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003680 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003681 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003682}
3683
Chris Lattner7203e152005-09-18 07:22:02 +00003684// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3685// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3686// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3687// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003688static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003689 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003690 uint32_t BitWidth = Val->getType()->getBitWidth();
3691 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003692
3693 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003694 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003695 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003696 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003697 return true;
3698}
3699
Chris Lattner7203e152005-09-18 07:22:02 +00003700/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3701/// where isSub determines whether the operator is a sub. If we can fold one of
3702/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003703///
3704/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3705/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3706/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707///
3708/// return (A +/- B).
3709///
3710Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003711 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003712 Instruction &I) {
3713 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3714 if (!LHSI || LHSI->getNumOperands() != 2 ||
3715 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3716
3717 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3718
3719 switch (LHSI->getOpcode()) {
3720 default: return 0;
3721 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003722 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003723 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003724 if ((Mask->getValue().countLeadingZeros() +
3725 Mask->getValue().countPopulation()) ==
3726 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003727 break;
3728
3729 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3730 // part, we don't need any explicit masks to take them out of A. If that
3731 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003732 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003733 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003734 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003735 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003736 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003737 break;
3738 }
3739 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003740 return 0;
3741 case Instruction::Or:
3742 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003743 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003744 if ((Mask->getValue().countLeadingZeros() +
3745 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003746 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003747 break;
3748 return 0;
3749 }
3750
3751 Instruction *New;
3752 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003753 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003754 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003755 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003756 return InsertNewInstBefore(New, I);
3757}
3758
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003759/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3760Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3761 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003762 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003763 ConstantInt *LHSCst, *RHSCst;
3764 ICmpInst::Predicate LHSCC, RHSCC;
3765
Chris Lattnerea065fb2008-11-16 05:10:52 +00003766 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003767 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3768 m_ConstantInt(LHSCst)), *Context) ||
3769 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3770 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003771 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003772
3773 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3774 // where C is a power of 2
3775 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3776 LHSCst->getValue().isPowerOf2()) {
3777 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3778 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003779 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003780 }
3781
3782 // From here on, we only handle:
3783 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3784 if (Val != Val2) return 0;
3785
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003786 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3787 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3788 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3789 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3790 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3791 return 0;
3792
3793 // We can't fold (ugt x, C) & (sgt x, C2).
3794 if (!PredicatesFoldable(LHSCC, RHSCC))
3795 return 0;
3796
3797 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003798 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003799 if (ICmpInst::isSignedPredicate(LHSCC) ||
3800 (ICmpInst::isEquality(LHSCC) &&
3801 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003802 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003804 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3805
3806 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 std::swap(LHS, RHS);
3808 std::swap(LHSCst, RHSCst);
3809 std::swap(LHSCC, RHSCC);
3810 }
3811
3812 // At this point, we know we have have two icmp instructions
3813 // comparing a value against two constants and and'ing the result
3814 // together. Because of the above check, we know that we only have
3815 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3816 // (from the FoldICmpLogical check above), that the two constants
3817 // are not equal and that the larger constant is on the RHS
3818 assert(LHSCst != RHSCst && "Compares not folded above?");
3819
3820 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003821 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003822 case ICmpInst::ICMP_EQ:
3823 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003824 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003825 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3826 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3827 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003828 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003829 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3830 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3831 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3832 return ReplaceInstUsesWith(I, LHS);
3833 }
3834 case ICmpInst::ICMP_NE:
3835 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003836 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003838 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003839 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 break; // (X != 13 & X u< 15) -> no change
3841 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003842 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003843 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003844 break; // (X != 13 & X s< 15) -> no change
3845 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3846 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3847 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3848 return ReplaceInstUsesWith(I, RHS);
3849 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003850 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3851 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003852 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3853 Val->getName()+".off");
3854 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003855 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003856 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003857 }
3858 break; // (X != 13 & X != 15) -> no change
3859 }
3860 break;
3861 case ICmpInst::ICMP_ULT:
3862 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003863 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003864 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3865 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003866 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003867 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3868 break;
3869 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3870 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3871 return ReplaceInstUsesWith(I, LHS);
3872 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3873 break;
3874 }
3875 break;
3876 case ICmpInst::ICMP_SLT:
3877 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003878 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003879 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3880 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00003881 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003882 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3883 break;
3884 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3885 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3886 return ReplaceInstUsesWith(I, LHS);
3887 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3888 break;
3889 }
3890 break;
3891 case ICmpInst::ICMP_UGT:
3892 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003893 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003894 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3895 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3896 return ReplaceInstUsesWith(I, RHS);
3897 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3898 break;
3899 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003900 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003901 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003902 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003903 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003904 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3905 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003906 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3907 break;
3908 }
3909 break;
3910 case ICmpInst::ICMP_SGT:
3911 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003912 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003913 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3914 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3915 return ReplaceInstUsesWith(I, RHS);
3916 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3917 break;
3918 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003919 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003920 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003921 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003922 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003923 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3924 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003925 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3926 break;
3927 }
3928 break;
3929 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003930
3931 return 0;
3932}
3933
3934
Chris Lattner7e708292002-06-25 16:13:24 +00003935Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003936 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003938
Chris Lattnere87597f2004-10-16 18:11:37 +00003939 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003940 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003941
Chris Lattner6e7ba452005-01-01 16:22:27 +00003942 // and X, X = X
3943 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003944 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003945
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003946 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003947 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003948 if (SimplifyDemandedInstructionBits(I))
3949 return &I;
3950 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003951 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003952 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003953 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003954 } else if (isa<ConstantAggregateZero>(Op1)) {
3955 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003956 }
3957 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003958
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003959 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003960 const APInt& AndRHSMask = AndRHS->getValue();
3961 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003962
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003963 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003964 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003965 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003966 Value *Op0LHS = Op0I->getOperand(0);
3967 Value *Op0RHS = Op0I->getOperand(1);
3968 switch (Op0I->getOpcode()) {
3969 case Instruction::Xor:
3970 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003971 // If the mask is only needed on one incoming arm, push it up.
3972 if (Op0I->hasOneUse()) {
3973 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3974 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003975 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003976 Op0RHS->getName()+".masked");
3977 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003978 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003979 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003980 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003981 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003982 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3983 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003984 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003985 Op0LHS->getName()+".masked");
3986 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003987 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003988 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3989 }
3990 }
3991
Chris Lattner6e7ba452005-01-01 16:22:27 +00003992 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003993 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003994 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3995 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3996 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3997 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003998 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003999 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004000 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004001 break;
4002
4003 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004004 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4005 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4006 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4007 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004008 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004009
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004010 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4011 // has 1's for all bits that the subtraction with A might affect.
4012 if (Op0I->hasOneUse()) {
4013 uint32_t BitWidth = AndRHSMask.getBitWidth();
4014 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4015 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4016
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004017 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004018 if (!(A && A->isZero()) && // avoid infinite recursion.
4019 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004020 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004021 InsertNewInstBefore(NewNeg, I);
4022 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4023 }
4024 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004025 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004026
4027 case Instruction::Shl:
4028 case Instruction::LShr:
4029 // (1 << x) & 1 --> zext(x == 0)
4030 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004031 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004032 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4033 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004034 InsertNewInstBefore(NewICmp, I);
4035 return new ZExtInst(NewICmp, I.getType());
4036 }
4037 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004038 }
4039
Chris Lattner58403262003-07-23 19:25:52 +00004040 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004041 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004042 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004043 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004044 // If this is an integer truncation or change from signed-to-unsigned, and
4045 // if the source is an and/or with immediate, transform it. This
4046 // frequently occurs for bitfield accesses.
4047 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004048 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004049 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004050 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004051 if (CastOp->getOpcode() == Instruction::And) {
4052 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004053 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4054 // This will fold the two constants together, which may allow
4055 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004056 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004057 CastOp->getOperand(0), I.getType(),
4058 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004059 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004060 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004061 Constant *C3 =
4062 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4063 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004064 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004065 } else if (CastOp->getOpcode() == Instruction::Or) {
4066 // Change: and (cast (or X, C1) to T), C2
4067 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004068 Constant *C3 =
4069 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4070 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4071 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004072 return ReplaceInstUsesWith(I, AndRHS);
4073 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004074 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004075 }
Chris Lattner06782f82003-07-23 19:36:21 +00004076 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004077
4078 // Try to fold constant and into select arguments.
4079 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004080 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004081 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004082 if (isa<PHINode>(Op0))
4083 if (Instruction *NV = FoldOpIntoPhi(I))
4084 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004085 }
4086
Owen Andersond672ecb2009-07-03 00:17:18 +00004087 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4088 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004089
Chris Lattner5b62aa72004-06-18 06:07:51 +00004090 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004091 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004092
Misha Brukmancb6267b2004-07-30 12:50:08 +00004093 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004094 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004095 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004096 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004097 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004098 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004099 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004100
4101 {
Chris Lattner003b6202007-06-15 05:58:24 +00004102 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004103 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004104 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4105 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004106
4107 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004108 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004109 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004110 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004111 }
4112 }
4113
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004114 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004115 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4116 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004117
4118 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004119 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004120 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004121 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004122 }
4123 }
Chris Lattner64daab52006-04-01 08:03:55 +00004124
4125 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004126 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004127 if (A == Op1) { // (A^B)&A -> A&(A^B)
4128 I.swapOperands(); // Simplify below
4129 std::swap(Op0, Op1);
4130 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4131 cast<BinaryOperator>(Op0)->swapOperands();
4132 I.swapOperands(); // Simplify below
4133 std::swap(Op0, Op1);
4134 }
4135 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004136
Chris Lattner64daab52006-04-01 08:03:55 +00004137 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004138 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004139 if (B == Op0) { // B&(A^B) -> B&(B^A)
4140 cast<BinaryOperator>(Op1)->swapOperands();
4141 std::swap(A, B);
4142 }
4143 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004144 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004145 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004146 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004147 }
4148 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004149
4150 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004151 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4152 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004153 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004154 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4155 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004156 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004157 }
4158
Reid Spencere4d87aa2006-12-23 06:05:41 +00004159 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4160 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004161 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004162 return R;
4163
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004164 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4165 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4166 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004167 }
4168
Chris Lattner6fc205f2006-05-05 06:39:07 +00004169 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004170 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4171 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4172 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4173 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004174 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004175 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004176 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4177 I.getType(), TD) &&
4178 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4179 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004180 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004181 Op1C->getOperand(0),
4182 I.getName());
4183 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004184 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004185 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004186 }
Chris Lattnere511b742006-11-14 07:46:50 +00004187
4188 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004189 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4190 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4191 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004192 SI0->getOperand(1) == SI1->getOperand(1) &&
4193 (SI0->hasOneUse() || SI1->hasOneUse())) {
4194 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004195 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004196 SI1->getOperand(0),
4197 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004198 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004199 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004200 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004201 }
4202
Evan Cheng8db90722008-10-14 17:15:11 +00004203 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004204 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4205 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4206 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004207 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4208 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004209 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4210 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4211 // If either of the constants are nans, then the whole thing returns
4212 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004213 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb3056fa2009-07-21 18:03:38 +00004214 return ReplaceInstUsesWith(I, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004215 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4216 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004217 }
Evan Cheng8db90722008-10-14 17:15:11 +00004218 } else {
4219 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4220 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004221 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4222 m_Value(Op0RHS)), *Context) &&
4223 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4224 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004225 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4226 // Swap RHS operands to match LHS.
4227 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4228 std::swap(Op1LHS, Op1RHS);
4229 }
Evan Cheng8db90722008-10-14 17:15:11 +00004230 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4231 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4232 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004233 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4234 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004235 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4236 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004237 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004238 else if (Op0CC == FCmpInst::FCMP_TRUE)
4239 return ReplaceInstUsesWith(I, Op1);
4240 else if (Op1CC == FCmpInst::FCMP_TRUE)
4241 return ReplaceInstUsesWith(I, Op0);
4242 bool Op0Ordered;
4243 bool Op1Ordered;
4244 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4245 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4246 if (Op1Pred == 0) {
4247 std::swap(Op0, Op1);
4248 std::swap(Op0Pred, Op1Pred);
4249 std::swap(Op0Ordered, Op1Ordered);
4250 }
4251 if (Op0Pred == 0) {
4252 // uno && ueq -> uno && (uno || eq) -> ueq
4253 // ord && olt -> ord && (ord && lt) -> olt
4254 if (Op0Ordered == Op1Ordered)
4255 return ReplaceInstUsesWith(I, Op1);
4256 // uno && oeq -> uno && (ord && eq) -> false
4257 // uno && ord -> false
4258 if (!Op0Ordered)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004259 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004260 // ord && ueq -> ord && (uno || eq) -> oeq
4261 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004262 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004263 }
4264 }
4265 }
4266 }
Chris Lattner99c65742007-10-24 05:38:08 +00004267 }
4268 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004269
Chris Lattner7e708292002-06-25 16:13:24 +00004270 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004271}
4272
Chris Lattner8c34cd22008-10-05 02:13:19 +00004273/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4274/// capable of providing pieces of a bswap. The subexpression provides pieces
4275/// of a bswap if it is proven that each of the non-zero bytes in the output of
4276/// the expression came from the corresponding "byte swapped" byte in some other
4277/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4278/// we know that the expression deposits the low byte of %X into the high byte
4279/// of the bswap result and that all other bytes are zero. This expression is
4280/// accepted, the high byte of ByteValues is set to X to indicate a correct
4281/// match.
4282///
4283/// This function returns true if the match was unsuccessful and false if so.
4284/// On entry to the function the "OverallLeftShift" is a signed integer value
4285/// indicating the number of bytes that the subexpression is later shifted. For
4286/// example, if the expression is later right shifted by 16 bits, the
4287/// OverallLeftShift value would be -2 on entry. This is used to specify which
4288/// byte of ByteValues is actually being set.
4289///
4290/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4291/// byte is masked to zero by a user. For example, in (X & 255), X will be
4292/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4293/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4294/// always in the local (OverallLeftShift) coordinate space.
4295///
4296static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4297 SmallVector<Value*, 8> &ByteValues) {
4298 if (Instruction *I = dyn_cast<Instruction>(V)) {
4299 // If this is an or instruction, it may be an inner node of the bswap.
4300 if (I->getOpcode() == Instruction::Or) {
4301 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4302 ByteValues) ||
4303 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4304 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004305 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004306
4307 // If this is a logical shift by a constant multiple of 8, recurse with
4308 // OverallLeftShift and ByteMask adjusted.
4309 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4310 unsigned ShAmt =
4311 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4312 // Ensure the shift amount is defined and of a byte value.
4313 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4314 return true;
4315
4316 unsigned ByteShift = ShAmt >> 3;
4317 if (I->getOpcode() == Instruction::Shl) {
4318 // X << 2 -> collect(X, +2)
4319 OverallLeftShift += ByteShift;
4320 ByteMask >>= ByteShift;
4321 } else {
4322 // X >>u 2 -> collect(X, -2)
4323 OverallLeftShift -= ByteShift;
4324 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004325 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004326 }
4327
4328 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4329 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4330
4331 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4332 ByteValues);
4333 }
4334
4335 // If this is a logical 'and' with a mask that clears bytes, clear the
4336 // corresponding bytes in ByteMask.
4337 if (I->getOpcode() == Instruction::And &&
4338 isa<ConstantInt>(I->getOperand(1))) {
4339 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4340 unsigned NumBytes = ByteValues.size();
4341 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4342 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4343
4344 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4345 // If this byte is masked out by a later operation, we don't care what
4346 // the and mask is.
4347 if ((ByteMask & (1 << i)) == 0)
4348 continue;
4349
4350 // If the AndMask is all zeros for this byte, clear the bit.
4351 APInt MaskB = AndMask & Byte;
4352 if (MaskB == 0) {
4353 ByteMask &= ~(1U << i);
4354 continue;
4355 }
4356
4357 // If the AndMask is not all ones for this byte, it's not a bytezap.
4358 if (MaskB != Byte)
4359 return true;
4360
4361 // Otherwise, this byte is kept.
4362 }
4363
4364 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4365 ByteValues);
4366 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004367 }
4368
Chris Lattner8c34cd22008-10-05 02:13:19 +00004369 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4370 // the input value to the bswap. Some observations: 1) if more than one byte
4371 // is demanded from this input, then it could not be successfully assembled
4372 // into a byteswap. At least one of the two bytes would not be aligned with
4373 // their ultimate destination.
4374 if (!isPowerOf2_32(ByteMask)) return true;
4375 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004376
Chris Lattner8c34cd22008-10-05 02:13:19 +00004377 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4378 // is demanded, it needs to go into byte 0 of the result. This means that the
4379 // byte needs to be shifted until it lands in the right byte bucket. The
4380 // shift amount depends on the position: if the byte is coming from the high
4381 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4382 // low part, it must be shifted left.
4383 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4384 if (InputByteNo < ByteValues.size()/2) {
4385 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4386 return true;
4387 } else {
4388 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4389 return true;
4390 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004391
4392 // If the destination byte value is already defined, the values are or'd
4393 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004394 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004395 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004396 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004397 return false;
4398}
4399
4400/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4401/// If so, insert the new bswap intrinsic and return it.
4402Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004403 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004404 if (!ITy || ITy->getBitWidth() % 16 ||
4405 // ByteMask only allows up to 32-byte values.
4406 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004407 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004408
4409 /// ByteValues - For each byte of the result, we keep track of which value
4410 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004411 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004412 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004413
4414 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004415 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4416 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004417 return 0;
4418
4419 // Check to see if all of the bytes come from the same value.
4420 Value *V = ByteValues[0];
4421 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4422
4423 // Check to make sure that all of the bytes come from the same value.
4424 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4425 if (ByteValues[i] != V)
4426 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004427 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004429 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004430 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431}
4432
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004433/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4434/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4435/// we can simplify this expression to "cond ? C : D or B".
4436static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004437 Value *C, Value *D,
4438 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004439 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004440 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004441 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004442 return 0;
4443
Chris Lattnera6a474d2008-11-16 04:26:55 +00004444 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004445 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004446 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004447 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004448 return SelectInst::Create(Cond, C, B);
4449 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004450 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004451 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004452 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004453 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004454 return 0;
4455}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004456
Chris Lattner69d4ced2008-11-16 05:20:07 +00004457/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4458Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4459 ICmpInst *LHS, ICmpInst *RHS) {
4460 Value *Val, *Val2;
4461 ConstantInt *LHSCst, *RHSCst;
4462 ICmpInst::Predicate LHSCC, RHSCC;
4463
4464 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004465 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4466 m_ConstantInt(LHSCst)), *Context) ||
4467 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4468 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004469 return 0;
4470
4471 // From here on, we only handle:
4472 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4473 if (Val != Val2) return 0;
4474
4475 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4476 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4477 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4478 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4479 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4480 return 0;
4481
4482 // We can't fold (ugt x, C) | (sgt x, C2).
4483 if (!PredicatesFoldable(LHSCC, RHSCC))
4484 return 0;
4485
4486 // Ensure that the larger constant is on the RHS.
4487 bool ShouldSwap;
4488 if (ICmpInst::isSignedPredicate(LHSCC) ||
4489 (ICmpInst::isEquality(LHSCC) &&
4490 ICmpInst::isSignedPredicate(RHSCC)))
4491 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4492 else
4493 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4494
4495 if (ShouldSwap) {
4496 std::swap(LHS, RHS);
4497 std::swap(LHSCst, RHSCst);
4498 std::swap(LHSCC, RHSCC);
4499 }
4500
4501 // At this point, we know we have have two icmp instructions
4502 // comparing a value against two constants and or'ing the result
4503 // together. Because of the above check, we know that we only have
4504 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4505 // FoldICmpLogical check above), that the two constants are not
4506 // equal.
4507 assert(LHSCst != RHSCst && "Compares not folded above?");
4508
4509 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004510 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004511 case ICmpInst::ICMP_EQ:
4512 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004513 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004514 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004515 if (LHSCst == SubOne(RHSCst, Context)) {
4516 // (X == 13 | X == 14) -> X-13 <u 2
4517 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004518 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4519 Val->getName()+".off");
4520 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004521 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004522 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004523 }
4524 break; // (X == 13 | X == 15) -> no change
4525 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4526 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4527 break;
4528 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4529 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4530 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4531 return ReplaceInstUsesWith(I, RHS);
4532 }
4533 break;
4534 case ICmpInst::ICMP_NE:
4535 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004536 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004537 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4538 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4539 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4540 return ReplaceInstUsesWith(I, LHS);
4541 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4542 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4543 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004544 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004545 }
4546 break;
4547 case ICmpInst::ICMP_ULT:
4548 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004549 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004550 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4551 break;
4552 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4553 // If RHSCst is [us]MAXINT, it is always false. Not handling
4554 // this can cause overflow.
4555 if (RHSCst->isMaxValue(false))
4556 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004557 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4558 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004559 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4560 break;
4561 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4562 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4563 return ReplaceInstUsesWith(I, RHS);
4564 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4565 break;
4566 }
4567 break;
4568 case ICmpInst::ICMP_SLT:
4569 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004570 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004571 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4572 break;
4573 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4574 // If RHSCst is [us]MAXINT, it is always false. Not handling
4575 // this can cause overflow.
4576 if (RHSCst->isMaxValue(true))
4577 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004578 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4579 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004580 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4581 break;
4582 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4583 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4584 return ReplaceInstUsesWith(I, RHS);
4585 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4586 break;
4587 }
4588 break;
4589 case ICmpInst::ICMP_UGT:
4590 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004591 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004592 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4593 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4594 return ReplaceInstUsesWith(I, LHS);
4595 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4596 break;
4597 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4598 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004599 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004600 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4601 break;
4602 }
4603 break;
4604 case ICmpInst::ICMP_SGT:
4605 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004606 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004607 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4608 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4609 return ReplaceInstUsesWith(I, LHS);
4610 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4611 break;
4612 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4613 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00004614 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004615 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4616 break;
4617 }
4618 break;
4619 }
4620 return 0;
4621}
4622
Bill Wendlinga698a472008-12-01 08:23:25 +00004623/// FoldOrWithConstants - This helper function folds:
4624///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004625/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004626///
4627/// into:
4628///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004629/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004630///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004631/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004632Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004633 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004634 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4635 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004636
Bill Wendling286a0542008-12-02 06:24:20 +00004637 Value *V1 = 0;
4638 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004639 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004640
Bill Wendling29976b92008-12-02 06:18:11 +00004641 APInt Xor = CI1->getValue() ^ CI2->getValue();
4642 if (!Xor.isAllOnesValue()) return 0;
4643
Bill Wendling286a0542008-12-02 06:24:20 +00004644 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004645 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004646 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4647 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004648 }
4649
4650 return 0;
4651}
4652
Chris Lattner7e708292002-06-25 16:13:24 +00004653Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004654 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004655 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004656
Chris Lattner42593e62007-03-24 23:56:43 +00004657 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004658 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004659
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004660 // or X, X = X
4661 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004662 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004663
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004664 // See if we can simplify any instructions used by the instruction whose sole
4665 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004666 if (SimplifyDemandedInstructionBits(I))
4667 return &I;
4668 if (isa<VectorType>(I.getType())) {
4669 if (isa<ConstantAggregateZero>(Op1)) {
4670 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4671 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4672 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4673 return ReplaceInstUsesWith(I, I.getOperand(1));
4674 }
Chris Lattner42593e62007-03-24 23:56:43 +00004675 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004676
Chris Lattner3f5b8772002-05-06 16:14:14 +00004677 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004678 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004679 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004680 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004681 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4682 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004683 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004684 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004685 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004686 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004687 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004688 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004689
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004690 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004691 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4692 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004693 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004694 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004695 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004696 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004697 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004698 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004699
4700 // Try to fold constant and into select arguments.
4701 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004702 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004703 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004704 if (isa<PHINode>(Op0))
4705 if (Instruction *NV = FoldOpIntoPhi(I))
4706 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004707 }
4708
Chris Lattner4f637d42006-01-06 17:59:59 +00004709 Value *A = 0, *B = 0;
4710 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004711
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004712 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004713 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4714 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004715 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004716 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4717 return ReplaceInstUsesWith(I, Op0);
4718
Chris Lattner6423d4c2006-07-10 20:25:24 +00004719 // (A | B) | C and A | (B | C) -> bswap if possible.
4720 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004721 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4722 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4723 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4724 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004725 if (Instruction *BSwap = MatchBSwap(I))
4726 return BSwap;
4727 }
4728
Chris Lattner6e4c6492005-05-09 04:58:36 +00004729 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004730 if (Op0->hasOneUse() &&
4731 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004732 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004733 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004734 InsertNewInstBefore(NOr, I);
4735 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004736 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004737 }
4738
4739 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004740 if (Op1->hasOneUse() &&
4741 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004742 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004743 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004744 InsertNewInstBefore(NOr, I);
4745 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004746 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004747 }
4748
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004749 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004750 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004751 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4752 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004753 Value *V1 = 0, *V2 = 0, *V3 = 0;
4754 C1 = dyn_cast<ConstantInt>(C);
4755 C2 = dyn_cast<ConstantInt>(D);
4756 if (C1 && C2) { // (A & C1)|(B & C2)
4757 // If we have: ((V + N) & C1) | (V & C2)
4758 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4759 // replace with V+N.
4760 if (C1->getValue() == ~C2->getValue()) {
4761 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004762 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004763 // Add commutes, try both ways.
4764 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4765 return ReplaceInstUsesWith(I, A);
4766 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4767 return ReplaceInstUsesWith(I, A);
4768 }
4769 // Or commutes, try both ways.
4770 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004771 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004772 // Add commutes, try both ways.
4773 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4774 return ReplaceInstUsesWith(I, B);
4775 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4776 return ReplaceInstUsesWith(I, B);
4777 }
4778 }
Chris Lattner044e5332007-04-08 08:01:49 +00004779 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004780 }
4781
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004782 // Check to see if we have any common things being and'ed. If so, find the
4783 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004784 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4785 if (A == B) // (A & C)|(A & D) == A & (C|D)
4786 V1 = A, V2 = C, V3 = D;
4787 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4788 V1 = A, V2 = B, V3 = C;
4789 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4790 V1 = C, V2 = A, V3 = D;
4791 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4792 V1 = C, V2 = A, V3 = B;
4793
4794 if (V1) {
4795 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004796 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4797 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004798 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004799 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004800
Dan Gohman1975d032008-10-30 20:40:10 +00004801 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004802 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004803 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004804 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004805 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004806 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004807 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004808 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004809 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004810
Bill Wendlingb01865c2008-11-30 13:52:49 +00004811 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004812 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4813 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004814 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004815 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004816 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4817 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004818 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004819 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004820 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4821 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004822 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004823 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004824 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4825 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004826 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004827 }
Chris Lattnere511b742006-11-14 07:46:50 +00004828
4829 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004830 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4831 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4832 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004833 SI0->getOperand(1) == SI1->getOperand(1) &&
4834 (SI0->hasOneUse() || SI1->hasOneUse())) {
4835 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004836 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004837 SI1->getOperand(0),
4838 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004839 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004840 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004841 }
4842 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004843
Bill Wendlingb3833d12008-12-01 01:07:11 +00004844 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004845 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4846 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004847 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004848 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004849 }
4850 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004851 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4852 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004853 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004854 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004855 }
4856
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004857 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004858 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004859 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004860 } else {
4861 A = 0;
4862 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004863 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004864 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004865 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004866 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004867
Misha Brukmancb6267b2004-07-30 12:50:08 +00004868 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004869 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004870 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004871 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004872 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004873 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004874 }
Chris Lattnera2881962003-02-18 19:28:33 +00004875
Reid Spencere4d87aa2006-12-23 06:05:41 +00004876 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4877 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004878 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004879 return R;
4880
Chris Lattner69d4ced2008-11-16 05:20:07 +00004881 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4882 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4883 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004884 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004885
4886 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004887 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004888 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004889 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004890 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4891 !isa<ICmpInst>(Op1C->getOperand(0))) {
4892 const Type *SrcTy = Op0C->getOperand(0)->getType();
4893 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4894 // Only do this if the casts both really cause code to be
4895 // generated.
4896 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4897 I.getType(), TD) &&
4898 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4899 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004900 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004901 Op1C->getOperand(0),
4902 I.getName());
4903 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004904 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004905 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004906 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004907 }
Chris Lattner99c65742007-10-24 05:38:08 +00004908 }
4909
4910
4911 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4912 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4913 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4914 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004915 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004916 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004917 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4918 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4919 // If either of the constants are nans, then the whole thing returns
4920 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004921 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersonb3056fa2009-07-21 18:03:38 +00004922 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004923
4924 // Otherwise, no need to compare the two constants, compare the
4925 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004926 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4927 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004928 }
Evan Cheng40300622008-10-14 18:44:08 +00004929 } else {
4930 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4931 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004932 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4933 m_Value(Op0RHS)), *Context) &&
4934 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4935 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004936 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4937 // Swap RHS operands to match LHS.
4938 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4939 std::swap(Op1LHS, Op1RHS);
4940 }
4941 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4942 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4943 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004944 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4945 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004946 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4947 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00004948 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004949 else if (Op0CC == FCmpInst::FCMP_FALSE)
4950 return ReplaceInstUsesWith(I, Op1);
4951 else if (Op1CC == FCmpInst::FCMP_FALSE)
4952 return ReplaceInstUsesWith(I, Op0);
4953 bool Op0Ordered;
4954 bool Op1Ordered;
4955 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4956 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4957 if (Op0Ordered == Op1Ordered) {
4958 // If both are ordered or unordered, return a new fcmp with
4959 // or'ed predicates.
4960 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004961 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004962 if (Instruction *I = dyn_cast<Instruction>(RV))
4963 return I;
4964 // Otherwise, it's a constant boolean value...
4965 return ReplaceInstUsesWith(I, RV);
4966 }
4967 }
4968 }
4969 }
Chris Lattner99c65742007-10-24 05:38:08 +00004970 }
4971 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004972
Chris Lattner7e708292002-06-25 16:13:24 +00004973 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004974}
4975
Dan Gohman844731a2008-05-13 00:00:25 +00004976namespace {
4977
Chris Lattnerc317d392004-02-16 01:20:27 +00004978// XorSelf - Implements: X ^ X --> 0
4979struct XorSelf {
4980 Value *RHS;
4981 XorSelf(Value *rhs) : RHS(rhs) {}
4982 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4983 Instruction *apply(BinaryOperator &Xor) const {
4984 return &Xor;
4985 }
4986};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004987
Dan Gohman844731a2008-05-13 00:00:25 +00004988}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004989
Chris Lattner7e708292002-06-25 16:13:24 +00004990Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004991 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004992 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004993
Evan Chengd34af782008-03-25 20:07:13 +00004994 if (isa<UndefValue>(Op1)) {
4995 if (isa<UndefValue>(Op0))
4996 // Handle undef ^ undef -> 0 special case. This is a common
4997 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00004998 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004999 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005000 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005001
Chris Lattnerc317d392004-02-16 01:20:27 +00005002 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005003 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005004 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005005 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005006 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005007
5008 // See if we can simplify any instructions used by the instruction whose sole
5009 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005010 if (SimplifyDemandedInstructionBits(I))
5011 return &I;
5012 if (isa<VectorType>(I.getType()))
5013 if (isa<ConstantAggregateZero>(Op1))
5014 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005015
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005016 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005017 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005018 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5019 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5020 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5021 if (Op0I->getOpcode() == Instruction::And ||
5022 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005023 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5024 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005025 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005026 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005027 Op0I->getOperand(1)->getName()+".not");
5028 InsertNewInstBefore(NotY, I);
5029 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005030 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005031 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005032 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005033 }
5034 }
5035 }
5036 }
5037
5038
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005039 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersonb3056fa2009-07-21 18:03:38 +00005040 if (RHS == Context->getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005041 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005042 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005043 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005044 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005045
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005046 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005047 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005048 FCI->getOperand(0), FCI->getOperand(1));
5049 }
5050
Nick Lewycky517e1f52008-05-31 19:01:33 +00005051 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5052 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5053 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5054 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5055 Instruction::CastOps Opcode = Op0C->getOpcode();
5056 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005057 if (RHS == Context->getConstantExprCast(Opcode,
Owen Andersonb3056fa2009-07-21 18:03:38 +00005058 Context->getTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005059 Op0C->getDestTy())) {
5060 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005061 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005062 CI->getOpcode(), CI->getInversePredicate(),
5063 CI->getOperand(0), CI->getOperand(1)), I);
5064 NewCI->takeName(CI);
5065 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5066 }
5067 }
5068 }
5069 }
5070 }
5071
Reid Spencere4d87aa2006-12-23 06:05:41 +00005072 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005073 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005074 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5075 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005076 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5077 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5078 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005079 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005080 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005081
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005082 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005083 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005084 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005085 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005086 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005087 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005088 Context->getConstantExprSub(NegOp0CI,
5089 Context->getConstantInt(I.getType(), 1)),
5090 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005091 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005092 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005093 Constant *C =
5094 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005095 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005096
Chris Lattner7c4049c2004-01-12 19:35:11 +00005097 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005098 } else if (Op0I->getOpcode() == Instruction::Or) {
5099 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005100 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005101 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005102 // Anything in both C1 and C2 is known to be zero, remove it from
5103 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005104 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5105 NewRHS = Context->getConstantExprAnd(NewRHS,
5106 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005107 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005108 I.setOperand(0, Op0I->getOperand(0));
5109 I.setOperand(1, NewRHS);
5110 return &I;
5111 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005112 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005113 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005114 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005115
5116 // Try to fold constant and into select arguments.
5117 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005118 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005119 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005120 if (isa<PHINode>(Op0))
5121 if (Instruction *NV = FoldOpIntoPhi(I))
5122 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005123 }
5124
Owen Andersond672ecb2009-07-03 00:17:18 +00005125 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005126 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005127 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005128
Owen Andersond672ecb2009-07-03 00:17:18 +00005129 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005130 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005131 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005132
Chris Lattner318bf792007-03-18 22:51:34 +00005133
5134 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5135 if (Op1I) {
5136 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005137 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005138 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005139 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005140 I.swapOperands();
5141 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005142 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005143 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005144 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005145 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005146 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005147 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005148 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005149 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005150 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5151 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005152 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005153 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005154 std::swap(A, B);
5155 }
Chris Lattner318bf792007-03-18 22:51:34 +00005156 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005157 I.swapOperands(); // Simplified below.
5158 std::swap(Op0, Op1);
5159 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005160 }
Chris Lattner318bf792007-03-18 22:51:34 +00005161 }
5162
5163 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5164 if (Op0I) {
5165 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005166 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5167 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005168 if (A == Op1) // (B|A)^B == (A|B)^B
5169 std::swap(A, B);
5170 if (B == Op1) { // (A|B)^B == A & ~B
5171 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005172 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5173 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005174 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005175 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005176 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005177 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005178 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005179 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005180 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5181 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005182 if (A == Op1) // (A&B)^A -> (B&A)^A
5183 std::swap(A, B);
5184 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005185 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005186 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005187 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005188 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005189 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005190 }
Chris Lattner318bf792007-03-18 22:51:34 +00005191 }
5192
5193 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5194 if (Op0I && Op1I && Op0I->isShift() &&
5195 Op0I->getOpcode() == Op1I->getOpcode() &&
5196 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5197 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5198 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005199 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005200 Op1I->getOperand(0),
5201 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005202 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005203 Op1I->getOperand(1));
5204 }
5205
5206 if (Op0I && Op1I) {
5207 Value *A, *B, *C, *D;
5208 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005209 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5210 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005211 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005212 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005213 }
5214 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005215 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5216 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005217 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005218 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005219 }
5220
5221 // (A & B)^(C & D)
5222 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005223 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5224 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005225 // (X & Y)^(X & Y) -> (Y^Z) & X
5226 Value *X = 0, *Y = 0, *Z = 0;
5227 if (A == C)
5228 X = A, Y = B, Z = D;
5229 else if (A == D)
5230 X = A, Y = B, Z = C;
5231 else if (B == C)
5232 X = B, Y = A, Z = D;
5233 else if (B == D)
5234 X = B, Y = A, Z = C;
5235
5236 if (X) {
5237 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005238 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5239 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005240 }
5241 }
5242 }
5243
Reid Spencere4d87aa2006-12-23 06:05:41 +00005244 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5245 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005246 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005247 return R;
5248
Chris Lattner6fc205f2006-05-05 06:39:07 +00005249 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005250 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005251 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005252 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5253 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005254 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005255 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005256 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5257 I.getType(), TD) &&
5258 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5259 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005260 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005261 Op1C->getOperand(0),
5262 I.getName());
5263 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005264 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005265 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005266 }
Chris Lattner99c65742007-10-24 05:38:08 +00005267 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005268
Chris Lattner7e708292002-06-25 16:13:24 +00005269 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005270}
5271
Owen Andersond672ecb2009-07-03 00:17:18 +00005272static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005273 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005274 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005275}
Chris Lattnera96879a2004-09-29 17:40:11 +00005276
Dan Gohman6de29f82009-06-15 22:12:54 +00005277static bool HasAddOverflow(ConstantInt *Result,
5278 ConstantInt *In1, ConstantInt *In2,
5279 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005280 if (IsSigned)
5281 if (In2->getValue().isNegative())
5282 return Result->getValue().sgt(In1->getValue());
5283 else
5284 return Result->getValue().slt(In1->getValue());
5285 else
5286 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005287}
5288
Dan Gohman6de29f82009-06-15 22:12:54 +00005289/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005290/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005291static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005292 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005293 bool IsSigned = false) {
5294 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005295
Dan Gohman6de29f82009-06-15 22:12:54 +00005296 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5297 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005298 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5299 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5300 ExtractElement(In1, Idx, Context),
5301 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005302 IsSigned))
5303 return true;
5304 }
5305 return false;
5306 }
5307
5308 return HasAddOverflow(cast<ConstantInt>(Result),
5309 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5310 IsSigned);
5311}
5312
5313static bool HasSubOverflow(ConstantInt *Result,
5314 ConstantInt *In1, ConstantInt *In2,
5315 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005316 if (IsSigned)
5317 if (In2->getValue().isNegative())
5318 return Result->getValue().slt(In1->getValue());
5319 else
5320 return Result->getValue().sgt(In1->getValue());
5321 else
5322 return Result->getValue().ugt(In1->getValue());
5323}
5324
Dan Gohman6de29f82009-06-15 22:12:54 +00005325/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5326/// overflowed for this type.
5327static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005328 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005329 bool IsSigned = false) {
5330 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005331
5332 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5333 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005334 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5335 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5336 ExtractElement(In1, Idx, Context),
5337 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005338 IsSigned))
5339 return true;
5340 }
5341 return false;
5342 }
5343
5344 return HasSubOverflow(cast<ConstantInt>(Result),
5345 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5346 IsSigned);
5347}
5348
Chris Lattner574da9b2005-01-13 20:14:25 +00005349/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5350/// code necessary to compute the offset from the base pointer (without adding
5351/// in the base pointer). Return the result as a signed integer of intptr size.
5352static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005353 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005354 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005355 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005356 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005357 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005358
5359 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005360 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005361 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005362
Gabor Greif177dd3f2008-06-12 21:37:33 +00005363 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5364 ++i, ++GTI) {
5365 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005366 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005367 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5368 if (OpC->isZero()) continue;
5369
5370 // Handle a struct index, which adds its field offset to the pointer.
5371 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5372 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5373
5374 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005375 Result =
5376 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005377 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005378 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005379 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005380 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005381 GEP->getName()+".offs"), I);
5382 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005383 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005384
Owen Andersond672ecb2009-07-03 00:17:18 +00005385 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5386 Constant *OC =
5387 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5388 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005389 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005390 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005391 else {
5392 // Emit an add instruction.
5393 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005394 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005395 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005396 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005397 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005398 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005399 // Convert to correct type.
5400 if (Op->getType() != IntPtrTy) {
5401 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005402 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005403 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005404 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5405 true,
5406 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005407 }
5408 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005409 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005410 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005411 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005412 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005413 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005414 GEP->getName()+".idx"), I);
5415 }
5416
5417 // Emit an add instruction.
5418 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005419 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005420 cast<Constant>(Result));
5421 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005422 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005423 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005424 }
5425 return Result;
5426}
5427
Chris Lattner10c0d912008-04-22 02:53:33 +00005428
Dan Gohman8f080f02009-07-17 22:16:21 +00005429/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5430/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5431/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5432/// be complex, and scales are involved. The above expression would also be
5433/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5434/// This later form is less amenable to optimization though, and we are allowed
5435/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005436///
5437/// If we can't emit an optimized form for this expression, this returns null.
5438///
5439static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5440 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005441 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005442 gep_type_iterator GTI = gep_type_begin(GEP);
5443
5444 // Check to see if this gep only has a single variable index. If so, and if
5445 // any constant indices are a multiple of its scale, then we can compute this
5446 // in terms of the scale of the variable index. For example, if the GEP
5447 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5448 // because the expression will cross zero at the same point.
5449 unsigned i, e = GEP->getNumOperands();
5450 int64_t Offset = 0;
5451 for (i = 1; i != e; ++i, ++GTI) {
5452 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5453 // Compute the aggregate offset of constant indices.
5454 if (CI->isZero()) continue;
5455
5456 // Handle a struct index, which adds its field offset to the pointer.
5457 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5458 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5459 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005460 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005461 Offset += Size*CI->getSExtValue();
5462 }
5463 } else {
5464 // Found our variable index.
5465 break;
5466 }
5467 }
5468
5469 // If there are no variable indices, we must have a constant offset, just
5470 // evaluate it the general way.
5471 if (i == e) return 0;
5472
5473 Value *VariableIdx = GEP->getOperand(i);
5474 // Determine the scale factor of the variable element. For example, this is
5475 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005476 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005477
5478 // Verify that there are no other variable indices. If so, emit the hard way.
5479 for (++i, ++GTI; i != e; ++i, ++GTI) {
5480 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5481 if (!CI) return 0;
5482
5483 // Compute the aggregate offset of constant indices.
5484 if (CI->isZero()) continue;
5485
5486 // Handle a struct index, which adds its field offset to the pointer.
5487 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5488 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5489 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005490 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005491 Offset += Size*CI->getSExtValue();
5492 }
5493 }
5494
5495 // Okay, we know we have a single variable index, which must be a
5496 // pointer/array/vector index. If there is no offset, life is simple, return
5497 // the index.
5498 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5499 if (Offset == 0) {
5500 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5501 // we don't need to bother extending: the extension won't affect where the
5502 // computation crosses zero.
5503 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5504 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5505 VariableIdx->getNameStart(), &I);
5506 return VariableIdx;
5507 }
5508
5509 // Otherwise, there is an index. The computation we will do will be modulo
5510 // the pointer size, so get it.
5511 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5512
5513 Offset &= PtrSizeMask;
5514 VariableScale &= PtrSizeMask;
5515
5516 // To do this transformation, any constant index must be a multiple of the
5517 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5518 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5519 // multiple of the variable scale.
5520 int64_t NewOffs = Offset / (int64_t)VariableScale;
5521 if (Offset != NewOffs*(int64_t)VariableScale)
5522 return 0;
5523
5524 // Okay, we can do this evaluation. Start by converting the index to intptr.
5525 const Type *IntPtrTy = TD.getIntPtrType();
5526 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005527 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005528 true /*SExt*/,
5529 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005530 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005531 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005532}
5533
5534
Reid Spencere4d87aa2006-12-23 06:05:41 +00005535/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005536/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005537Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5538 ICmpInst::Predicate Cond,
5539 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005540 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005541
Chris Lattner10c0d912008-04-22 02:53:33 +00005542 // Look through bitcasts.
5543 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5544 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005545
Chris Lattner574da9b2005-01-13 20:14:25 +00005546 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005547 if (TD && PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005548 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005549 // This transformation (ignoring the base and scales) is valid because we
5550 // know pointers can't overflow. See if we can output an optimized form.
5551 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5552
5553 // If not, synthesize the offset the hard way.
5554 if (Offset == 0)
5555 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005556 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005557 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005558 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005559 // If the base pointers are different, but the indices are the same, just
5560 // compare the base pointer.
5561 if (PtrBase != GEPRHS->getOperand(0)) {
5562 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005563 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005564 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005565 if (IndicesTheSame)
5566 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5567 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5568 IndicesTheSame = false;
5569 break;
5570 }
5571
5572 // If all indices are the same, just compare the base pointers.
5573 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005574 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005575 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005576
5577 // Otherwise, the base pointers are different and the indices are
5578 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005579 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005580 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005581
Chris Lattnere9d782b2005-01-13 22:25:21 +00005582 // If one of the GEPs has all zero indices, recurse.
5583 bool AllZeros = true;
5584 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5585 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5586 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5587 AllZeros = false;
5588 break;
5589 }
5590 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005591 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5592 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005593
5594 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005595 AllZeros = true;
5596 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5597 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5598 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5599 AllZeros = false;
5600 break;
5601 }
5602 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005603 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005604
Chris Lattner4401c9c2005-01-14 00:20:05 +00005605 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5606 // If the GEPs only differ by one index, compare it.
5607 unsigned NumDifferences = 0; // Keep track of # differences.
5608 unsigned DiffOperand = 0; // The operand that differs.
5609 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5610 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005611 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5612 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005613 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005614 NumDifferences = 2;
5615 break;
5616 } else {
5617 if (NumDifferences++) break;
5618 DiffOperand = i;
5619 }
5620 }
5621
5622 if (NumDifferences == 0) // SAME GEP?
5623 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005624 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005625 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005626
Chris Lattner4401c9c2005-01-14 00:20:05 +00005627 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005628 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5629 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005630 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005631 return new ICmpInst(*Context,
5632 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005633 }
5634 }
5635
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005637 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005638 if (TD &&
5639 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005640 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5641 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5642 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5643 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005644 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005645 }
5646 }
5647 return 0;
5648}
5649
Chris Lattnera5406232008-05-19 20:18:56 +00005650/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5651///
5652Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5653 Instruction *LHSI,
5654 Constant *RHSC) {
5655 if (!isa<ConstantFP>(RHSC)) return 0;
5656 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5657
5658 // Get the width of the mantissa. We don't want to hack on conversions that
5659 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005660 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005661 if (MantissaWidth == -1) return 0; // Unknown.
5662
5663 // Check to see that the input is converted from an integer type that is small
5664 // enough that preserves all bits. TODO: check here for "known" sign bits.
5665 // 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 +00005666 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005667
5668 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005669 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5670 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005671 ++InputSize;
5672
5673 // If the conversion would lose info, don't hack on this.
5674 if ((int)InputSize > MantissaWidth)
5675 return 0;
5676
5677 // Otherwise, we can potentially simplify the comparison. We know that it
5678 // will always come through as an integer value and we know the constant is
5679 // not a NAN (it would have been previously simplified).
5680 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5681
5682 ICmpInst::Predicate Pred;
5683 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005684 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005685 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005686 case FCmpInst::FCMP_OEQ:
5687 Pred = ICmpInst::ICMP_EQ;
5688 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005689 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005690 case FCmpInst::FCMP_OGT:
5691 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5692 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005693 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005694 case FCmpInst::FCMP_OGE:
5695 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5696 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005697 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005698 case FCmpInst::FCMP_OLT:
5699 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5700 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005701 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005702 case FCmpInst::FCMP_OLE:
5703 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5704 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005705 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005706 case FCmpInst::FCMP_ONE:
5707 Pred = ICmpInst::ICMP_NE;
5708 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005709 case FCmpInst::FCMP_ORD:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005710 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005711 case FCmpInst::FCMP_UNO:
Owen Andersonb3056fa2009-07-21 18:03:38 +00005712 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005713 }
5714
5715 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5716
5717 // Now we know that the APFloat is a normal number, zero or inf.
5718
Chris Lattner85162782008-05-20 03:50:52 +00005719 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005720 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005721 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005722
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005723 if (!LHSUnsigned) {
5724 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5725 // and large values.
5726 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5727 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5728 APFloat::rmNearestTiesToEven);
5729 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5730 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5731 Pred == ICmpInst::ICMP_SLE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005732 return ReplaceInstUsesWith(I, Context->getTrue());
5733 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005734 }
5735 } else {
5736 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5737 // +INF and large values.
5738 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5739 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5740 APFloat::rmNearestTiesToEven);
5741 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5742 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5743 Pred == ICmpInst::ICMP_ULE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005744 return ReplaceInstUsesWith(I, Context->getTrue());
5745 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005746 }
Chris Lattnera5406232008-05-19 20:18:56 +00005747 }
5748
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005749 if (!LHSUnsigned) {
5750 // See if the RHS value is < SignedMin.
5751 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5752 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5753 APFloat::rmNearestTiesToEven);
5754 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5755 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5756 Pred == ICmpInst::ICMP_SGE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005757 return ReplaceInstUsesWith(I, Context->getTrue());
5758 return ReplaceInstUsesWith(I, Context->getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005759 }
Chris Lattnera5406232008-05-19 20:18:56 +00005760 }
5761
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005762 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5763 // [0, UMAX], but it may still be fractional. See if it is fractional by
5764 // casting the FP value to the integer value and back, checking for equality.
5765 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005766 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005767 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5768 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005769 if (!RHS.isZero()) {
5770 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005771 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5772 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005773 if (!Equal) {
5774 // If we had a comparison against a fractional value, we have to adjust
5775 // the compare predicate and sometimes the value. RHSC is rounded towards
5776 // zero at this point.
5777 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005778 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005779 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersonb3056fa2009-07-21 18:03:38 +00005780 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005781 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersonb3056fa2009-07-21 18:03:38 +00005782 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005783 case ICmpInst::ICMP_ULE:
5784 // (float)int <= 4.4 --> int <= 4
5785 // (float)int <= -4.4 --> false
5786 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005787 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005788 break;
5789 case ICmpInst::ICMP_SLE:
5790 // (float)int <= 4.4 --> int <= 4
5791 // (float)int <= -4.4 --> int < -4
5792 if (RHS.isNegative())
5793 Pred = ICmpInst::ICMP_SLT;
5794 break;
5795 case ICmpInst::ICMP_ULT:
5796 // (float)int < -4.4 --> false
5797 // (float)int < 4.4 --> int <= 4
5798 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005799 return ReplaceInstUsesWith(I, Context->getFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005800 Pred = ICmpInst::ICMP_ULE;
5801 break;
5802 case ICmpInst::ICMP_SLT:
5803 // (float)int < -4.4 --> int < -4
5804 // (float)int < 4.4 --> int <= 4
5805 if (!RHS.isNegative())
5806 Pred = ICmpInst::ICMP_SLE;
5807 break;
5808 case ICmpInst::ICMP_UGT:
5809 // (float)int > 4.4 --> int > 4
5810 // (float)int > -4.4 --> true
5811 if (RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005812 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005813 break;
5814 case ICmpInst::ICMP_SGT:
5815 // (float)int > 4.4 --> int > 4
5816 // (float)int > -4.4 --> int >= -4
5817 if (RHS.isNegative())
5818 Pred = ICmpInst::ICMP_SGE;
5819 break;
5820 case ICmpInst::ICMP_UGE:
5821 // (float)int >= -4.4 --> true
5822 // (float)int >= 4.4 --> int > 4
5823 if (!RHS.isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00005824 return ReplaceInstUsesWith(I, Context->getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005825 Pred = ICmpInst::ICMP_UGT;
5826 break;
5827 case ICmpInst::ICMP_SGE:
5828 // (float)int >= -4.4 --> int >= -4
5829 // (float)int >= 4.4 --> int > 4
5830 if (!RHS.isNegative())
5831 Pred = ICmpInst::ICMP_SGT;
5832 break;
5833 }
Chris Lattnera5406232008-05-19 20:18:56 +00005834 }
5835 }
5836
5837 // Lower this FP comparison into an appropriate integer version of the
5838 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005839 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005840}
5841
Reid Spencere4d87aa2006-12-23 06:05:41 +00005842Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5843 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005844 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005845
Chris Lattner58e97462007-01-14 19:42:17 +00005846 // Fold trivial predicates.
5847 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005848 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005849 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00005850 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005851
5852 // Simplify 'fcmp pred X, X'
5853 if (Op0 == Op1) {
5854 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005855 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005856 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5857 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5858 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005859 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005860 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5861 case FCmpInst::FCMP_OLT: // True if ordered and less than
5862 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersonb3056fa2009-07-21 18:03:38 +00005863 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005864
5865 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5866 case FCmpInst::FCMP_ULT: // True if unordered or less than
5867 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5868 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5869 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5870 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005871 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005872 return &I;
5873
5874 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5875 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5876 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5877 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5878 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5879 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005880 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005881 return &I;
5882 }
5883 }
5884
Reid Spencere4d87aa2006-12-23 06:05:41 +00005885 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005886 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005887
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888 // Handle fcmp with constant RHS
5889 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005890 // If the constant is a nan, see if we can fold the comparison based on it.
5891 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5892 if (CFP->getValueAPF().isNaN()) {
5893 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersonb3056fa2009-07-21 18:03:38 +00005894 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005895 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5896 "Comparison must be either ordered or unordered!");
5897 // True if unordered.
Owen Andersonb3056fa2009-07-21 18:03:38 +00005898 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005899 }
5900 }
5901
Reid Spencere4d87aa2006-12-23 06:05:41 +00005902 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5903 switch (LHSI->getOpcode()) {
5904 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005905 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5906 // block. If in the same block, we're encouraging jump threading. If
5907 // not, we are just pessimizing the code by making an i1 phi.
5908 if (LHSI->getParent() == I.getParent())
5909 if (Instruction *NV = FoldOpIntoPhi(I))
5910 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005911 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005912 case Instruction::SIToFP:
5913 case Instruction::UIToFP:
5914 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5915 return NV;
5916 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005917 case Instruction::Select:
5918 // If either operand of the select is a constant, we can fold the
5919 // comparison into the select arms, which will cause one to be
5920 // constant folded and the select turned into a bitwise or.
5921 Value *Op1 = 0, *Op2 = 0;
5922 if (LHSI->hasOneUse()) {
5923 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5924 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005925 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005926 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005927 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 LHSI->getOperand(2), RHSC,
5929 I.getName()), I);
5930 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5931 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005932 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005933 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005934 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005935 LHSI->getOperand(1), RHSC,
5936 I.getName()), I);
5937 }
5938 }
5939
5940 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005941 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005942 break;
5943 }
5944 }
5945
5946 return Changed ? &I : 0;
5947}
5948
5949Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5950 bool Changed = SimplifyCompare(I);
5951 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5952 const Type *Ty = Op0->getType();
5953
5954 // icmp X, X
5955 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005956 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005957 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005958
5959 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005960 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005961
Reid Spencere4d87aa2006-12-23 06:05:41 +00005962 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005963 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005964 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5965 isa<ConstantPointerNull>(Op0)) &&
5966 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005967 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005968 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005969 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005970
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005972 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005973 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005974 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005975 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005976 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005977 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00005978 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005979 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005980 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005981 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005982
Reid Spencere4d87aa2006-12-23 06:05:41 +00005983 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005984 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005985 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005986 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00005987 Instruction *Not = BinaryOperator::CreateNot(*Context,
5988 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005989 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005990 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005991 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005992 case ICmpInst::ICMP_SGT:
5993 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005994 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005995 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00005996 Instruction *Not = BinaryOperator::CreateNot(*Context,
5997 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005998 InsertNewInstBefore(Not, I);
5999 return BinaryOperator::CreateAnd(Not, Op0);
6000 }
6001 case ICmpInst::ICMP_UGE:
6002 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6003 // FALL THROUGH
6004 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006005 Instruction *Not = BinaryOperator::CreateNot(*Context,
6006 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006007 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006008 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006009 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006010 case ICmpInst::ICMP_SGE:
6011 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6012 // FALL THROUGH
6013 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006014 Instruction *Not = BinaryOperator::CreateNot(*Context,
6015 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006016 InsertNewInstBefore(Not, I);
6017 return BinaryOperator::CreateOr(Not, Op0);
6018 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006019 }
Chris Lattner8b170942002-08-09 23:47:40 +00006020 }
6021
Dan Gohman1c8491e2009-04-25 17:12:48 +00006022 unsigned BitWidth = 0;
6023 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006024 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6025 else if (Ty->isIntOrIntVector())
6026 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006027
6028 bool isSignBit = false;
6029
Dan Gohman81b28ce2008-09-16 18:46:06 +00006030 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006031 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006032 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006033
Chris Lattnerb6566012008-01-05 01:18:20 +00006034 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6035 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006036 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006037 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006038 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006039 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006040
Dan Gohman81b28ce2008-09-16 18:46:06 +00006041 // If we have an icmp le or icmp ge instruction, turn it into the
6042 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6043 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006044 switch (I.getPredicate()) {
6045 default: break;
6046 case ICmpInst::ICMP_ULE:
6047 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006048 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006049 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6050 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006051 case ICmpInst::ICMP_SLE:
6052 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006053 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006054 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6055 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006056 case ICmpInst::ICMP_UGE:
6057 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006058 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006059 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6060 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006061 case ICmpInst::ICMP_SGE:
6062 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersonb3056fa2009-07-21 18:03:38 +00006063 return ReplaceInstUsesWith(I, Context->getTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006064 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6065 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006066 }
6067
Chris Lattner183661e2008-07-11 05:40:05 +00006068 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006069 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006070 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006071 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6072 }
6073
6074 // See if we can fold the comparison based on range information we can get
6075 // by checking whether bits are known to be zero or one in the input.
6076 if (BitWidth != 0) {
6077 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6078 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6079
6080 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006081 isSignBit ? APInt::getSignBit(BitWidth)
6082 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006083 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006084 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006085 if (SimplifyDemandedBits(I.getOperandUse(1),
6086 APInt::getAllOnesValue(BitWidth),
6087 Op1KnownZero, Op1KnownOne, 0))
6088 return &I;
6089
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006090 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006091 // in. Compute the Min, Max and RHS values based on the known bits. For the
6092 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006093 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6094 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6095 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6096 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6097 Op0Min, Op0Max);
6098 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6099 Op1Min, Op1Max);
6100 } else {
6101 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6102 Op0Min, Op0Max);
6103 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6104 Op1Min, Op1Max);
6105 }
6106
Chris Lattner183661e2008-07-11 05:40:05 +00006107 // If Min and Max are known to be the same, then SimplifyDemandedBits
6108 // figured out that the LHS is a constant. Just constant fold this now so
6109 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006111 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006112 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006114 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006115 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116
Chris Lattner183661e2008-07-11 05:40:05 +00006117 // Based on the range information we know about the LHS, see if we can
6118 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006120 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006121 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006122 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006123 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006124 break;
6125 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersonb3056fa2009-07-21 18:03:38 +00006127 return ReplaceInstUsesWith(I, Context->getTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006128 break;
6129 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006131 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006133 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006134 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006135 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006136 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6137 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006138 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6139 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006140
6141 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6142 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006143 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006144 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 }
Chris Lattner84dff672008-07-11 05:08:55 +00006146 break;
6147 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006149 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006150 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006151 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152
6153 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006154 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006157 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6158 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159
6160 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6161 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006162 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006163 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 }
Chris Lattner84dff672008-07-11 05:08:55 +00006165 break;
6166 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006168 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006169 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006170 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006171 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006172 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006173 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6174 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006175 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6176 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 }
Chris Lattner84dff672008-07-11 05:08:55 +00006178 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006179 case ICmpInst::ICMP_SGT:
6180 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006181 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006183 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184
6185 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006186 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6188 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006189 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6190 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006191 }
6192 break;
6193 case ICmpInst::ICMP_SGE:
6194 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6195 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006196 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006198 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006199 break;
6200 case ICmpInst::ICMP_SLE:
6201 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6202 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006203 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006205 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006206 break;
6207 case ICmpInst::ICMP_UGE:
6208 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6209 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006210 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006212 return ReplaceInstUsesWith(I, Context->getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006213 break;
6214 case ICmpInst::ICMP_ULE:
6215 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6216 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006217 return ReplaceInstUsesWith(I, Context->getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006218 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006219 return ReplaceInstUsesWith(I, Context->getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006220 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006221 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006222
6223 // Turn a signed comparison into an unsigned one if both operands
6224 // are known to have the same sign.
6225 if (I.isSignedPredicate() &&
6226 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6227 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006228 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006229 }
6230
6231 // Test if the ICmpInst instruction is used exclusively by a select as
6232 // part of a minimum or maximum operation. If so, refrain from doing
6233 // any other folding. This helps out other analyses which understand
6234 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6235 // and CodeGen. And in this case, at least one of the comparison
6236 // operands has at least one user besides the compare (the select),
6237 // which would often largely negate the benefit of folding anyway.
6238 if (I.hasOneUse())
6239 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6240 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6241 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6242 return 0;
6243
6244 // See if we are doing a comparison between a constant and an instruction that
6245 // can be folded into the comparison.
6246 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006247 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006248 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006249 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006250 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006251 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6252 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006253 }
6254
Chris Lattner01deb9d2007-04-03 17:43:25 +00006255 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006256 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6257 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6258 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006259 case Instruction::GetElementPtr:
6260 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006261 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006262 bool isAllZeros = true;
6263 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6264 if (!isa<Constant>(LHSI->getOperand(i)) ||
6265 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6266 isAllZeros = false;
6267 break;
6268 }
6269 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006270 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006271 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006272 }
6273 break;
6274
Chris Lattner6970b662005-04-23 15:31:55 +00006275 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006276 // Only fold icmp into the PHI if the phi and fcmp are in the same
6277 // block. If in the same block, we're encouraging jump threading. If
6278 // not, we are just pessimizing the code by making an i1 phi.
6279 if (LHSI->getParent() == I.getParent())
6280 if (Instruction *NV = FoldOpIntoPhi(I))
6281 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006282 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006283 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006284 // If either operand of the select is a constant, we can fold the
6285 // comparison into the select arms, which will cause one to be
6286 // constant folded and the select turned into a bitwise or.
6287 Value *Op1 = 0, *Op2 = 0;
6288 if (LHSI->hasOneUse()) {
6289 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6290 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006291 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006292 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006293 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006294 LHSI->getOperand(2), RHSC,
6295 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006296 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6297 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006298 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006299 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006300 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 LHSI->getOperand(1), RHSC,
6302 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006303 }
6304 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006305
Chris Lattner6970b662005-04-23 15:31:55 +00006306 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006307 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006308 break;
6309 }
Chris Lattner4802d902007-04-06 18:57:34 +00006310 case Instruction::Malloc:
6311 // If we have (malloc != null), and if the malloc has a single use, we
6312 // can assume it is successful and remove the malloc.
6313 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6314 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006315 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006316 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006317 }
6318 break;
6319 }
Chris Lattner6970b662005-04-23 15:31:55 +00006320 }
6321
Reid Spencere4d87aa2006-12-23 06:05:41 +00006322 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006323 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006324 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006325 return NI;
6326 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006327 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6328 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006329 return NI;
6330
Reid Spencere4d87aa2006-12-23 06:05:41 +00006331 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006332 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6333 // now.
6334 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6335 if (isa<PointerType>(Op0->getType()) &&
6336 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006337 // We keep moving the cast from the left operand over to the right
6338 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006339 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006340
Chris Lattner57d86372007-01-06 01:45:59 +00006341 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6342 // so eliminate it as well.
6343 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6344 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006345
Chris Lattnerde90b762003-11-03 04:25:02 +00006346 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006347 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006348 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006349 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006350 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006351 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006352 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006353 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006354 }
Owen Anderson333c4002009-07-09 23:48:35 +00006355 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006356 }
Chris Lattner57d86372007-01-06 01:45:59 +00006357 }
6358
6359 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006360 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006361 // This comes up when you have code like
6362 // int X = A < B;
6363 // if (X) ...
6364 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006365 // with a constant or another cast from the same type.
6366 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006367 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006368 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006369 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006370
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006371 // See if it's the same type of instruction on the left and right.
6372 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6373 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006374 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006375 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006376 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006377 default: break;
6378 case Instruction::Add:
6379 case Instruction::Sub:
6380 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006381 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006382 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006383 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006384 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6385 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6386 if (CI->getValue().isSignBit()) {
6387 ICmpInst::Predicate Pred = I.isSignedPredicate()
6388 ? I.getUnsignedPredicate()
6389 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006390 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006391 Op1I->getOperand(0));
6392 }
6393
6394 if (CI->getValue().isMaxSignedValue()) {
6395 ICmpInst::Predicate Pred = I.isSignedPredicate()
6396 ? I.getUnsignedPredicate()
6397 : I.getSignedPredicate();
6398 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006399 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006400 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006401 }
6402 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006403 break;
6404 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006405 if (!I.isEquality())
6406 break;
6407
Nick Lewycky5d52c452008-08-21 05:56:10 +00006408 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6409 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6410 // Mask = -1 >> count-trailing-zeros(Cst).
6411 if (!CI->isZero() && !CI->isOne()) {
6412 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006413 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006414 APInt::getLowBitsSet(AP.getBitWidth(),
6415 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006416 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006417 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6418 Mask);
6419 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6420 Mask);
6421 InsertNewInstBefore(And1, I);
6422 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006423 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006424 }
6425 }
6426 break;
6427 }
6428 }
6429 }
6430 }
6431
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006432 // ~x < ~y --> y < x
6433 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006434 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6435 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006436 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006437 }
6438
Chris Lattner65b72ba2006-09-18 04:22:48 +00006439 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006440 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006441
6442 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006443 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6444 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006445 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006446
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006447 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006448 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6449 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006450 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006451 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006452 }
6453
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006454 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006455 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006456 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006457 if (match(B, m_ConstantInt(C1), *Context) &&
6458 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006459 Constant *NC =
6460 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006461 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006462 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006463 InsertNewInstBefore(Xor, I));
6464 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006465
6466 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006467 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6468 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6469 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6470 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006471 }
6472 }
6473
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006474 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006475 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006476 // A == (A^B) -> B == 0
6477 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006478 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006479 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006480 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006481
6482 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006483 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006484 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006485 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006486
6487 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006488 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006489 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006490 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006491
Chris Lattner9c2328e2006-11-14 06:06:06 +00006492 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6493 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006494 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6495 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006496 Value *X = 0, *Y = 0, *Z = 0;
6497
6498 if (A == C) {
6499 X = B; Y = D; Z = A;
6500 } else if (A == D) {
6501 X = B; Y = C; Z = A;
6502 } else if (B == C) {
6503 X = A; Y = D; Z = B;
6504 } else if (B == D) {
6505 X = A; Y = C; Z = B;
6506 }
6507
6508 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006509 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6510 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006511 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006512 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006513 return &I;
6514 }
6515 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006516 }
Chris Lattner7e708292002-06-25 16:13:24 +00006517 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006518}
6519
Chris Lattner562ef782007-06-20 23:46:26 +00006520
6521/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6522/// and CmpRHS are both known to be integer constants.
6523Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6524 ConstantInt *DivRHS) {
6525 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6526 const APInt &CmpRHSV = CmpRHS->getValue();
6527
6528 // FIXME: If the operand types don't match the type of the divide
6529 // then don't attempt this transform. The code below doesn't have the
6530 // logic to deal with a signed divide and an unsigned compare (and
6531 // vice versa). This is because (x /s C1) <s C2 produces different
6532 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6533 // (x /u C1) <u C2. Simply casting the operands and result won't
6534 // work. :( The if statement below tests that condition and bails
6535 // if it finds it.
6536 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6537 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6538 return 0;
6539 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006540 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006541 if (DivIsSigned && DivRHS->isAllOnesValue())
6542 return 0; // The overflow computation also screws up here
6543 if (DivRHS->isOne())
6544 return 0; // Not worth bothering, and eliminates some funny cases
6545 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006546
6547 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6548 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6549 // C2 (CI). By solving for X we can turn this into a range check
6550 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006551 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006552
6553 // Determine if the product overflows by seeing if the product is
6554 // not equal to the divide. Make sure we do the same kind of divide
6555 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006556 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6557 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006558
6559 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006560 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006561
Chris Lattner1dbfd482007-06-21 18:11:19 +00006562 // Figure out the interval that is being checked. For example, a comparison
6563 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6564 // Compute this interval based on the constants involved and the signedness of
6565 // the compare/divide. This computes a half-open interval, keeping track of
6566 // whether either value in the interval overflows. After analysis each
6567 // overflow variable is set to 0 if it's corresponding bound variable is valid
6568 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6569 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006570 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006571
Chris Lattner562ef782007-06-20 23:46:26 +00006572 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006574 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006575 HiOverflow = LoOverflow = ProdOV;
6576 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006577 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006578 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006579 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006580 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006581 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6582 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006583 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006584 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006585 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6586 HiOverflow = LoOverflow = ProdOV;
6587 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006588 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006589 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006590 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006591 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006592 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6593 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006594 ConstantInt* DivNeg =
6595 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6596 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006597 true) ? -1 : 0;
6598 }
Chris Lattner562ef782007-06-20 23:46:26 +00006599 }
Dan Gohman76491272008-02-13 22:09:18 +00006600 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006601 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006602 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006603 LoBound = AddOne(DivRHS, Context);
6604 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6606 HiOverflow = 1; // [INTMIN+1, overflow)
6607 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6608 }
Dan Gohman76491272008-02-13 22:09:18 +00006609 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006610 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006611 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006612 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006613 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006614 LoOverflow = AddWithOverflow(LoBound, HiBound,
6615 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006616 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006617 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6618 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006619 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006620 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006621 }
6622
Chris Lattner1dbfd482007-06-21 18:11:19 +00006623 // Dividing by a negative swaps the condition. LT <-> GT
6624 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006625 }
6626
6627 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006628 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006629 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006630 case ICmpInst::ICMP_EQ:
6631 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006632 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006633 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006634 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006635 ICmpInst::ICMP_UGE, X, LoBound);
6636 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006637 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006638 ICmpInst::ICMP_ULT, X, HiBound);
6639 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006640 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006641 case ICmpInst::ICMP_NE:
6642 if (LoOverflow && HiOverflow)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006643 return ReplaceInstUsesWith(ICI, Context->getTrue());
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_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006646 ICmpInst::ICMP_ULT, X, LoBound);
6647 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006648 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006649 ICmpInst::ICMP_UGE, X, HiBound);
6650 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006651 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006652 case ICmpInst::ICMP_ULT:
6653 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006654 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006655 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006656 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006657 return ReplaceInstUsesWith(ICI, Context->getFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006658 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006659 case ICmpInst::ICMP_UGT:
6660 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006661 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006662 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006663 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersonb3056fa2009-07-21 18:03:38 +00006664 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006665 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006666 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006667 else
Owen Anderson333c4002009-07-09 23:48:35 +00006668 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006669 }
6670}
6671
6672
Chris Lattner01deb9d2007-04-03 17:43:25 +00006673/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6674///
6675Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6676 Instruction *LHSI,
6677 ConstantInt *RHS) {
6678 const APInt &RHSV = RHS->getValue();
6679
6680 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006681 case Instruction::Trunc:
6682 if (ICI.isEquality() && LHSI->hasOneUse()) {
6683 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6684 // of the high bits truncated out of x are known.
6685 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6686 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6687 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6688 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6689 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6690
6691 // If all the high bits are known, we can do this xform.
6692 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6693 // Pull in the high bits from known-ones set.
6694 APInt NewRHS(RHS->getValue());
6695 NewRHS.zext(SrcBits);
6696 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006697 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006698 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006699 }
6700 }
6701 break;
6702
Duncan Sands0091bf22007-04-04 06:42:45 +00006703 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006704 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6705 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6706 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006707 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6708 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006709 Value *CompareVal = LHSI->getOperand(0);
6710
6711 // If the sign bit of the XorCST is not set, there is no change to
6712 // the operation, just stop using the Xor.
6713 if (!XorCST->getValue().isNegative()) {
6714 ICI.setOperand(0, CompareVal);
6715 AddToWorkList(LHSI);
6716 return &ICI;
6717 }
6718
6719 // Was the old condition true if the operand is positive?
6720 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6721
6722 // If so, the new one isn't.
6723 isTrueIfPositive ^= true;
6724
6725 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006726 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006727 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006728 else
Owen Anderson333c4002009-07-09 23:48:35 +00006729 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006730 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006731 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006732
6733 if (LHSI->hasOneUse()) {
6734 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6735 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6736 const APInt &SignBit = XorCST->getValue();
6737 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6738 ? ICI.getUnsignedPredicate()
6739 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006740 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006741 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006742 }
6743
6744 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006745 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006746 const APInt &NotSignBit = XorCST->getValue();
6747 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6748 ? ICI.getUnsignedPredicate()
6749 : ICI.getSignedPredicate();
6750 Pred = ICI.getSwappedPredicate(Pred);
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 ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006753 }
6754 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006755 }
6756 break;
6757 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6758 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6759 LHSI->getOperand(0)->hasOneUse()) {
6760 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6761
6762 // If the LHS is an AND of a truncating cast, we can widen the
6763 // and/compare to be the input width without changing the value
6764 // produced, eliminating a cast.
6765 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6766 // We can do this transformation if either the AND constant does not
6767 // have its sign bit set or if it is an equality comparison.
6768 // Extending a relational comparison when we're checking the sign
6769 // bit would not work.
6770 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006771 (ICI.isEquality() ||
6772 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006773 uint32_t BitWidth =
6774 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6775 APInt NewCST = AndCST->getValue();
6776 NewCST.zext(BitWidth);
6777 APInt NewCI = RHSV;
6778 NewCI.zext(BitWidth);
6779 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006780 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006781 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006782 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006783 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006784 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006785 }
6786 }
6787
6788 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6789 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6790 // happens a LOT in code produced by the C front-end, for bitfield
6791 // access.
6792 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6793 if (Shift && !Shift->isShift())
6794 Shift = 0;
6795
6796 ConstantInt *ShAmt;
6797 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6798 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6799 const Type *AndTy = AndCST->getType(); // Type of the and.
6800
6801 // We can fold this as long as we can't shift unknown bits
6802 // into the mask. This can only happen with signed shift
6803 // rights, as they sign-extend.
6804 if (ShAmt) {
6805 bool CanFold = Shift->isLogicalShift();
6806 if (!CanFold) {
6807 // To test for the bad case of the signed shr, see if any
6808 // of the bits shifted in could be tested after the mask.
6809 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6810 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6811
6812 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6813 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6814 AndCST->getValue()) == 0)
6815 CanFold = true;
6816 }
6817
6818 if (CanFold) {
6819 Constant *NewCst;
6820 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006821 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006822 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006823 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006824
6825 // Check to see if we are shifting out any of the bits being
6826 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006827 if (Context->getConstantExpr(Shift->getOpcode(),
6828 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006829 // If we shifted bits out, the fold is not going to work out.
6830 // As a special case, check to see if this means that the
6831 // result is always true or false now.
6832 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006833 return ReplaceInstUsesWith(ICI, Context->getFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006834 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00006835 return ReplaceInstUsesWith(ICI, Context->getTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006836 } else {
6837 ICI.setOperand(1, NewCst);
6838 Constant *NewAndCST;
6839 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006840 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006841 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006842 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843 LHSI->setOperand(1, NewAndCST);
6844 LHSI->setOperand(0, Shift->getOperand(0));
6845 AddToWorkList(Shift); // Shift is dead.
6846 AddUsesToWorkList(ICI);
6847 return &ICI;
6848 }
6849 }
6850 }
6851
6852 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6853 // preferable because it allows the C<<Y expression to be hoisted out
6854 // of a loop if Y is invariant and X is not.
6855 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006856 ICI.isEquality() && !Shift->isArithmeticShift() &&
6857 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858 // Compute C << Y.
6859 Value *NS;
6860 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006861 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006862 Shift->getOperand(1), "tmp");
6863 } else {
6864 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006865 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006866 Shift->getOperand(1), "tmp");
6867 }
6868 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6869
6870 // Compute X & (C << Y).
6871 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006872 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006873 InsertNewInstBefore(NewAnd, ICI);
6874
6875 ICI.setOperand(0, NewAnd);
6876 return &ICI;
6877 }
6878 }
6879 break;
6880
Chris Lattnera0141b92007-07-15 20:42:37 +00006881 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6882 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6883 if (!ShAmt) break;
6884
6885 uint32_t TypeBits = RHSV.getBitWidth();
6886
6887 // Check that the shift amount is in range. If not, don't perform
6888 // undefined shifts. When the shift is visited it will be
6889 // simplified.
6890 if (ShAmt->uge(TypeBits))
6891 break;
6892
6893 if (ICI.isEquality()) {
6894 // If we are comparing against bits always shifted out, the
6895 // comparison cannot succeed.
6896 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006897 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6898 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006899 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6900 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006901 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006902 return ReplaceInstUsesWith(ICI, Cst);
6903 }
6904
6905 if (LHSI->hasOneUse()) {
6906 // Otherwise strength reduce the shift into an and.
6907 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6908 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006909 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6910 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006911
Chris Lattnera0141b92007-07-15 20:42:37 +00006912 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006913 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006914 Mask, LHSI->getName()+".mask");
6915 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006916 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006917 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006918 }
6919 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006920
6921 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6922 bool TrueIfSigned = false;
6923 if (LHSI->hasOneUse() &&
6924 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6925 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006926 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006927 (TypeBits-ShAmt->getZExtValue()-1));
6928 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006929 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006930 Mask, LHSI->getName()+".mask");
6931 Value *And = InsertNewInstBefore(AndI, ICI);
6932
Owen Anderson333c4002009-07-09 23:48:35 +00006933 return new ICmpInst(*Context,
6934 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006935 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006936 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006937 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006938 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006939
6940 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006942 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006943 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006944 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006945
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006946 // Check that the shift amount is in range. If not, don't perform
6947 // undefined shifts. When the shift is visited it will be
6948 // simplified.
6949 uint32_t TypeBits = RHSV.getBitWidth();
6950 if (ShAmt->uge(TypeBits))
6951 break;
6952
6953 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006954
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006955 // If we are comparing against bits always shifted out, the
6956 // comparison cannot succeed.
6957 APInt Comp = RHSV << ShAmtVal;
6958 if (LHSI->getOpcode() == Instruction::LShr)
6959 Comp = Comp.lshr(ShAmtVal);
6960 else
6961 Comp = Comp.ashr(ShAmtVal);
6962
6963 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6964 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006965 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006966 return ReplaceInstUsesWith(ICI, Cst);
6967 }
6968
6969 // Otherwise, check to see if the bits shifted out are known to be zero.
6970 // If so, we can compare against the unshifted value:
6971 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006972 if (LHSI->hasOneUse() &&
6973 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006974 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00006975 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006976 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006977 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006978
Evan Chengf30752c2008-04-23 00:38:06 +00006979 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006980 // Otherwise strength reduce the shift into an and.
6981 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00006982 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006983
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006984 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006985 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006986 Mask, LHSI->getName()+".mask");
6987 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006988 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006989 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006990 }
6991 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006992 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006993
6994 case Instruction::SDiv:
6995 case Instruction::UDiv:
6996 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6997 // Fold this div into the comparison, producing a range check.
6998 // Determine, based on the divide type, what the range is being
6999 // checked. If there is an overflow on the low or high side, remember
7000 // it, otherwise compute the range [low, hi) bounding the new value.
7001 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007002 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7003 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7004 DivRHS))
7005 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007006 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007007
7008 case Instruction::Add:
7009 // Fold: icmp pred (add, X, C1), C2
7010
7011 if (!ICI.isEquality()) {
7012 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7013 if (!LHSC) break;
7014 const APInt &LHSV = LHSC->getValue();
7015
7016 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7017 .subtract(LHSV);
7018
7019 if (ICI.isSignedPredicate()) {
7020 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007021 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007022 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007023 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007024 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007025 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007026 }
7027 } else {
7028 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007029 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007030 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007031 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007032 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007033 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007034 }
7035 }
7036 }
7037 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038 }
7039
7040 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7041 if (ICI.isEquality()) {
7042 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7043
7044 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7045 // the second operand is a constant, simplify a bit.
7046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7047 switch (BO->getOpcode()) {
7048 case Instruction::SRem:
7049 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7050 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7051 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7052 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7053 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007054 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007055 BO->getName());
7056 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007057 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007058 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007059 }
7060 }
7061 break;
7062 case Instruction::Add:
7063 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7064 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7065 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007066 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007067 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 } else if (RHSV == 0) {
7069 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7070 // efficiently invertible, or if the add has just this one use.
7071 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7072
Owen Andersond672ecb2009-07-03 00:17:18 +00007073 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007074 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007075 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007076 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007078 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007079 InsertNewInstBefore(Neg, ICI);
7080 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007081 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007082 }
7083 }
7084 break;
7085 case Instruction::Xor:
7086 // For the xor case, we can xor two constants together, eliminating
7087 // the explicit xor.
7088 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007089 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007090 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007091
7092 // FALLTHROUGH
7093 case Instruction::Sub:
7094 // Replace (([sub|xor] A, B) != 0) with (A != B)
7095 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007096 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007097 BO->getOperand(1));
7098 break;
7099
7100 case Instruction::Or:
7101 // If bits are being or'd in that are not present in the constant we
7102 // are comparing against, then the comparison could never succeed!
7103 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007104 Constant *NotCI = Context->getConstantExprNot(RHS);
7105 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7106 return ReplaceInstUsesWith(ICI,
7107 Context->getConstantInt(Type::Int1Ty,
7108 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109 }
7110 break;
7111
7112 case Instruction::And:
7113 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7114 // If bits are being compared against that are and'd out, then the
7115 // comparison can never succeed!
7116 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007117 return ReplaceInstUsesWith(ICI,
7118 Context->getConstantInt(Type::Int1Ty,
7119 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007120
7121 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7122 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007123 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007124 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007125 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007126
7127 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007128 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007129 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007130 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007131 ICmpInst::Predicate pred = isICMP_NE ?
7132 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007133 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007134 }
7135
7136 // ((X & ~7) == 0) --> X < 8
7137 if (RHSV == 0 && isHighOnes(BOC)) {
7138 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007139 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007140 ICmpInst::Predicate pred = isICMP_NE ?
7141 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007142 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007143 }
7144 }
7145 default: break;
7146 }
7147 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7148 // Handle icmp {eq|ne} <intrinsic>, intcst.
7149 if (II->getIntrinsicID() == Intrinsic::bswap) {
7150 AddToWorkList(II);
7151 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007152 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153 return &ICI;
7154 }
7155 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156 }
7157 return 0;
7158}
7159
7160/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7161/// We only handle extending casts so far.
7162///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007163Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7164 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007165 Value *LHSCIOp = LHSCI->getOperand(0);
7166 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007167 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007168 Value *RHSCIOp;
7169
Chris Lattner8c756c12007-05-05 22:41:33 +00007170 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7171 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007172 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7173 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007174 cast<IntegerType>(DestTy)->getBitWidth()) {
7175 Value *RHSOp = 0;
7176 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007177 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007178 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7179 RHSOp = RHSC->getOperand(0);
7180 // If the pointer types don't match, insert a bitcast.
7181 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007182 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007183 }
7184
7185 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007186 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007187 }
7188
7189 // The code below only handles extension cast instructions, so far.
7190 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007191 if (LHSCI->getOpcode() != Instruction::ZExt &&
7192 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007193 return 0;
7194
Reid Spencere4d87aa2006-12-23 06:05:41 +00007195 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7196 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007197
Reid Spencere4d87aa2006-12-23 06:05:41 +00007198 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007199 // Not an extension from the same type?
7200 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007201 if (RHSCIOp->getType() != LHSCIOp->getType())
7202 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007203
Nick Lewycky4189a532008-01-28 03:48:02 +00007204 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007205 // and the other is a zext), then we can't handle this.
7206 if (CI->getOpcode() != LHSCI->getOpcode())
7207 return 0;
7208
Nick Lewycky4189a532008-01-28 03:48:02 +00007209 // Deal with equality cases early.
7210 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007211 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007212
7213 // A signed comparison of sign extended values simplifies into a
7214 // signed comparison.
7215 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007216 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007217
7218 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007219 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007220 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007221
Reid Spencere4d87aa2006-12-23 06:05:41 +00007222 // If we aren't dealing with a constant on the RHS, exit early
7223 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7224 if (!CI)
7225 return 0;
7226
7227 // Compute the constant that would happen if we truncated to SrcTy then
7228 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007229 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7230 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7231 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007232
7233 // If the re-extended constant didn't change...
7234 if (Res2 == CI) {
7235 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7236 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007237 // %A = sext i16 %X to i32
7238 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007239 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007240 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007241 // because %A may have negative value.
7242 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007243 // However, we allow this when the compare is EQ/NE, because they are
7244 // signless.
7245 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007246 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007247 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007248 }
7249
7250 // The re-extended constant changed so the constant cannot be represented
7251 // in the shorter type. Consequently, we cannot emit a simple comparison.
7252
7253 // First, handle some easy cases. We know the result cannot be equal at this
7254 // point so handle the ICI.isEquality() cases
7255 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007256 return ReplaceInstUsesWith(ICI, Context->getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007257 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersonb3056fa2009-07-21 18:03:38 +00007258 return ReplaceInstUsesWith(ICI, Context->getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007259
7260 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7261 // should have been folded away previously and not enter in here.
7262 Value *Result;
7263 if (isSignedCmp) {
7264 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007265 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersonb3056fa2009-07-21 18:03:38 +00007266 Result = Context->getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 else
Owen Andersonb3056fa2009-07-21 18:03:38 +00007268 Result = Context->getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007269 } else {
7270 // We're performing an unsigned comparison.
7271 if (isSignedExt) {
7272 // We're performing an unsigned comp with a sign extended value.
7273 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007274 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007275 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7276 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007277 } else {
7278 // Unsigned extend & unsigned compare -> always true.
Owen Andersonb3056fa2009-07-21 18:03:38 +00007279 Result = Context->getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007280 }
7281 }
7282
7283 // Finally, return the value computed.
7284 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007285 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007287
7288 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7289 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7290 "ICmp should be folded!");
7291 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007292 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007293 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007294}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007295
Reid Spencer832254e2007-02-02 02:16:23 +00007296Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7297 return commonShiftTransforms(I);
7298}
7299
7300Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7301 return commonShiftTransforms(I);
7302}
7303
7304Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007305 if (Instruction *R = commonShiftTransforms(I))
7306 return R;
7307
7308 Value *Op0 = I.getOperand(0);
7309
7310 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7311 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7312 if (CSI->isAllOnesValue())
7313 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007314
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007315 // See if we can turn a signed shr into an unsigned shr.
7316 if (MaskedValueIsZero(Op0,
7317 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7318 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7319
7320 // Arithmetic shifting an all-sign-bit value is a no-op.
7321 unsigned NumSignBits = ComputeNumSignBits(Op0);
7322 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7323 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007324
Chris Lattner348f6652007-12-06 01:59:46 +00007325 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007326}
7327
7328Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7329 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007330 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007331
7332 // shl X, 0 == X and shr X, 0 == X
7333 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007334 if (Op1 == Context->getNullValue(Op1->getType()) ||
7335 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007336 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007337
Reid Spencere4d87aa2006-12-23 06:05:41 +00007338 if (isa<UndefValue>(Op0)) {
7339 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007340 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007341 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007342 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007343 }
7344 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007345 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7346 return ReplaceInstUsesWith(I, Op0);
7347 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007348 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007349 }
7350
Dan Gohman9004c8a2009-05-21 02:28:33 +00007351 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007352 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007353 return &I;
7354
Chris Lattner2eefe512004-04-09 19:05:30 +00007355 // Try to fold constant and into select arguments.
7356 if (isa<Constant>(Op0))
7357 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007358 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007359 return R;
7360
Reid Spencerb83eb642006-10-20 07:07:24 +00007361 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007362 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7363 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007364 return 0;
7365}
7366
Reid Spencerb83eb642006-10-20 07:07:24 +00007367Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007368 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007369 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007370
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007371 // See if we can simplify any instructions used by the instruction whose sole
7372 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007373 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007374
Dan Gohmana119de82009-06-14 23:30:43 +00007375 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7376 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007377 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007378 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007379 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007380 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007381 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007382 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007383 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007384 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007385 }
7386
7387 // ((X*C1) << C2) == (X * (C1 << C2))
7388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7389 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7390 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007391 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007392 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007393
7394 // Try to fold constant and into select arguments.
7395 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7397 return R;
7398 if (isa<PHINode>(Op0))
7399 if (Instruction *NV = FoldOpIntoPhi(I))
7400 return NV;
7401
Chris Lattner8999dd32007-12-22 09:07:47 +00007402 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7403 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7404 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7405 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7406 // place. Don't try to do this transformation in this case. Also, we
7407 // require that the input operand is a shift-by-constant so that we have
7408 // confidence that the shifts will get folded together. We could do this
7409 // xform in more cases, but it is unlikely to be profitable.
7410 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7411 isa<ConstantInt>(TrOp->getOperand(1))) {
7412 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007413 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007414 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007415 I.getName());
7416 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7417
7418 // For logical shifts, the truncation has the effect of making the high
7419 // part of the register be zeros. Emulate this by inserting an AND to
7420 // clear the top bits as needed. This 'and' will usually be zapped by
7421 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007422 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7423 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007424 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7425
7426 // The mask we constructed says what the trunc would do if occurring
7427 // between the shifts. We want to know the effect *after* the second
7428 // shift. We know that it is a logical shift by a constant, so adjust the
7429 // mask as appropriate.
7430 if (I.getOpcode() == Instruction::Shl)
7431 MaskV <<= Op1->getZExtValue();
7432 else {
7433 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7434 MaskV = MaskV.lshr(Op1->getZExtValue());
7435 }
7436
Owen Andersond672ecb2009-07-03 00:17:18 +00007437 Instruction *And =
7438 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7439 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007440 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7441
7442 // Return the value truncated to the interesting size.
7443 return new TruncInst(And, I.getType());
7444 }
7445 }
7446
Chris Lattner4d5542c2006-01-06 07:12:35 +00007447 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007448 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7449 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7450 Value *V1, *V2;
7451 ConstantInt *CC;
7452 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007453 default: break;
7454 case Instruction::Add:
7455 case Instruction::And:
7456 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007457 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007458 // These operators commute.
7459 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007460 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007461 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7462 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007463 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007464 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007465 Op0BO->getName());
7466 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007467 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007468 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007469 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007470 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007471 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007472 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007473 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007474 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007475
Chris Lattner150f12a2005-09-18 06:30:59 +00007476 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007477 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007478 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007479 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007480 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007481 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007482 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007483 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007484 Op0BO->getOperand(0), Op1,
7485 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007486 InsertNewInstBefore(YS, I); // (Y << C)
7487 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007488 BinaryOperator::CreateAnd(V1,
7489 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007490 V1->getName()+".mask");
7491 InsertNewInstBefore(XM, I); // X & (CC << C)
7492
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007493 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007494 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007495 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007496
Reid Spencera07cb7d2007-02-02 14:41:37 +00007497 // FALL THROUGH.
7498 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007499 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007500 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007501 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7502 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007503 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007504 Op0BO->getOperand(1), Op1,
7505 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007506 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007507 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007508 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007509 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007510 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007511 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007512 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007513 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007514 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007515
Chris Lattner13d4ab42006-05-31 21:14:00 +00007516 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007517 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7518 match(Op0BO->getOperand(0),
7519 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007520 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007521 cast<BinaryOperator>(Op0BO->getOperand(0))
7522 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007523 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007524 Op0BO->getOperand(1), Op1,
7525 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007526 InsertNewInstBefore(YS, I); // (Y << C)
7527 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007528 BinaryOperator::CreateAnd(V1,
7529 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007530 V1->getName()+".mask");
7531 InsertNewInstBefore(XM, I); // X & (CC << C)
7532
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007533 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007534 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007535
Chris Lattner11021cb2005-09-18 05:12:10 +00007536 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007537 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007538 }
7539
7540
7541 // If the operand is an bitwise operator with a constant RHS, and the
7542 // shift is the only use, we can pull it out of the shift.
7543 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7544 bool isValid = true; // Valid only for And, Or, Xor
7545 bool highBitSet = false; // Transform if high bit of constant set?
7546
7547 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007548 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007549 case Instruction::Add:
7550 isValid = isLeftShift;
7551 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007552 case Instruction::Or:
7553 case Instruction::Xor:
7554 highBitSet = false;
7555 break;
7556 case Instruction::And:
7557 highBitSet = true;
7558 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007559 }
7560
7561 // If this is a signed shift right, and the high bit is modified
7562 // by the logical operation, do not perform the transformation.
7563 // The highBitSet boolean indicates the value of the high bit of
7564 // the constant which would cause it to be modified for this
7565 // operation.
7566 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007567 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007568 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007569
7570 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007571 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007572
7573 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007574 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007575 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007576 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007577
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007578 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007579 NewRHS);
7580 }
7581 }
7582 }
7583 }
7584
Chris Lattnerad0124c2006-01-06 07:52:12 +00007585 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007586 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7587 if (ShiftOp && !ShiftOp->isShift())
7588 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007589
Reid Spencerb83eb642006-10-20 07:07:24 +00007590 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007591 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007592 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7593 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007594 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7595 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7596 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007597
Zhou Sheng4351c642007-04-02 08:20:41 +00007598 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007599
7600 const IntegerType *Ty = cast<IntegerType>(I.getType());
7601
7602 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007603 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007604 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7605 // saturates.
7606 if (AmtSum >= TypeBits) {
7607 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007608 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007609 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7610 }
7611
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007612 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007613 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007614 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7615 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007616 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007617 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007618
Chris Lattnerb87056f2007-02-05 00:57:54 +00007619 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007620 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007621 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7622 I.getOpcode() == Instruction::LShr) {
7623 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007624 if (AmtSum >= TypeBits)
7625 AmtSum = TypeBits-1;
7626
Chris Lattnerb87056f2007-02-05 00:57:54 +00007627 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007628 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007629 InsertNewInstBefore(Shift, I);
7630
Zhou Shenge9e03f62007-03-28 15:02:20 +00007631 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007632 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007633 }
7634
Chris Lattnerb87056f2007-02-05 00:57:54 +00007635 // Okay, if we get here, one shift must be left, and the other shift must be
7636 // right. See if the amounts are equal.
7637 if (ShiftAmt1 == ShiftAmt2) {
7638 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7639 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007640 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007641 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007642 }
7643 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7644 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007645 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007646 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007647 }
7648 // We can simplify ((X << C) >>s C) into a trunc + sext.
7649 // NOTE: we could do this for any C, but that would make 'unusual' integer
7650 // types. For now, just stick to ones well-supported by the code
7651 // generators.
7652 const Type *SExtType = 0;
7653 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007654 case 1 :
7655 case 8 :
7656 case 16 :
7657 case 32 :
7658 case 64 :
7659 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007660 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007661 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007662 default: break;
7663 }
7664 if (SExtType) {
7665 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7666 InsertNewInstBefore(NewTrunc, I);
7667 return new SExtInst(NewTrunc, Ty);
7668 }
7669 // Otherwise, we can't handle it yet.
7670 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007671 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007672
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007673 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007674 if (I.getOpcode() == Instruction::Shl) {
7675 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7676 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007677 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007678 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007679 InsertNewInstBefore(Shift, I);
7680
Reid Spencer55702aa2007-03-25 21:11:44 +00007681 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007682 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007683 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007684
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007685 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007686 if (I.getOpcode() == Instruction::LShr) {
7687 assert(ShiftOp->getOpcode() == Instruction::Shl);
7688 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007689 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007690 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007691
Reid Spencerd5e30f02007-03-26 17:18:58 +00007692 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007693 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007694 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007695
7696 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7697 } else {
7698 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007699 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007700
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007701 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007702 if (I.getOpcode() == Instruction::Shl) {
7703 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7704 ShiftOp->getOpcode() == Instruction::AShr);
7705 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007706 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007707 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007708 InsertNewInstBefore(Shift, I);
7709
Reid Spencer55702aa2007-03-25 21:11:44 +00007710 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007711 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007712 }
7713
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007714 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007715 if (I.getOpcode() == Instruction::LShr) {
7716 assert(ShiftOp->getOpcode() == Instruction::Shl);
7717 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007718 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007719 InsertNewInstBefore(Shift, I);
7720
Reid Spencer68d27cf2007-03-26 23:45:51 +00007721 APInt Mask(APInt::getLowBitsSet(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
7725 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007726 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007727 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007728 return 0;
7729}
7730
Chris Lattnera1be5662002-05-02 17:06:02 +00007731
Chris Lattnercfd65102005-10-29 04:36:15 +00007732/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7733/// expression. If so, decompose it, returning some value X, such that Val is
7734/// X*Scale+Offset.
7735///
7736static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007737 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007738 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007739 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007740 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007741 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007742 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007743 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7744 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7745 if (I->getOpcode() == Instruction::Shl) {
7746 // This is a value scaled by '1 << the shift amt'.
7747 Scale = 1U << RHS->getZExtValue();
7748 Offset = 0;
7749 return I->getOperand(0);
7750 } else if (I->getOpcode() == Instruction::Mul) {
7751 // This value is scaled by 'RHS'.
7752 Scale = RHS->getZExtValue();
7753 Offset = 0;
7754 return I->getOperand(0);
7755 } else if (I->getOpcode() == Instruction::Add) {
7756 // We have X+C. Check to see if we really have (X*C2)+C1,
7757 // where C1 is divisible by C2.
7758 unsigned SubScale;
7759 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007760 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7761 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007762 Offset += RHS->getZExtValue();
7763 Scale = SubScale;
7764 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007765 }
7766 }
7767 }
7768
7769 // Otherwise, we can't look past this.
7770 Scale = 1;
7771 Offset = 0;
7772 return Val;
7773}
7774
7775
Chris Lattnerb3f83972005-10-24 06:03:58 +00007776/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7777/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007778Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007779 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007780 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007781
Chris Lattnerb53c2382005-10-24 06:22:12 +00007782 // Remove any uses of AI that are dead.
7783 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007784
Chris Lattnerb53c2382005-10-24 06:22:12 +00007785 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7786 Instruction *User = cast<Instruction>(*UI++);
7787 if (isInstructionTriviallyDead(User)) {
7788 while (UI != E && *UI == User)
7789 ++UI; // If this instruction uses AI more than once, don't break UI.
7790
Chris Lattnerb53c2382005-10-24 06:22:12 +00007791 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007792 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007793 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007794 }
7795 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007796
7797 // This requires TargetData to get the alloca alignment and size information.
7798 if (!TD) return 0;
7799
Chris Lattnerb3f83972005-10-24 06:03:58 +00007800 // Get the type really allocated and the type casted to.
7801 const Type *AllocElTy = AI.getAllocatedType();
7802 const Type *CastElTy = PTy->getElementType();
7803 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007804
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007805 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7806 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007807 if (CastElTyAlign < AllocElTyAlign) return 0;
7808
Chris Lattner39387a52005-10-24 06:35:18 +00007809 // If the allocation has multiple uses, only promote it if we are strictly
7810 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007811 // same, we open the door to infinite loops of various kinds. (A reference
7812 // from a dbg.declare doesn't count as a use for this purpose.)
7813 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7814 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007815
Duncan Sands777d2302009-05-09 07:06:46 +00007816 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7817 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007818 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007819
Chris Lattner455fcc82005-10-29 03:19:53 +00007820 // See if we can satisfy the modulus by pulling a scale out of the array
7821 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007822 unsigned ArraySizeScale;
7823 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007824 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007825 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7826 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007827
Chris Lattner455fcc82005-10-29 03:19:53 +00007828 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7829 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007830 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7831 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007832
Chris Lattner455fcc82005-10-29 03:19:53 +00007833 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7834 Value *Amt = 0;
7835 if (Scale == 1) {
7836 Amt = NumElements;
7837 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007838 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007839 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007840 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007841 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007842 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007843 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007844 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007845 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007846 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007847 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007848 }
7849
Jeff Cohen86796be2007-04-04 16:58:57 +00007850 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007851 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007852 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007853 Amt = InsertNewInstBefore(Tmp, AI);
7854 }
7855
Chris Lattnerb3f83972005-10-24 06:03:58 +00007856 AllocationInst *New;
7857 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007858 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007859 else
Owen Anderson50dead02009-07-15 23:53:25 +00007860 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007861 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007862 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007863
Dale Johannesena0a66372009-03-05 00:39:02 +00007864 // If the allocation has one real use plus a dbg.declare, just remove the
7865 // declare.
7866 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7867 EraseInstFromFunction(*DI);
7868 }
7869 // If the allocation has multiple real uses, insert a cast and change all
7870 // things that used it to use the new cast. This will also hack on CI, but it
7871 // will die soon.
7872 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007873 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007874 // New is the allocation instruction, pointer typed. AI is the original
7875 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7876 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007877 InsertNewInstBefore(NewCast, AI);
7878 AI.replaceAllUsesWith(NewCast);
7879 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007880 return ReplaceInstUsesWith(CI, New);
7881}
7882
Chris Lattner70074e02006-05-13 02:06:03 +00007883/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007884/// and return it as type Ty without inserting any new casts and without
7885/// changing the computed value. This is used by code that tries to decide
7886/// whether promoting or shrinking integer operations to wider or smaller types
7887/// will allow us to eliminate a truncate or extend.
7888///
7889/// This is a truncation operation if Ty is smaller than V->getType(), or an
7890/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007891///
7892/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7893/// should return true if trunc(V) can be computed by computing V in the smaller
7894/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7895/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7896/// efficiently truncated.
7897///
7898/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7899/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7900/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007901bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007902 unsigned CastOpc,
7903 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007904 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007905 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007906 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007907
7908 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007909 if (!I) return false;
7910
Dan Gohman6de29f82009-06-15 22:12:54 +00007911 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007912
Chris Lattner951626b2007-08-02 06:11:14 +00007913 // If this is an extension or truncate, we can often eliminate it.
7914 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7915 // If this is a cast from the destination type, we can trivially eliminate
7916 // it, and this will remove a cast overall.
7917 if (I->getOperand(0)->getType() == Ty) {
7918 // If the first operand is itself a cast, and is eliminable, do not count
7919 // this as an eliminable cast. We would prefer to eliminate those two
7920 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007921 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007922 ++NumCastsRemoved;
7923 return true;
7924 }
7925 }
7926
7927 // We can't extend or shrink something that has multiple uses: doing so would
7928 // require duplicating the instruction in general, which isn't profitable.
7929 if (!I->hasOneUse()) return false;
7930
Evan Chengf35fd542009-01-15 17:01:23 +00007931 unsigned Opc = I->getOpcode();
7932 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007933 case Instruction::Add:
7934 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007935 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007936 case Instruction::And:
7937 case Instruction::Or:
7938 case Instruction::Xor:
7939 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007940 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007941 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007942 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007943 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007944
Eli Friedman070a9812009-07-13 22:46:01 +00007945 case Instruction::UDiv:
7946 case Instruction::URem: {
7947 // UDiv and URem can be truncated if all the truncated bits are zero.
7948 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7949 uint32_t BitWidth = Ty->getScalarSizeInBits();
7950 if (BitWidth < OrigBitWidth) {
7951 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7952 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7953 MaskedValueIsZero(I->getOperand(1), Mask)) {
7954 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7955 NumCastsRemoved) &&
7956 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7957 NumCastsRemoved);
7958 }
7959 }
7960 break;
7961 }
Chris Lattner46b96052006-11-29 07:18:39 +00007962 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007963 // If we are truncating the result of this SHL, and if it's a shift of a
7964 // constant amount, we can always perform a SHL in a smaller type.
7965 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007966 uint32_t BitWidth = Ty->getScalarSizeInBits();
7967 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007968 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007969 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007970 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007971 }
7972 break;
7973 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007974 // If this is a truncate of a logical shr, we can truncate it to a smaller
7975 // lshr iff we know that the bits we would otherwise be shifting in are
7976 // already zeros.
7977 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007978 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7979 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007980 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007981 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007982 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7983 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007984 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007985 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007986 }
7987 }
Chris Lattner46b96052006-11-29 07:18:39 +00007988 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007989 case Instruction::ZExt:
7990 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007991 case Instruction::Trunc:
7992 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007993 // can safely replace it. Note that replacing it does not reduce the number
7994 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007995 if (Opc == CastOpc)
7996 return true;
7997
7998 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007999 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008000 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008001 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008002 case Instruction::Select: {
8003 SelectInst *SI = cast<SelectInst>(I);
8004 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008005 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008006 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008007 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008008 }
Chris Lattner8114b712008-06-18 04:00:49 +00008009 case Instruction::PHI: {
8010 // We can change a phi if we can change all operands.
8011 PHINode *PN = cast<PHINode>(I);
8012 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8013 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008014 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008015 return false;
8016 return true;
8017 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008018 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008019 // TODO: Can handle more cases here.
8020 break;
8021 }
8022
8023 return false;
8024}
8025
8026/// EvaluateInDifferentType - Given an expression that
8027/// CanEvaluateInDifferentType returns true for, actually insert the code to
8028/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008029Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008030 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008031 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008032 return Context->getConstantExprIntegerCast(C, Ty,
8033 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008034
8035 // Otherwise, it must be an instruction.
8036 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008037 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008038 unsigned Opc = I->getOpcode();
8039 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008040 case Instruction::Add:
8041 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008042 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008043 case Instruction::And:
8044 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008045 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008046 case Instruction::AShr:
8047 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008048 case Instruction::Shl:
8049 case Instruction::UDiv:
8050 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008051 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008052 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008053 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008054 break;
8055 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008056 case Instruction::Trunc:
8057 case Instruction::ZExt:
8058 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008059 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008060 // just return the source. There's no need to insert it because it is not
8061 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008062 if (I->getOperand(0)->getType() == Ty)
8063 return I->getOperand(0);
8064
Chris Lattner8114b712008-06-18 04:00:49 +00008065 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008066 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008067 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008068 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008069 case Instruction::Select: {
8070 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8071 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8072 Res = SelectInst::Create(I->getOperand(0), True, False);
8073 break;
8074 }
Chris Lattner8114b712008-06-18 04:00:49 +00008075 case Instruction::PHI: {
8076 PHINode *OPN = cast<PHINode>(I);
8077 PHINode *NPN = PHINode::Create(Ty);
8078 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8079 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8080 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8081 }
8082 Res = NPN;
8083 break;
8084 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008085 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008086 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008087 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008088 break;
8089 }
8090
Chris Lattner8114b712008-06-18 04:00:49 +00008091 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008092 return InsertNewInstBefore(Res, *I);
8093}
8094
Reid Spencer3da59db2006-11-27 01:05:10 +00008095/// @brief Implement the transforms common to all CastInst visitors.
8096Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008097 Value *Src = CI.getOperand(0);
8098
Dan Gohman23d9d272007-05-11 21:10:54 +00008099 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008100 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008101 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008102 if (Instruction::CastOps opc =
8103 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8104 // The first cast (CSrc) is eliminable so we need to fix up or replace
8105 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008106 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008107 }
8108 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008109
Reid Spencer3da59db2006-11-27 01:05:10 +00008110 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008111 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8112 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8113 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008114
8115 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008116 if (isa<PHINode>(Src))
8117 if (Instruction *NV = FoldOpIntoPhi(CI))
8118 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008119
Reid Spencer3da59db2006-11-27 01:05:10 +00008120 return 0;
8121}
8122
Chris Lattner46cd5a12009-01-09 05:44:56 +00008123/// FindElementAtOffset - Given a type and a constant offset, determine whether
8124/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008125/// the specified offset. If so, fill them into NewIndices and return the
8126/// resultant element type, otherwise return null.
8127static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8128 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008129 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008130 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008131 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008132 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008133
8134 // Start with the index over the outer type. Note that the type size
8135 // might be zero (even if the offset isn't zero) if the indexed type
8136 // is something like [0 x {int, int}]
8137 const Type *IntPtrTy = TD->getIntPtrType();
8138 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008139 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008140 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008141 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008142
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008143 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008144 if (Offset < 0) {
8145 --FirstIdx;
8146 Offset += TySize;
8147 assert(Offset >= 0);
8148 }
8149 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8150 }
8151
Owen Andersond672ecb2009-07-03 00:17:18 +00008152 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008153
8154 // Index into the types. If we fail, set OrigBase to null.
8155 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008156 // Indexing into tail padding between struct/array elements.
8157 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008158 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008159
Chris Lattner46cd5a12009-01-09 05:44:56 +00008160 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8161 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008162 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8163 "Offset must stay within the indexed type");
8164
Chris Lattner46cd5a12009-01-09 05:44:56 +00008165 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008166 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008167
8168 Offset -= SL->getElementOffset(Elt);
8169 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008170 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008171 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008172 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008173 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008174 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008175 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008176 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008177 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008178 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008179 }
8180 }
8181
Chris Lattner3914f722009-01-24 01:00:13 +00008182 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008183}
8184
Chris Lattnerd3e28342007-04-27 17:44:50 +00008185/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8186Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8187 Value *Src = CI.getOperand(0);
8188
Chris Lattnerd3e28342007-04-27 17:44:50 +00008189 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008190 // If casting the result of a getelementptr instruction with no offset, turn
8191 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008192 if (GEP->hasAllZeroIndices()) {
8193 // Changing the cast operand is usually not a good idea but it is safe
8194 // here because the pointer operand is being replaced with another
8195 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008196 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008197 CI.setOperand(0, GEP->getOperand(0));
8198 return &CI;
8199 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008200
8201 // If the GEP has a single use, and the base pointer is a bitcast, and the
8202 // GEP computes a constant offset, see if we can convert these three
8203 // instructions into fewer. This typically happens with unions and other
8204 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008205 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008206 if (GEP->hasAllConstantIndices()) {
8207 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008208 ConstantInt *OffsetV =
8209 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008210 int64_t Offset = OffsetV->getSExtValue();
8211
8212 // Get the base pointer input of the bitcast, and the type it points to.
8213 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8214 const Type *GEPIdxTy =
8215 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008216 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008217 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008218 // If we were able to index down into an element, create the GEP
8219 // and bitcast the result. This eliminates one bitcast, potentially
8220 // two.
8221 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8222 NewIndices.begin(),
8223 NewIndices.end(), "");
8224 InsertNewInstBefore(NGEP, CI);
8225 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008226
Chris Lattner46cd5a12009-01-09 05:44:56 +00008227 if (isa<BitCastInst>(CI))
8228 return new BitCastInst(NGEP, CI.getType());
8229 assert(isa<PtrToIntInst>(CI));
8230 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008231 }
8232 }
8233 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008234 }
8235
8236 return commonCastTransforms(CI);
8237}
8238
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008239/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8240/// type like i42. We don't want to introduce operations on random non-legal
8241/// integer types where they don't already exist in the code. In the future,
8242/// we should consider making this based off target-data, so that 32-bit targets
8243/// won't get i64 operations etc.
8244static bool isSafeIntegerType(const Type *Ty) {
8245 switch (Ty->getPrimitiveSizeInBits()) {
8246 case 8:
8247 case 16:
8248 case 32:
8249 case 64:
8250 return true;
8251 default:
8252 return false;
8253 }
8254}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008255
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008256/// commonIntCastTransforms - This function implements the common transforms
8257/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008258Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8259 if (Instruction *Result = commonCastTransforms(CI))
8260 return Result;
8261
8262 Value *Src = CI.getOperand(0);
8263 const Type *SrcTy = Src->getType();
8264 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008265 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8266 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008267
Reid Spencer3da59db2006-11-27 01:05:10 +00008268 // See if we can simplify any instructions used by the LHS whose sole
8269 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008270 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008271 return &CI;
8272
8273 // If the source isn't an instruction or has more than one use then we
8274 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008275 Instruction *SrcI = dyn_cast<Instruction>(Src);
8276 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008277 return 0;
8278
Chris Lattnerc739cd62007-03-03 05:27:34 +00008279 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008280 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008281 // Only do this if the dest type is a simple type, don't convert the
8282 // expression tree to something weird like i93 unless the source is also
8283 // strange.
8284 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008285 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8286 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008287 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008288 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008289 // eliminates the cast, so it is always a win. If this is a zero-extension,
8290 // we need to do an AND to maintain the clear top-part of the computation,
8291 // so we require that the input have eliminated at least one cast. If this
8292 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008293 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008294 bool DoXForm = false;
8295 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008296 switch (CI.getOpcode()) {
8297 default:
8298 // All the others use floating point so we shouldn't actually
8299 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008300 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008301 case Instruction::Trunc:
8302 DoXForm = true;
8303 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008304 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008305 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008306 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008307 // If it's unnecessary to issue an AND to clear the high bits, it's
8308 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008309 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008310 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8311 if (MaskedValueIsZero(TryRes, Mask))
8312 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008313
8314 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008315 if (TryI->use_empty())
8316 EraseInstFromFunction(*TryI);
8317 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008318 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008319 }
Evan Chengf35fd542009-01-15 17:01:23 +00008320 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008321 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008322 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008323 // If we do not have to emit the truncate + sext pair, then it's always
8324 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008325 //
8326 // It's not safe to eliminate the trunc + sext pair if one of the
8327 // eliminated cast is a truncate. e.g.
8328 // t2 = trunc i32 t1 to i16
8329 // t3 = sext i16 t2 to i32
8330 // !=
8331 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008332 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008333 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8334 if (NumSignBits > (DestBitSize - SrcBitSize))
8335 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008336
8337 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008338 if (TryI->use_empty())
8339 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008340 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008341 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008342 }
Evan Chengf35fd542009-01-15 17:01:23 +00008343 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008344
8345 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008346 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8347 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008348 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8349 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008350 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008351 // Just replace this cast with the result.
8352 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008353
Reid Spencer3da59db2006-11-27 01:05:10 +00008354 assert(Res->getType() == DestTy);
8355 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008356 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008357 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008358 // Just replace this cast with the result.
8359 return ReplaceInstUsesWith(CI, Res);
8360 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008361 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008362
8363 // If the high bits are already zero, just replace this cast with the
8364 // result.
8365 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8366 if (MaskedValueIsZero(Res, Mask))
8367 return ReplaceInstUsesWith(CI, Res);
8368
8369 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008370 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008371 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008372 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008373 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008374 case Instruction::SExt: {
8375 // If the high bits are already filled with sign bit, just replace this
8376 // cast with the result.
8377 unsigned NumSignBits = ComputeNumSignBits(Res);
8378 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008379 return ReplaceInstUsesWith(CI, Res);
8380
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008382 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008383 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8384 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008386 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008387 }
8388 }
8389
8390 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8391 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8392
8393 switch (SrcI->getOpcode()) {
8394 case Instruction::Add:
8395 case Instruction::Mul:
8396 case Instruction::And:
8397 case Instruction::Or:
8398 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008399 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008400 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8401 // Don't insert two casts unless at least one can be eliminated.
8402 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008403 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008404 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8405 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008406 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008407 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008408 }
8409 }
8410
8411 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8412 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8413 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersonb3056fa2009-07-21 18:03:38 +00008414 Op1 == Context->getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008415 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008416 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008417 return BinaryOperator::CreateXor(New,
8418 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008419 }
8420 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008421
Eli Friedman65445c52009-07-13 21:45:57 +00008422 case Instruction::Shl: {
8423 // Canonicalize trunc inside shl, if we can.
8424 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8425 if (CI && DestBitSize < SrcBitSize &&
8426 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8427 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8428 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008429 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008430 }
8431 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008432 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008433 }
8434 return 0;
8435}
8436
Chris Lattner8a9f5712007-04-11 06:57:46 +00008437Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008438 if (Instruction *Result = commonIntCastTransforms(CI))
8439 return Result;
8440
8441 Value *Src = CI.getOperand(0);
8442 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008443 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8444 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008445
8446 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008447 if (DestBitWidth == 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008448 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008449 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008450 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008451 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008452 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008453
Chris Lattner4f9797d2009-03-24 18:15:30 +00008454 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8455 ConstantInt *ShAmtV = 0;
8456 Value *ShiftOp = 0;
8457 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008458 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008459 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8460
8461 // Get a mask for the bits shifting in.
8462 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8463 if (MaskedValueIsZero(ShiftOp, Mask)) {
8464 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008465 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008466
8467 // Okay, we can shrink this. Truncate the input, then return a new
8468 // shift.
8469 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008470 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008471 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008472 }
8473 }
8474
8475 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008476}
8477
Evan Chengb98a10e2008-03-24 00:21:34 +00008478/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8479/// in order to eliminate the icmp.
8480Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8481 bool DoXform) {
8482 // If we are just checking for a icmp eq of a single bit and zext'ing it
8483 // to an integer, then shift the bit to the appropriate place and then
8484 // cast to integer to avoid the comparison.
8485 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8486 const APInt &Op1CV = Op1C->getValue();
8487
8488 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8489 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8490 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8491 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8492 if (!DoXform) return ICI;
8493
8494 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008495 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008496 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008497 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008498 In->getName()+".lobit"),
8499 CI);
8500 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008501 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008502 false/*ZExt*/, "tmp", &CI);
8503
8504 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008505 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008506 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008507 In->getName()+".not"),
8508 CI);
8509 }
8510
8511 return ReplaceInstUsesWith(CI, In);
8512 }
8513
8514
8515
8516 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8517 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8518 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8519 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8520 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8521 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8522 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8523 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8524 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8525 // This only works for EQ and NE
8526 ICI->isEquality()) {
8527 // If Op1C some other power of two, convert:
8528 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8529 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8530 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8531 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8532
8533 APInt KnownZeroMask(~KnownZero);
8534 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8535 if (!DoXform) return ICI;
8536
8537 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8538 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8539 // (X&4) == 2 --> false
8540 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008541 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8542 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008543 return ReplaceInstUsesWith(CI, Res);
8544 }
8545
8546 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8547 Value *In = ICI->getOperand(0);
8548 if (ShiftAmt) {
8549 // Perform a logical shr by shiftamt.
8550 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008551 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008552 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008553 In->getName()+".lobit"), CI);
8554 }
8555
8556 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008557 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008558 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008559 InsertNewInstBefore(cast<Instruction>(In), CI);
8560 }
8561
8562 if (CI.getType() == In->getType())
8563 return ReplaceInstUsesWith(CI, In);
8564 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008565 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008566 }
8567 }
8568 }
8569
8570 return 0;
8571}
8572
Chris Lattner8a9f5712007-04-11 06:57:46 +00008573Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008574 // If one of the common conversion will work ..
8575 if (Instruction *Result = commonIntCastTransforms(CI))
8576 return Result;
8577
8578 Value *Src = CI.getOperand(0);
8579
Chris Lattnera84f47c2009-02-17 20:47:23 +00008580 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8581 // types and if the sizes are just right we can convert this into a logical
8582 // 'and' which will be much cheaper than the pair of casts.
8583 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8584 // Get the sizes of the types involved. We know that the intermediate type
8585 // will be smaller than A or C, but don't know the relation between A and C.
8586 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008587 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8588 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8589 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008590 // If we're actually extending zero bits, then if
8591 // SrcSize < DstSize: zext(a & mask)
8592 // SrcSize == DstSize: a & mask
8593 // SrcSize > DstSize: trunc(a) & mask
8594 if (SrcSize < DstSize) {
8595 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008596 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008597 Instruction *And =
8598 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8599 InsertNewInstBefore(And, CI);
8600 return new ZExtInst(And, CI.getType());
8601 } else if (SrcSize == DstSize) {
8602 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008603 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008604 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008605 } else if (SrcSize > DstSize) {
8606 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8607 InsertNewInstBefore(Trunc, CI);
8608 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008609 return BinaryOperator::CreateAnd(Trunc,
8610 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008611 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008612 }
8613 }
8614
Evan Chengb98a10e2008-03-24 00:21:34 +00008615 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8616 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008617
Evan Chengb98a10e2008-03-24 00:21:34 +00008618 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8619 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8620 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8621 // of the (zext icmp) will be transformed.
8622 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8623 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8624 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8625 (transformZExtICmp(LHS, CI, false) ||
8626 transformZExtICmp(RHS, CI, false))) {
8627 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8628 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008629 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008630 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008631 }
8632
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008633 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008634 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8635 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8636 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8637 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008638 if (TI0->getType() == CI.getType())
8639 return
8640 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008641 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008642 }
8643
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008644 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8645 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8646 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8647 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8648 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8649 And->getOperand(1) == C)
8650 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8651 Value *TI0 = TI->getOperand(0);
8652 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008653 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008654 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8655 InsertNewInstBefore(NewAnd, *And);
8656 return BinaryOperator::CreateXor(NewAnd, ZC);
8657 }
8658 }
8659
Reid Spencer3da59db2006-11-27 01:05:10 +00008660 return 0;
8661}
8662
Chris Lattner8a9f5712007-04-11 06:57:46 +00008663Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008664 if (Instruction *I = commonIntCastTransforms(CI))
8665 return I;
8666
Chris Lattner8a9f5712007-04-11 06:57:46 +00008667 Value *Src = CI.getOperand(0);
8668
Dan Gohman1975d032008-10-30 20:40:10 +00008669 // Canonicalize sign-extend from i1 to a select.
8670 if (Src->getType() == Type::Int1Ty)
8671 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008672 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008673 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008674
8675 // See if the value being truncated is already sign extended. If so, just
8676 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008677 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008678 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008679 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8680 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8681 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008682 unsigned NumSignBits = ComputeNumSignBits(Op);
8683
8684 if (OpBits == DestBits) {
8685 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8686 // bits, it is already ready.
8687 if (NumSignBits > DestBits-MidBits)
8688 return ReplaceInstUsesWith(CI, Op);
8689 } else if (OpBits < DestBits) {
8690 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8691 // bits, just sext from i32.
8692 if (NumSignBits > OpBits-MidBits)
8693 return new SExtInst(Op, CI.getType(), "tmp");
8694 } else {
8695 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8696 // bits, just truncate to i32.
8697 if (NumSignBits > OpBits-MidBits)
8698 return new TruncInst(Op, CI.getType(), "tmp");
8699 }
8700 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008701
8702 // If the input is a shl/ashr pair of a same constant, then this is a sign
8703 // extension from a smaller value. If we could trust arbitrary bitwidth
8704 // integers, we could turn this into a truncate to the smaller bit and then
8705 // use a sext for the whole extension. Since we don't, look deeper and check
8706 // for a truncate. If the source and dest are the same type, eliminate the
8707 // trunc and extend and just do shifts. For example, turn:
8708 // %a = trunc i32 %i to i8
8709 // %b = shl i8 %a, 6
8710 // %c = ashr i8 %b, 6
8711 // %d = sext i8 %c to i32
8712 // into:
8713 // %a = shl i32 %i, 30
8714 // %d = ashr i32 %a, 30
8715 Value *A = 0;
8716 ConstantInt *BA = 0, *CA = 0;
8717 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008718 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008719 BA == CA && isa<TruncInst>(A)) {
8720 Value *I = cast<TruncInst>(A)->getOperand(0);
8721 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008722 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8723 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008724 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008725 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008726 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8727 CI.getName()), CI);
8728 return BinaryOperator::CreateAShr(I, ShAmtV);
8729 }
8730 }
8731
Chris Lattnerba417832007-04-11 06:12:58 +00008732 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008733}
8734
Chris Lattnerb7530652008-01-27 05:29:54 +00008735/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8736/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008737static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008738 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008739 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008740 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008741 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8742 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008743 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008744 return 0;
8745}
8746
8747/// LookThroughFPExtensions - If this is an fp extension instruction, look
8748/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008749static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008750 if (Instruction *I = dyn_cast<Instruction>(V))
8751 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008752 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008753
8754 // If this value is a constant, return the constant in the smallest FP type
8755 // that can accurately represent it. This allows us to turn
8756 // (float)((double)X+2.0) into x+2.0f.
8757 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8758 if (CFP->getType() == Type::PPC_FP128Ty)
8759 return V; // No constant folding of this.
8760 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008761 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008762 return V;
8763 if (CFP->getType() == Type::DoubleTy)
8764 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008765 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008766 return V;
8767 // Don't try to shrink to various long double types.
8768 }
8769
8770 return V;
8771}
8772
8773Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8774 if (Instruction *I = commonCastTransforms(CI))
8775 return I;
8776
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008777 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008778 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008779 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008780 // many builtins (sqrt, etc).
8781 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8782 if (OpI && OpI->hasOneUse()) {
8783 switch (OpI->getOpcode()) {
8784 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008785 case Instruction::FAdd:
8786 case Instruction::FSub:
8787 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008788 case Instruction::FDiv:
8789 case Instruction::FRem:
8790 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008791 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8792 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008793 if (LHSTrunc->getType() != SrcTy &&
8794 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008795 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008796 // If the source types were both smaller than the destination type of
8797 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008798 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8799 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008800 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8801 CI.getType(), CI);
8802 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8803 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008804 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008805 }
8806 }
8807 break;
8808 }
8809 }
8810 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008811}
8812
8813Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8814 return commonCastTransforms(CI);
8815}
8816
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008817Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008818 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8819 if (OpI == 0)
8820 return commonCastTransforms(FI);
8821
8822 // fptoui(uitofp(X)) --> X
8823 // fptoui(sitofp(X)) --> X
8824 // This is safe if the intermediate type has enough bits in its mantissa to
8825 // accurately represent all values of X. For example, do not do this with
8826 // i64->float->i64. This is also safe for sitofp case, because any negative
8827 // 'X' value would cause an undefined result for the fptoui.
8828 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8829 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008830 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008831 OpI->getType()->getFPMantissaWidth())
8832 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008833
8834 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008835}
8836
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008837Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008838 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8839 if (OpI == 0)
8840 return commonCastTransforms(FI);
8841
8842 // fptosi(sitofp(X)) --> X
8843 // fptosi(uitofp(X)) --> X
8844 // This is safe if the intermediate type has enough bits in its mantissa to
8845 // accurately represent all values of X. For example, do not do this with
8846 // i64->float->i64. This is also safe for sitofp case, because any negative
8847 // 'X' value would cause an undefined result for the fptoui.
8848 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8849 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008850 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008851 OpI->getType()->getFPMantissaWidth())
8852 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008853
8854 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008855}
8856
8857Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8858 return commonCastTransforms(CI);
8859}
8860
8861Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8862 return commonCastTransforms(CI);
8863}
8864
Chris Lattnera0e69692009-03-24 18:35:40 +00008865Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8866 // If the destination integer type is smaller than the intptr_t type for
8867 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8868 // trunc to be exposed to other transforms. Don't do this for extending
8869 // ptrtoint's, because we don't know if the target sign or zero extends its
8870 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008871 if (TD &&
8872 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008873 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8874 TD->getIntPtrType(),
8875 "tmp"), CI);
8876 return new TruncInst(P, CI.getType());
8877 }
8878
Chris Lattnerd3e28342007-04-27 17:44:50 +00008879 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008880}
8881
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008882Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008883 // If the source integer type is larger than the intptr_t type for
8884 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8885 // allows the trunc to be exposed to other transforms. Don't do this for
8886 // extending inttoptr's, because we don't know if the target sign or zero
8887 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008888 if (TD &&
8889 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008890 TD->getPointerSizeInBits()) {
8891 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8892 TD->getIntPtrType(),
8893 "tmp"), CI);
8894 return new IntToPtrInst(P, CI.getType());
8895 }
8896
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008897 if (Instruction *I = commonCastTransforms(CI))
8898 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008899
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008900 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008901}
8902
Chris Lattnerd3e28342007-04-27 17:44:50 +00008903Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008904 // If the operands are integer typed then apply the integer transforms,
8905 // otherwise just apply the common ones.
8906 Value *Src = CI.getOperand(0);
8907 const Type *SrcTy = Src->getType();
8908 const Type *DestTy = CI.getType();
8909
Eli Friedman7e25d452009-07-13 20:53:00 +00008910 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008911 if (Instruction *I = commonPointerCastTransforms(CI))
8912 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008913 } else {
8914 if (Instruction *Result = commonCastTransforms(CI))
8915 return Result;
8916 }
8917
8918
8919 // Get rid of casts from one type to the same type. These are useless and can
8920 // be replaced by the operand.
8921 if (DestTy == Src->getType())
8922 return ReplaceInstUsesWith(CI, Src);
8923
Reid Spencer3da59db2006-11-27 01:05:10 +00008924 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008925 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8926 const Type *DstElTy = DstPTy->getElementType();
8927 const Type *SrcElTy = SrcPTy->getElementType();
8928
Nate Begeman83ad90a2008-03-31 00:22:16 +00008929 // If the address spaces don't match, don't eliminate the bitcast, which is
8930 // required for changing types.
8931 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8932 return 0;
8933
Chris Lattnerd3e28342007-04-27 17:44:50 +00008934 // If we are casting a malloc or alloca to a pointer to a type of the same
8935 // size, rewrite the allocation instruction to allocate the "right" type.
8936 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8937 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8938 return V;
8939
Chris Lattnerd717c182007-05-05 22:32:24 +00008940 // If the source and destination are pointers, and this cast is equivalent
8941 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008942 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00008943 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008944 unsigned NumZeros = 0;
8945 while (SrcElTy != DstElTy &&
8946 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8947 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8948 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8949 ++NumZeros;
8950 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008951
Chris Lattnerd3e28342007-04-27 17:44:50 +00008952 // If we found a path from the src to dest, create the getelementptr now.
8953 if (SrcElTy == DstElTy) {
8954 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008955 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8956 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008957 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008958 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008959
Eli Friedman2451a642009-07-18 23:06:53 +00008960 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8961 if (DestVTy->getNumElements() == 1) {
8962 if (!isa<VectorType>(SrcTy)) {
8963 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8964 DestVTy->getElementType(), CI);
8965 return InsertElementInst::Create(Context->getUndef(DestTy), Elem,
8966 Context->getNullValue(Type::Int32Ty));
8967 }
8968 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8969 }
8970 }
8971
8972 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8973 if (SrcVTy->getNumElements() == 1) {
8974 if (!isa<VectorType>(DestTy)) {
8975 Instruction *Elem =
8976 new ExtractElementInst(Src, Context->getNullValue(Type::Int32Ty));
8977 InsertNewInstBefore(Elem, CI);
8978 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8979 }
8980 }
8981 }
8982
Reid Spencer3da59db2006-11-27 01:05:10 +00008983 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8984 if (SVI->hasOneUse()) {
8985 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8986 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008987 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008988 cast<VectorType>(DestTy)->getNumElements() ==
8989 SVI->getType()->getNumElements() &&
8990 SVI->getType()->getNumElements() ==
8991 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008992 CastInst *Tmp;
8993 // If either of the operands is a cast from CI.getType(), then
8994 // evaluating the shuffle in the casted destination's type will allow
8995 // us to eliminate at least one cast.
8996 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8997 Tmp->getOperand(0)->getType() == DestTy) ||
8998 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8999 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009000 Value *LHS = InsertCastBefore(Instruction::BitCast,
9001 SVI->getOperand(0), DestTy, CI);
9002 Value *RHS = InsertCastBefore(Instruction::BitCast,
9003 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009004 // Return a new shuffle vector. Use the same element ID's, as we
9005 // know the vector types match #elts.
9006 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009007 }
9008 }
9009 }
9010 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009011 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009012}
9013
Chris Lattnere576b912004-04-09 23:46:01 +00009014/// GetSelectFoldableOperands - We want to turn code that looks like this:
9015/// %C = or %A, %B
9016/// %D = select %cond, %C, %A
9017/// into:
9018/// %C = select %cond, %B, 0
9019/// %D = or %A, %C
9020///
9021/// Assuming that the specified instruction is an operand to the select, return
9022/// a bitmask indicating which operands of this instruction are foldable if they
9023/// equal the other incoming value of the select.
9024///
9025static unsigned GetSelectFoldableOperands(Instruction *I) {
9026 switch (I->getOpcode()) {
9027 case Instruction::Add:
9028 case Instruction::Mul:
9029 case Instruction::And:
9030 case Instruction::Or:
9031 case Instruction::Xor:
9032 return 3; // Can fold through either operand.
9033 case Instruction::Sub: // Can only fold on the amount subtracted.
9034 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009035 case Instruction::LShr:
9036 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009037 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009038 default:
9039 return 0; // Cannot fold
9040 }
9041}
9042
9043/// GetSelectFoldableConstant - For the same transformation as the previous
9044/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009045static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009046 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009047 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009048 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009049 case Instruction::Add:
9050 case Instruction::Sub:
9051 case Instruction::Or:
9052 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009053 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009054 case Instruction::LShr:
9055 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009056 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009057 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009058 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009059 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009060 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009061 }
9062}
9063
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009064/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9065/// have the same opcode and only one use each. Try to simplify this.
9066Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9067 Instruction *FI) {
9068 if (TI->getNumOperands() == 1) {
9069 // If this is a non-volatile load or a cast from the same type,
9070 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009071 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009072 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9073 return 0;
9074 } else {
9075 return 0; // unknown unary op.
9076 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009077
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009078 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009079 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9080 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009081 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009082 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009083 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009084 }
9085
Reid Spencer832254e2007-02-02 02:16:23 +00009086 // Only handle binary operators here.
9087 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009088 return 0;
9089
9090 // Figure out if the operations have any operands in common.
9091 Value *MatchOp, *OtherOpT, *OtherOpF;
9092 bool MatchIsOpZero;
9093 if (TI->getOperand(0) == FI->getOperand(0)) {
9094 MatchOp = TI->getOperand(0);
9095 OtherOpT = TI->getOperand(1);
9096 OtherOpF = FI->getOperand(1);
9097 MatchIsOpZero = true;
9098 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9099 MatchOp = TI->getOperand(1);
9100 OtherOpT = TI->getOperand(0);
9101 OtherOpF = FI->getOperand(0);
9102 MatchIsOpZero = false;
9103 } else if (!TI->isCommutative()) {
9104 return 0;
9105 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9106 MatchOp = TI->getOperand(0);
9107 OtherOpT = TI->getOperand(1);
9108 OtherOpF = FI->getOperand(0);
9109 MatchIsOpZero = true;
9110 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9111 MatchOp = TI->getOperand(1);
9112 OtherOpT = TI->getOperand(0);
9113 OtherOpF = FI->getOperand(1);
9114 MatchIsOpZero = true;
9115 } else {
9116 return 0;
9117 }
9118
9119 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009120 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9121 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009122 InsertNewInstBefore(NewSI, SI);
9123
9124 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9125 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009126 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009127 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009128 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009129 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009130 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009131 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009132}
9133
Evan Chengde621922009-03-31 20:42:45 +00009134static bool isSelect01(Constant *C1, Constant *C2) {
9135 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9136 if (!C1I)
9137 return false;
9138 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9139 if (!C2I)
9140 return false;
9141 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9142}
9143
9144/// FoldSelectIntoOp - Try fold the select into one of the operands to
9145/// facilitate further optimization.
9146Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9147 Value *FalseVal) {
9148 // See the comment above GetSelectFoldableOperands for a description of the
9149 // transformation we are doing here.
9150 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9151 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9152 !isa<Constant>(FalseVal)) {
9153 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9154 unsigned OpToFold = 0;
9155 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9156 OpToFold = 1;
9157 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9158 OpToFold = 2;
9159 }
9160
9161 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009162 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009163 Value *OOp = TVI->getOperand(2-OpToFold);
9164 // Avoid creating select between 2 constants unless it's selecting
9165 // between 0 and 1.
9166 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9167 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9168 InsertNewInstBefore(NewSel, SI);
9169 NewSel->takeName(TVI);
9170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9171 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009172 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009173 }
9174 }
9175 }
9176 }
9177 }
9178
9179 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9180 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9181 !isa<Constant>(TrueVal)) {
9182 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9183 unsigned OpToFold = 0;
9184 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9185 OpToFold = 1;
9186 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9187 OpToFold = 2;
9188 }
9189
9190 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009191 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009192 Value *OOp = FVI->getOperand(2-OpToFold);
9193 // Avoid creating select between 2 constants unless it's selecting
9194 // between 0 and 1.
9195 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9196 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9197 InsertNewInstBefore(NewSel, SI);
9198 NewSel->takeName(FVI);
9199 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9200 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009201 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009202 }
9203 }
9204 }
9205 }
9206 }
9207
9208 return 0;
9209}
9210
Dan Gohman81b28ce2008-09-16 18:46:06 +00009211/// visitSelectInstWithICmp - Visit a SelectInst that has an
9212/// ICmpInst as its first operand.
9213///
9214Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9215 ICmpInst *ICI) {
9216 bool Changed = false;
9217 ICmpInst::Predicate Pred = ICI->getPredicate();
9218 Value *CmpLHS = ICI->getOperand(0);
9219 Value *CmpRHS = ICI->getOperand(1);
9220 Value *TrueVal = SI.getTrueValue();
9221 Value *FalseVal = SI.getFalseValue();
9222
9223 // Check cases where the comparison is with a constant that
9224 // can be adjusted to fit the min/max idiom. We may edit ICI in
9225 // place here, so make sure the select is the only user.
9226 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009227 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009228 switch (Pred) {
9229 default: break;
9230 case ICmpInst::ICMP_ULT:
9231 case ICmpInst::ICMP_SLT: {
9232 // X < MIN ? T : F --> F
9233 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9234 return ReplaceInstUsesWith(SI, FalseVal);
9235 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009236 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009237 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9238 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9239 Pred = ICmpInst::getSwappedPredicate(Pred);
9240 CmpRHS = AdjustedRHS;
9241 std::swap(FalseVal, TrueVal);
9242 ICI->setPredicate(Pred);
9243 ICI->setOperand(1, CmpRHS);
9244 SI.setOperand(1, TrueVal);
9245 SI.setOperand(2, FalseVal);
9246 Changed = true;
9247 }
9248 break;
9249 }
9250 case ICmpInst::ICMP_UGT:
9251 case ICmpInst::ICMP_SGT: {
9252 // X > MAX ? T : F --> F
9253 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9254 return ReplaceInstUsesWith(SI, FalseVal);
9255 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009256 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009257 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9258 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9259 Pred = ICmpInst::getSwappedPredicate(Pred);
9260 CmpRHS = AdjustedRHS;
9261 std::swap(FalseVal, TrueVal);
9262 ICI->setPredicate(Pred);
9263 ICI->setOperand(1, CmpRHS);
9264 SI.setOperand(1, TrueVal);
9265 SI.setOperand(2, FalseVal);
9266 Changed = true;
9267 }
9268 break;
9269 }
9270 }
9271
Dan Gohman1975d032008-10-30 20:40:10 +00009272 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9273 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009274 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009275 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9276 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009277 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009278 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9279 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009280 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9281
Dan Gohman1975d032008-10-30 20:40:10 +00009282 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9283 // If we are just checking for a icmp eq of a single bit and zext'ing it
9284 // to an integer, then shift the bit to the appropriate place and then
9285 // cast to integer to avoid the comparison.
9286 const APInt &Op1CV = CI->getValue();
9287
9288 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9289 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9290 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009291 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009292 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009293 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009294 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009295 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9296 In->getName()+".lobit"),
9297 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009298 if (In->getType() != SI.getType())
9299 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009300 true/*SExt*/, "tmp", ICI);
9301
9302 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009303 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009304 In->getName()+".not"), *ICI);
9305
9306 return ReplaceInstUsesWith(SI, In);
9307 }
9308 }
9309 }
9310
Dan Gohman81b28ce2008-09-16 18:46:06 +00009311 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9312 // Transform (X == Y) ? X : Y -> Y
9313 if (Pred == ICmpInst::ICMP_EQ)
9314 return ReplaceInstUsesWith(SI, FalseVal);
9315 // Transform (X != Y) ? X : Y -> X
9316 if (Pred == ICmpInst::ICMP_NE)
9317 return ReplaceInstUsesWith(SI, TrueVal);
9318 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9319
9320 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9321 // Transform (X == Y) ? Y : X -> X
9322 if (Pred == ICmpInst::ICMP_EQ)
9323 return ReplaceInstUsesWith(SI, FalseVal);
9324 // Transform (X != Y) ? Y : X -> Y
9325 if (Pred == ICmpInst::ICMP_NE)
9326 return ReplaceInstUsesWith(SI, TrueVal);
9327 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9328 }
9329
9330 /// NOTE: if we wanted to, this is where to detect integer ABS
9331
9332 return Changed ? &SI : 0;
9333}
9334
Chris Lattner3d69f462004-03-12 05:52:32 +00009335Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009336 Value *CondVal = SI.getCondition();
9337 Value *TrueVal = SI.getTrueValue();
9338 Value *FalseVal = SI.getFalseValue();
9339
9340 // select true, X, Y -> X
9341 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009342 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009343 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009344
9345 // select C, X, X -> X
9346 if (TrueVal == FalseVal)
9347 return ReplaceInstUsesWith(SI, TrueVal);
9348
Chris Lattnere87597f2004-10-16 18:11:37 +00009349 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9350 return ReplaceInstUsesWith(SI, FalseVal);
9351 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9352 return ReplaceInstUsesWith(SI, TrueVal);
9353 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9354 if (isa<Constant>(TrueVal))
9355 return ReplaceInstUsesWith(SI, TrueVal);
9356 else
9357 return ReplaceInstUsesWith(SI, FalseVal);
9358 }
9359
Reid Spencer4fe16d62007-01-11 18:21:29 +00009360 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009361 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009362 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009363 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009364 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009365 } else {
9366 // Change: A = select B, false, C --> A = and !B, C
9367 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009368 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009369 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009370 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009371 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009372 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009373 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009374 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009375 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009376 } else {
9377 // Change: A = select B, C, true --> A = or !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::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009382 }
9383 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009384
9385 // select a, b, a -> a&b
9386 // select a, a, b -> a|b
9387 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009388 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009389 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009390 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009391 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009392
Chris Lattner2eefe512004-04-09 19:05:30 +00009393 // Selecting between two integer constants?
9394 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9395 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009396 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009397 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009398 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009399 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009400 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009401 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009402 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009403 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009404 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009405 }
Chris Lattner457dd822004-06-09 07:59:58 +00009406
Reid Spencere4d87aa2006-12-23 06:05:41 +00009407 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009408 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009409 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009410 // non-constant value, eliminate this whole mess. This corresponds to
9411 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009412 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009413 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009414 cast<Constant>(IC->getOperand(1))->isNullValue())
9415 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9416 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009417 isa<ConstantInt>(ICA->getOperand(1)) &&
9418 (ICA->getOperand(1) == TrueValC ||
9419 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009420 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9421 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009422 // know whether we have a icmp_ne or icmp_eq and whether the
9423 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009424 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009425 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009426 Value *V = ICA;
9427 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009428 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009429 Instruction::Xor, V, ICA->getOperand(1)), SI);
9430 return ReplaceInstUsesWith(SI, V);
9431 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009432 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009433 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009434
9435 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009436 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9437 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009438 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009439 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9440 // This is not safe in general for floating point:
9441 // consider X== -0, Y== +0.
9442 // It becomes safe if either operand is a nonzero constant.
9443 ConstantFP *CFPt, *CFPf;
9444 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9445 !CFPt->getValueAPF().isZero()) ||
9446 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9447 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009448 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009449 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009450 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009451 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009452 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009453 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009454
Reid Spencere4d87aa2006-12-23 06:05:41 +00009455 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009456 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009457 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9458 // This is not safe in general for floating point:
9459 // consider X== -0, Y== +0.
9460 // It becomes safe if either operand is a nonzero constant.
9461 ConstantFP *CFPt, *CFPf;
9462 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9463 !CFPt->getValueAPF().isZero()) ||
9464 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9465 !CFPf->getValueAPF().isZero()))
9466 return ReplaceInstUsesWith(SI, FalseVal);
9467 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009468 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009469 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9470 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009471 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009472 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009473 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009474 }
9475
9476 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009477 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9478 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9479 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009480
Chris Lattner87875da2005-01-13 22:52:24 +00009481 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9482 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9483 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009484 Instruction *AddOp = 0, *SubOp = 0;
9485
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009486 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9487 if (TI->getOpcode() == FI->getOpcode())
9488 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9489 return IV;
9490
9491 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9492 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009493 if ((TI->getOpcode() == Instruction::Sub &&
9494 FI->getOpcode() == Instruction::Add) ||
9495 (TI->getOpcode() == Instruction::FSub &&
9496 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009497 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009498 } else if ((FI->getOpcode() == Instruction::Sub &&
9499 TI->getOpcode() == Instruction::Add) ||
9500 (FI->getOpcode() == Instruction::FSub &&
9501 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009502 AddOp = TI; SubOp = FI;
9503 }
9504
9505 if (AddOp) {
9506 Value *OtherAddOp = 0;
9507 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9508 OtherAddOp = AddOp->getOperand(1);
9509 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9510 OtherAddOp = AddOp->getOperand(0);
9511 }
9512
9513 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009514 // So at this point we know we have (Y -> OtherAddOp):
9515 // select C, (add X, Y), (sub X, Z)
9516 Value *NegVal; // Compute -Z
9517 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009518 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009519 } else {
9520 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009521 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9522 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009523 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009524
9525 Value *NewTrueOp = OtherAddOp;
9526 Value *NewFalseOp = NegVal;
9527 if (AddOp != TI)
9528 std::swap(NewTrueOp, NewFalseOp);
9529 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009530 SelectInst::Create(CondVal, NewTrueOp,
9531 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009532
9533 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009534 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009535 }
9536 }
9537 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009538
Chris Lattnere576b912004-04-09 23:46:01 +00009539 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009540 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009541 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9542 if (FoldI)
9543 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009544 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009545
9546 if (BinaryOperator::isNot(CondVal)) {
9547 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9548 SI.setOperand(1, FalseVal);
9549 SI.setOperand(2, TrueVal);
9550 return &SI;
9551 }
9552
Chris Lattner3d69f462004-03-12 05:52:32 +00009553 return 0;
9554}
9555
Dan Gohmaneee962e2008-04-10 18:43:06 +00009556/// EnforceKnownAlignment - If the specified pointer points to an object that
9557/// we control, modify the object's alignment to PrefAlign. This isn't
9558/// often possible though. If alignment is important, a more reliable approach
9559/// is to simply align all global variables and allocation instructions to
9560/// their preferred alignment from the beginning.
9561///
9562static unsigned EnforceKnownAlignment(Value *V,
9563 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009564
Dan Gohmaneee962e2008-04-10 18:43:06 +00009565 User *U = dyn_cast<User>(V);
9566 if (!U) return Align;
9567
Dan Gohmanca178902009-07-17 20:47:02 +00009568 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009569 default: break;
9570 case Instruction::BitCast:
9571 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9572 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009573 // If all indexes are zero, it is just the alignment of the base pointer.
9574 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009575 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009576 if (!isa<Constant>(*i) ||
9577 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009578 AllZeroOperands = false;
9579 break;
9580 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009581
9582 if (AllZeroOperands) {
9583 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009584 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009585 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009586 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009587 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009588 }
9589
9590 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9591 // If there is a large requested alignment and we can, bump up the alignment
9592 // of the global.
9593 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009594 if (GV->getAlignment() >= PrefAlign)
9595 Align = GV->getAlignment();
9596 else {
9597 GV->setAlignment(PrefAlign);
9598 Align = PrefAlign;
9599 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009600 }
9601 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9602 // If there is a requested alignment and if this is an alloca, round up. We
9603 // don't do this for malloc, because some systems can't respect the request.
9604 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009605 if (AI->getAlignment() >= PrefAlign)
9606 Align = AI->getAlignment();
9607 else {
9608 AI->setAlignment(PrefAlign);
9609 Align = PrefAlign;
9610 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009611 }
9612 }
9613
9614 return Align;
9615}
9616
9617/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9618/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9619/// and it is more than the alignment of the ultimate object, see if we can
9620/// increase the alignment of the ultimate object, making this check succeed.
9621unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9622 unsigned PrefAlign) {
9623 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9624 sizeof(PrefAlign) * CHAR_BIT;
9625 APInt Mask = APInt::getAllOnesValue(BitWidth);
9626 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9627 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9628 unsigned TrailZ = KnownZero.countTrailingOnes();
9629 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9630
9631 if (PrefAlign > Align)
9632 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9633
9634 // We don't need to make any adjustment.
9635 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009636}
9637
Chris Lattnerf497b022008-01-13 23:50:23 +00009638Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009639 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009640 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009641 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009642 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009643
9644 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009645 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9646 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009647 return MI;
9648 }
9649
9650 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9651 // load/store.
9652 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9653 if (MemOpLength == 0) return 0;
9654
Chris Lattner37ac6082008-01-14 00:28:35 +00009655 // Source and destination pointer types are always "i8*" for intrinsic. See
9656 // if the size is something we can handle with a single primitive load/store.
9657 // A single load+store correctly handles overlapping memory in the memmove
9658 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009659 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009660 if (Size == 0) return MI; // Delete this mem transfer.
9661
9662 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009663 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009664
Chris Lattner37ac6082008-01-14 00:28:35 +00009665 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009666 Type *NewPtrTy =
9667 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009668
9669 // Memcpy forces the use of i8* for the source and destination. That means
9670 // that if you're using memcpy to move one double around, you'll get a cast
9671 // from double* to i8*. We'd much rather use a double load+store rather than
9672 // an i64 load+store, here because this improves the odds that the source or
9673 // dest address will be promotable. See if we can find a better type than the
9674 // integer datatype.
9675 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9676 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009677 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009678 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9679 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009680 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009681 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9682 if (STy->getNumElements() == 1)
9683 SrcETy = STy->getElementType(0);
9684 else
9685 break;
9686 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9687 if (ATy->getNumElements() == 1)
9688 SrcETy = ATy->getElementType();
9689 else
9690 break;
9691 } else
9692 break;
9693 }
9694
Dan Gohman8f8e2692008-05-23 01:52:21 +00009695 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009696 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009697 }
9698 }
9699
9700
Chris Lattnerf497b022008-01-13 23:50:23 +00009701 // If the memcpy/memmove provides better alignment info than we can
9702 // infer, use it.
9703 SrcAlign = std::max(SrcAlign, CopyAlign);
9704 DstAlign = std::max(DstAlign, CopyAlign);
9705
9706 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9707 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009708 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9709 InsertNewInstBefore(L, *MI);
9710 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9711
9712 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009713 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009714 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009715}
Chris Lattner3d69f462004-03-12 05:52:32 +00009716
Chris Lattner69ea9d22008-04-30 06:39:11 +00009717Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9718 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009719 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009720 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9721 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009722 return MI;
9723 }
9724
9725 // Extract the length and alignment and fill if they are constant.
9726 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9727 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9728 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9729 return 0;
9730 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009731 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009732
9733 // If the length is zero, this is a no-op
9734 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9735
9736 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9737 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009738 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009739
9740 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009741 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009742
9743 // Alignment 0 is identity for alignment 1 for memset, but not store.
9744 if (Alignment == 0) Alignment = 1;
9745
9746 // Extract the fill value and store.
9747 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009748 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9749 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009750
9751 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009752 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009753 return MI;
9754 }
9755
9756 return 0;
9757}
9758
9759
Chris Lattner8b0ea312006-01-13 20:11:04 +00009760/// visitCallInst - CallInst simplification. This mostly only handles folding
9761/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9762/// the heavy lifting.
9763///
Chris Lattner9fe38862003-06-19 17:00:31 +00009764Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009765 // If the caller function is nounwind, mark the call as nounwind, even if the
9766 // callee isn't.
9767 if (CI.getParent()->getParent()->doesNotThrow() &&
9768 !CI.doesNotThrow()) {
9769 CI.setDoesNotThrow();
9770 return &CI;
9771 }
9772
9773
9774
Chris Lattner8b0ea312006-01-13 20:11:04 +00009775 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9776 if (!II) return visitCallSite(&CI);
9777
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009778 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9779 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009780 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009781 bool Changed = false;
9782
9783 // memmove/cpy/set of zero bytes is a noop.
9784 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9785 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9786
Chris Lattner35b9e482004-10-12 04:52:52 +00009787 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009788 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009789 // Replace the instruction with just byte operations. We would
9790 // transform other cases to loads/stores, but we don't know if
9791 // alignment is sufficient.
9792 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009793 }
9794
Chris Lattner35b9e482004-10-12 04:52:52 +00009795 // If we have a memmove and the source operation is a constant global,
9796 // then the source and dest pointers can't alias, so we can change this
9797 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009798 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009799 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9800 if (GVSrc->isConstant()) {
9801 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009802 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9803 const Type *Tys[1];
9804 Tys[0] = CI.getOperand(3)->getType();
9805 CI.setOperand(0,
9806 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009807 Changed = true;
9808 }
Chris Lattnera935db82008-05-28 05:30:41 +00009809
9810 // memmove(x,x,size) -> noop.
9811 if (MMI->getSource() == MMI->getDest())
9812 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009813 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009814
Chris Lattner95a959d2006-03-06 20:18:44 +00009815 // If we can determine a pointer alignment that is bigger than currently
9816 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009817 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009818 if (Instruction *I = SimplifyMemTransfer(MI))
9819 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009820 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9821 if (Instruction *I = SimplifyMemSet(MSI))
9822 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009823 }
9824
Chris Lattner8b0ea312006-01-13 20:11:04 +00009825 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009826 }
9827
9828 switch (II->getIntrinsicID()) {
9829 default: break;
9830 case Intrinsic::bswap:
9831 // bswap(bswap(x)) -> x
9832 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9833 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9834 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9835 break;
9836 case Intrinsic::ppc_altivec_lvx:
9837 case Intrinsic::ppc_altivec_lvxl:
9838 case Intrinsic::x86_sse_loadu_ps:
9839 case Intrinsic::x86_sse2_loadu_pd:
9840 case Intrinsic::x86_sse2_loadu_dq:
9841 // Turn PPC lvx -> load if the pointer is known aligned.
9842 // Turn X86 loadups -> load if the pointer is known aligned.
9843 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9844 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009845 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009846 CI);
9847 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009848 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009849 break;
9850 case Intrinsic::ppc_altivec_stvx:
9851 case Intrinsic::ppc_altivec_stvxl:
9852 // Turn stvx -> store if the pointer is known aligned.
9853 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9854 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009855 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009856 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9857 return new StoreInst(II->getOperand(1), Ptr);
9858 }
9859 break;
9860 case Intrinsic::x86_sse_storeu_ps:
9861 case Intrinsic::x86_sse2_storeu_pd:
9862 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009863 // Turn X86 storeu -> store if the pointer is known aligned.
9864 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9865 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009866 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009867 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9868 return new StoreInst(II->getOperand(2), Ptr);
9869 }
9870 break;
9871
9872 case Intrinsic::x86_sse_cvttss2si: {
9873 // These intrinsics only demands the 0th element of its input vector. If
9874 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009875 unsigned VWidth =
9876 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9877 APInt DemandedElts(VWidth, 1);
9878 APInt UndefElts(VWidth, 0);
9879 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009880 UndefElts)) {
9881 II->setOperand(1, V);
9882 return II;
9883 }
9884 break;
9885 }
9886
9887 case Intrinsic::ppc_altivec_vperm:
9888 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9889 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9890 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009891
Chris Lattner0521e3c2008-06-18 04:33:20 +00009892 // Check that all of the elements are integer constants or undefs.
9893 bool AllEltsOk = true;
9894 for (unsigned i = 0; i != 16; ++i) {
9895 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9896 !isa<UndefValue>(Mask->getOperand(i))) {
9897 AllEltsOk = false;
9898 break;
9899 }
9900 }
9901
9902 if (AllEltsOk) {
9903 // Cast the input vectors to byte vectors.
9904 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9905 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009906 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009907
Chris Lattner0521e3c2008-06-18 04:33:20 +00009908 // Only extract each element once.
9909 Value *ExtractedElts[32];
9910 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9911
Chris Lattnere2ed0572006-04-06 19:19:17 +00009912 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009913 if (isa<UndefValue>(Mask->getOperand(i)))
9914 continue;
9915 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9916 Idx &= 31; // Match the hardware behavior.
9917
9918 if (ExtractedElts[Idx] == 0) {
9919 Instruction *Elt =
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009920 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9921 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009922 InsertNewInstBefore(Elt, CI);
9923 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009924 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009925
Chris Lattner0521e3c2008-06-18 04:33:20 +00009926 // Insert this value into the result vector.
9927 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009928 Context->getConstantInt(Type::Int32Ty, i, false),
9929 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009931 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009932 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009933 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009934 }
9935 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009936
Chris Lattner0521e3c2008-06-18 04:33:20 +00009937 case Intrinsic::stackrestore: {
9938 // If the save is right next to the restore, remove the restore. This can
9939 // happen when variable allocas are DCE'd.
9940 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9941 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9942 BasicBlock::iterator BI = SS;
9943 if (&*++BI == II)
9944 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009945 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009946 }
9947
9948 // Scan down this block to see if there is another stack restore in the
9949 // same block without an intervening call/alloca.
9950 BasicBlock::iterator BI = II;
9951 TerminatorInst *TI = II->getParent()->getTerminator();
9952 bool CannotRemove = false;
9953 for (++BI; &*BI != TI; ++BI) {
9954 if (isa<AllocaInst>(BI)) {
9955 CannotRemove = true;
9956 break;
9957 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009958 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9959 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9960 // If there is a stackrestore below this one, remove this one.
9961 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9962 return EraseInstFromFunction(CI);
9963 // Otherwise, ignore the intrinsic.
9964 } else {
9965 // If we found a non-intrinsic call, we can't remove the stack
9966 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009967 CannotRemove = true;
9968 break;
9969 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009970 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009971 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009972
9973 // If the stack restore is in a return/unwind block and if there are no
9974 // allocas or calls between the restore and the return, nuke the restore.
9975 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9976 return EraseInstFromFunction(CI);
9977 break;
9978 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009979 }
9980
Chris Lattner8b0ea312006-01-13 20:11:04 +00009981 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009982}
9983
9984// InvokeInst simplification
9985//
9986Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009987 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009988}
9989
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009990/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9991/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009992static bool isSafeToEliminateVarargsCast(const CallSite CS,
9993 const CastInst * const CI,
9994 const TargetData * const TD,
9995 const int ix) {
9996 if (!CI->isLosslessCast())
9997 return false;
9998
9999 // The size of ByVal arguments is derived from the type, so we
10000 // can't change to a type with a different size. If the size were
10001 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010002 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010003 return true;
10004
10005 const Type* SrcTy =
10006 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10007 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10008 if (!SrcTy->isSized() || !DstTy->isSized())
10009 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010010 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010011 return false;
10012 return true;
10013}
10014
Chris Lattnera44d8a22003-10-07 22:32:43 +000010015// visitCallSite - Improvements for call and invoke instructions.
10016//
10017Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010018 bool Changed = false;
10019
10020 // If the callee is a constexpr cast of a function, attempt to move the cast
10021 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010022 if (transformConstExprCastCall(CS)) return 0;
10023
Chris Lattner6c266db2003-10-07 22:54:13 +000010024 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010025
Chris Lattner08b22ec2005-05-13 07:09:09 +000010026 if (Function *CalleeF = dyn_cast<Function>(Callee))
10027 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10028 Instruction *OldCall = CS.getInstruction();
10029 // If the call and callee calling conventions don't match, this call must
10030 // be unreachable, as the call is undefined.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010031 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010032 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10033 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010034 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010035 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010036 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10037 return EraseInstFromFunction(*OldCall);
10038 return 0;
10039 }
10040
Chris Lattner17be6352004-10-18 02:59:09 +000010041 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10042 // This instruction is not reachable, just remove it. We insert a store to
10043 // undef so that we know that this code is not reachable, despite the fact
10044 // that we can't modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000010045 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010046 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010047 CS.getInstruction());
10048
10049 if (!CS.getInstruction()->use_empty())
10050 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010051 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010052
10053 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10054 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010055 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersonb3056fa2009-07-21 18:03:38 +000010056 Context->getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010057 }
Chris Lattner17be6352004-10-18 02:59:09 +000010058 return EraseInstFromFunction(*CS.getInstruction());
10059 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010060
Duncan Sandscdb6d922007-09-17 10:26:40 +000010061 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10062 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10063 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10064 return transformCallThroughTrampoline(CS);
10065
Chris Lattner6c266db2003-10-07 22:54:13 +000010066 const PointerType *PTy = cast<PointerType>(Callee->getType());
10067 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10068 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010069 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010070 // See if we can optimize any arguments passed through the varargs area of
10071 // the call.
10072 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010073 E = CS.arg_end(); I != E; ++I, ++ix) {
10074 CastInst *CI = dyn_cast<CastInst>(*I);
10075 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10076 *I = CI->getOperand(0);
10077 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010078 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010079 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010080 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010081
Duncan Sandsf0c33542007-12-19 21:13:37 +000010082 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010083 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010084 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010085 Changed = true;
10086 }
10087
Chris Lattner6c266db2003-10-07 22:54:13 +000010088 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010089}
10090
Chris Lattner9fe38862003-06-19 17:00:31 +000010091// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10092// attempt to move the cast to the arguments of the call/invoke.
10093//
10094bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10095 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10096 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010097 if (CE->getOpcode() != Instruction::BitCast ||
10098 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010099 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010100 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010101 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010102 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010103
10104 // Okay, this is a cast from a function to a different type. Unless doing so
10105 // would cause a type conversion of one of our arguments, change this call to
10106 // be a direct call with arguments casted to the appropriate types.
10107 //
10108 const FunctionType *FT = Callee->getFunctionType();
10109 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010110 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010111
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010112 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010113 return false; // TODO: Handle multiple return values.
10114
Chris Lattnerf78616b2004-01-14 06:06:08 +000010115 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010116 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010117 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010118 // Conversion is ok if changing from one pointer type to another or from
10119 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010120 !((isa<PointerType>(OldRetTy) || !TD ||
10121 OldRetTy == TD->getIntPtrType()) &&
10122 (isa<PointerType>(NewRetTy) || !TD ||
10123 NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010124 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010125
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010126 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010127 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010128 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010129 return false; // Cannot transform this return value.
10130
Chris Lattner58d74912008-03-12 17:45:29 +000010131 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010132 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010133 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010134 return false; // Attribute not compatible with transformed value.
10135 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010136
Chris Lattnerf78616b2004-01-14 06:06:08 +000010137 // If the callsite is an invoke instruction, and the return value is used by
10138 // a PHI node in a successor, we cannot change the return type of the call
10139 // because there is no place to put the cast instruction (without breaking
10140 // the critical edge). Bail out in this case.
10141 if (!Caller->use_empty())
10142 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10143 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10144 UI != E; ++UI)
10145 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10146 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010147 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010148 return false;
10149 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010150
10151 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10152 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010153
Chris Lattner9fe38862003-06-19 17:00:31 +000010154 CallSite::arg_iterator AI = CS.arg_begin();
10155 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10156 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010157 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010158
10159 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010160 return false; // Cannot transform this parameter value.
10161
Devang Patel19c87462008-09-26 22:53:05 +000010162 if (CallerPAL.getParamAttributes(i + 1)
10163 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010164 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010165
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010166 // Converting from one pointer type to another or between a pointer and an
10167 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010168 bool isConvertible = ActTy == ParamTy ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010169 (TD && ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10170 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType())));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010171 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010172 }
10173
10174 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010175 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010176 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010177
Chris Lattner58d74912008-03-12 17:45:29 +000010178 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10179 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010180 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010181 // won't be dropping them. Check that these extra arguments have attributes
10182 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010183 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10184 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010185 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010186 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010187 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010188 return false;
10189 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010190
Chris Lattner9fe38862003-06-19 17:00:31 +000010191 // Okay, we decided that this is a safe thing to do: go ahead and start
10192 // inserting cast instructions as necessary...
10193 std::vector<Value*> Args;
10194 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010195 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010196 attrVec.reserve(NumCommonArgs);
10197
10198 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010199 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010200
10201 // If the return value is not being used, the type may not be compatible
10202 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010203 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010204
10205 // Add the new return attributes.
10206 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010207 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010208
10209 AI = CS.arg_begin();
10210 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10211 const Type *ParamTy = FT->getParamType(i);
10212 if ((*AI)->getType() == ParamTy) {
10213 Args.push_back(*AI);
10214 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010215 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010216 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010217 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010218 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010219 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010220
10221 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010222 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010223 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010224 }
10225
10226 // If the function takes more arguments than the call was taking, add them
10227 // now...
10228 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010229 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010230
10231 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010232 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010233 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010234 cerr << "WARNING: While resolving call to function '"
10235 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010236 } else {
10237 // Add all of the arguments in their promoted form to the arg list...
10238 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10239 const Type *PTy = getPromotedType((*AI)->getType());
10240 if (PTy != (*AI)->getType()) {
10241 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010242 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10243 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010244 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010245 InsertNewInstBefore(Cast, *Caller);
10246 Args.push_back(Cast);
10247 } else {
10248 Args.push_back(*AI);
10249 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010250
Duncan Sandse1e520f2008-01-13 08:02:44 +000010251 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010252 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010253 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010254 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010255 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010256 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010257
Devang Patel19c87462008-09-26 22:53:05 +000010258 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10259 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10260
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010261 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010262 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010263
Devang Patel05988662008-09-25 21:00:45 +000010264 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010265
Chris Lattner9fe38862003-06-19 17:00:31 +000010266 Instruction *NC;
10267 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010268 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010269 Args.begin(), Args.end(),
10270 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010271 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010272 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010273 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010274 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10275 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010276 CallInst *CI = cast<CallInst>(Caller);
10277 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010278 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010279 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010280 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010281 }
10282
Chris Lattner6934a042007-02-11 01:23:03 +000010283 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010284 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010285 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010286 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010287 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010288 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010289 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010290
10291 // If this is an invoke instruction, we should insert it after the first
10292 // non-phi, instruction in the normal successor block.
10293 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010294 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010295 InsertNewInstBefore(NC, *I);
10296 } else {
10297 // Otherwise, it's a call, just insert cast right after the call instr
10298 InsertNewInstBefore(NC, *Caller);
10299 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010300 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010301 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010302 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010303 }
10304 }
10305
10306 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10307 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010308 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010309 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010310 return true;
10311}
10312
Duncan Sandscdb6d922007-09-17 10:26:40 +000010313// transformCallThroughTrampoline - Turn a call to a function created by the
10314// init_trampoline intrinsic into a direct call to the underlying function.
10315//
10316Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10317 Value *Callee = CS.getCalledValue();
10318 const PointerType *PTy = cast<PointerType>(Callee->getType());
10319 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010320 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010321
10322 // If the call already has the 'nest' attribute somewhere then give up -
10323 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010324 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010325 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010326
10327 IntrinsicInst *Tramp =
10328 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10329
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010330 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010331 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10332 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10333
Devang Patel05988662008-09-25 21:00:45 +000010334 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010335 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010336 unsigned NestIdx = 1;
10337 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010338 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010339
10340 // Look for a parameter marked with the 'nest' attribute.
10341 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10342 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010343 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010344 // Record the parameter type and any other attributes.
10345 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010346 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010347 break;
10348 }
10349
10350 if (NestTy) {
10351 Instruction *Caller = CS.getInstruction();
10352 std::vector<Value*> NewArgs;
10353 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10354
Devang Patel05988662008-09-25 21:00:45 +000010355 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010356 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010357
Duncan Sandscdb6d922007-09-17 10:26:40 +000010358 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010359 // mean appending it. Likewise for attributes.
10360
Devang Patel19c87462008-09-26 22:53:05 +000010361 // Add any result attributes.
10362 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010363 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010364
Duncan Sandscdb6d922007-09-17 10:26:40 +000010365 {
10366 unsigned Idx = 1;
10367 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10368 do {
10369 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010370 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010371 Value *NestVal = Tramp->getOperand(3);
10372 if (NestVal->getType() != NestTy)
10373 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10374 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010375 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 }
10377
10378 if (I == E)
10379 break;
10380
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010381 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010382 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010383 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010384 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010385 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386
10387 ++Idx, ++I;
10388 } while (1);
10389 }
10390
Devang Patel19c87462008-09-26 22:53:05 +000010391 // Add any function attributes.
10392 if (Attributes Attr = Attrs.getFnAttributes())
10393 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10394
Duncan Sandscdb6d922007-09-17 10:26:40 +000010395 // The trampoline may have been bitcast to a bogus type (FTy).
10396 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010397 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010398
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010400 NewTypes.reserve(FTy->getNumParams()+1);
10401
Duncan Sandscdb6d922007-09-17 10:26:40 +000010402 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010403 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010404 {
10405 unsigned Idx = 1;
10406 FunctionType::param_iterator I = FTy->param_begin(),
10407 E = FTy->param_end();
10408
10409 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010410 if (Idx == NestIdx)
10411 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010412 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010413
10414 if (I == E)
10415 break;
10416
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010417 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010418 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010419
10420 ++Idx, ++I;
10421 } while (1);
10422 }
10423
10424 // Replace the trampoline call with a direct call. Let the generic
10425 // code sort out any function type mismatches.
10426 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010427 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10428 FTy->isVarArg());
10429 Constant *NewCallee =
10430 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10431 NestF : Context->getConstantExprBitCast(NestF,
10432 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010433 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010434
10435 Instruction *NewCaller;
10436 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010437 NewCaller = InvokeInst::Create(NewCallee,
10438 II->getNormalDest(), II->getUnwindDest(),
10439 NewArgs.begin(), NewArgs.end(),
10440 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010441 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010442 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010443 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010444 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10445 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010446 if (cast<CallInst>(Caller)->isTailCall())
10447 cast<CallInst>(NewCaller)->setTailCall();
10448 cast<CallInst>(NewCaller)->
10449 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010450 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010451 }
10452 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10453 Caller->replaceAllUsesWith(NewCaller);
10454 Caller->eraseFromParent();
10455 RemoveFromWorkList(Caller);
10456 return 0;
10457 }
10458 }
10459
10460 // Replace the trampoline call with a direct call. Since there is no 'nest'
10461 // parameter, there is no need to adjust the argument list. Let the generic
10462 // code sort out any function type mismatches.
10463 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010464 NestF->getType() == PTy ? NestF :
10465 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010466 CS.setCalledFunction(NewCallee);
10467 return CS.getInstruction();
10468}
10469
Chris Lattner7da52b22006-11-01 04:51:18 +000010470/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10471/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10472/// and a single binop.
10473Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10474 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010475 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010476 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010477 Value *LHSVal = FirstInst->getOperand(0);
10478 Value *RHSVal = FirstInst->getOperand(1);
10479
10480 const Type *LHSType = LHSVal->getType();
10481 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010482
10483 // Scan to see if all operands are the same opcode, all have one use, and all
10484 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010485 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010486 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010487 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010488 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010489 // types or GEP's with different index types.
10490 I->getOperand(0)->getType() != LHSType ||
10491 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010492 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010493
10494 // If they are CmpInst instructions, check their predicates
10495 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10496 if (cast<CmpInst>(I)->getPredicate() !=
10497 cast<CmpInst>(FirstInst)->getPredicate())
10498 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010499
10500 // Keep track of which operand needs a phi node.
10501 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10502 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010503 }
10504
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010505 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010506
Chris Lattner7da52b22006-11-01 04:51:18 +000010507 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010508 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010509 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010510 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010511 NewLHS = PHINode::Create(LHSType,
10512 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010513 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10514 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010515 InsertNewInstBefore(NewLHS, PN);
10516 LHSVal = NewLHS;
10517 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010518
10519 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010520 NewRHS = PHINode::Create(RHSType,
10521 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010522 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10523 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010524 InsertNewInstBefore(NewRHS, PN);
10525 RHSVal = NewRHS;
10526 }
10527
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010528 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010529 if (NewLHS || NewRHS) {
10530 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10531 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10532 if (NewLHS) {
10533 Value *NewInLHS = InInst->getOperand(0);
10534 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10535 }
10536 if (NewRHS) {
10537 Value *NewInRHS = InInst->getOperand(1);
10538 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10539 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010540 }
10541 }
10542
Chris Lattner7da52b22006-11-01 04:51:18 +000010543 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010544 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010545 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010546 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10547 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010548}
10549
Chris Lattner05f18922008-12-01 02:34:36 +000010550Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10551 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10552
10553 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10554 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010555 // This is true if all GEP bases are allocas and if all indices into them are
10556 // constants.
10557 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010558
10559 // Scan to see if all operands are the same opcode, all have one use, and all
10560 // kill their operands (i.e. the operands have one use).
10561 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10562 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10563 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10564 GEP->getNumOperands() != FirstInst->getNumOperands())
10565 return 0;
10566
Chris Lattner36d3e322009-02-21 00:46:50 +000010567 // Keep track of whether or not all GEPs are of alloca pointers.
10568 if (AllBasePointersAreAllocas &&
10569 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10570 !GEP->hasAllConstantIndices()))
10571 AllBasePointersAreAllocas = false;
10572
Chris Lattner05f18922008-12-01 02:34:36 +000010573 // Compare the operand lists.
10574 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10575 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10576 continue;
10577
10578 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10579 // if one of the PHIs has a constant for the index. The index may be
10580 // substantially cheaper to compute for the constants, so making it a
10581 // variable index could pessimize the path. This also handles the case
10582 // for struct indices, which must always be constant.
10583 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10584 isa<ConstantInt>(GEP->getOperand(op)))
10585 return 0;
10586
10587 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10588 return 0;
10589 FixedOperands[op] = 0; // Needs a PHI.
10590 }
10591 }
10592
Chris Lattner36d3e322009-02-21 00:46:50 +000010593 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010594 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010595 // offset calculation, but all the predecessors will have to materialize the
10596 // stack address into a register anyway. We'd actually rather *clone* the
10597 // load up into the predecessors so that we have a load of a gep of an alloca,
10598 // which can usually all be folded into the load.
10599 if (AllBasePointersAreAllocas)
10600 return 0;
10601
Chris Lattner05f18922008-12-01 02:34:36 +000010602 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10603 // that is variable.
10604 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10605
10606 bool HasAnyPHIs = false;
10607 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10608 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10609 Value *FirstOp = FirstInst->getOperand(i);
10610 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10611 FirstOp->getName()+".pn");
10612 InsertNewInstBefore(NewPN, PN);
10613
10614 NewPN->reserveOperandSpace(e);
10615 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10616 OperandPhis[i] = NewPN;
10617 FixedOperands[i] = NewPN;
10618 HasAnyPHIs = true;
10619 }
10620
10621
10622 // Add all operands to the new PHIs.
10623 if (HasAnyPHIs) {
10624 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10625 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10626 BasicBlock *InBB = PN.getIncomingBlock(i);
10627
10628 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10629 if (PHINode *OpPhi = OperandPhis[op])
10630 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10631 }
10632 }
10633
10634 Value *Base = FixedOperands[0];
10635 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10636 FixedOperands.end());
10637}
10638
10639
Chris Lattner21550882009-02-23 05:56:17 +000010640/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10641/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010642/// obvious the value of the load is not changed from the point of the load to
10643/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010644///
10645/// Finally, it is safe, but not profitable, to sink a load targetting a
10646/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10647/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010648static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010649 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10650
10651 for (++BBI; BBI != E; ++BBI)
10652 if (BBI->mayWriteToMemory())
10653 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010654
10655 // Check for non-address taken alloca. If not address-taken already, it isn't
10656 // profitable to do this xform.
10657 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10658 bool isAddressTaken = false;
10659 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10660 UI != E; ++UI) {
10661 if (isa<LoadInst>(UI)) continue;
10662 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10663 // If storing TO the alloca, then the address isn't taken.
10664 if (SI->getOperand(1) == AI) continue;
10665 }
10666 isAddressTaken = true;
10667 break;
10668 }
10669
Chris Lattner36d3e322009-02-21 00:46:50 +000010670 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010671 return false;
10672 }
10673
Chris Lattner36d3e322009-02-21 00:46:50 +000010674 // If this load is a load from a GEP with a constant offset from an alloca,
10675 // then we don't want to sink it. In its present form, it will be
10676 // load [constant stack offset]. Sinking it will cause us to have to
10677 // materialize the stack addresses in each predecessor in a register only to
10678 // do a shared load from register in the successor.
10679 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10680 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10681 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10682 return false;
10683
Chris Lattner76c73142006-11-01 07:13:54 +000010684 return true;
10685}
10686
Chris Lattner9fe38862003-06-19 17:00:31 +000010687
Chris Lattnerbac32862004-11-14 19:13:23 +000010688// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10689// operator and they all are only used by the PHI, PHI together their
10690// inputs, and do the operation once, to the result of the PHI.
10691Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10692 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10693
10694 // Scan the instruction, looking for input operations that can be folded away.
10695 // If all input operands to the phi are the same instruction (e.g. a cast from
10696 // the same type or "+42") we can pull the operation through the PHI, reducing
10697 // code size and simplifying code.
10698 Constant *ConstantOp = 0;
10699 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010700 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010701 if (isa<CastInst>(FirstInst)) {
10702 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010703 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010704 // Can fold binop, compare or shift here if the RHS is a constant,
10705 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010706 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010707 if (ConstantOp == 0)
10708 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010709 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10710 isVolatile = LI->isVolatile();
10711 // We can't sink the load if the loaded value could be modified between the
10712 // load and the PHI.
10713 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010714 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010715 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010716
10717 // If the PHI is of volatile loads and the load block has multiple
10718 // successors, sinking it would remove a load of the volatile value from
10719 // the path through the other successor.
10720 if (isVolatile &&
10721 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10722 return 0;
10723
Chris Lattner9c080502006-11-01 07:43:41 +000010724 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010725 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010726 } else {
10727 return 0; // Cannot fold this operation.
10728 }
10729
10730 // Check to see if all arguments are the same operation.
10731 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10732 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10733 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010734 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010735 return 0;
10736 if (CastSrcTy) {
10737 if (I->getOperand(0)->getType() != CastSrcTy)
10738 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010739 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010740 // We can't sink the load if the loaded value could be modified between
10741 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010742 if (LI->isVolatile() != isVolatile ||
10743 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010744 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010745 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010746
Chris Lattner71042962008-07-08 17:18:32 +000010747 // If the PHI is of volatile loads and the load block has multiple
10748 // successors, sinking it would remove a load of the volatile value from
10749 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010750 if (isVolatile &&
10751 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10752 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010753
Chris Lattnerbac32862004-11-14 19:13:23 +000010754 } else if (I->getOperand(1) != ConstantOp) {
10755 return 0;
10756 }
10757 }
10758
10759 // Okay, they are all the same operation. Create a new PHI node of the
10760 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010761 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10762 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010763 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010764
10765 Value *InVal = FirstInst->getOperand(0);
10766 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010767
10768 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010769 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10770 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10771 if (NewInVal != InVal)
10772 InVal = 0;
10773 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10774 }
10775
10776 Value *PhiVal;
10777 if (InVal) {
10778 // The new PHI unions all of the same values together. This is really
10779 // common, so we handle it intelligently here for compile-time speed.
10780 PhiVal = InVal;
10781 delete NewPN;
10782 } else {
10783 InsertNewInstBefore(NewPN, PN);
10784 PhiVal = NewPN;
10785 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010786
Chris Lattnerbac32862004-11-14 19:13:23 +000010787 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010788 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010789 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010790 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010791 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010792 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010793 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010794 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010795 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10796
10797 // If this was a volatile load that we are merging, make sure to loop through
10798 // and mark all the input loads as non-volatile. If we don't do this, we will
10799 // insert a new volatile load and the old ones will not be deletable.
10800 if (isVolatile)
10801 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10802 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10803
10804 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010805}
Chris Lattnera1be5662002-05-02 17:06:02 +000010806
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010807/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10808/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010809static bool DeadPHICycle(PHINode *PN,
10810 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010811 if (PN->use_empty()) return true;
10812 if (!PN->hasOneUse()) return false;
10813
10814 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010815 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010816 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010817
10818 // Don't scan crazily complex things.
10819 if (PotentiallyDeadPHIs.size() == 16)
10820 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010821
10822 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10823 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010824
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010825 return false;
10826}
10827
Chris Lattnercf5008a2007-11-06 21:52:06 +000010828/// PHIsEqualValue - Return true if this phi node is always equal to
10829/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10830/// z = some value; x = phi (y, z); y = phi (x, z)
10831static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10832 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10833 // See if we already saw this PHI node.
10834 if (!ValueEqualPHIs.insert(PN))
10835 return true;
10836
10837 // Don't scan crazily complex things.
10838 if (ValueEqualPHIs.size() == 16)
10839 return false;
10840
10841 // Scan the operands to see if they are either phi nodes or are equal to
10842 // the value.
10843 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10844 Value *Op = PN->getIncomingValue(i);
10845 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10846 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10847 return false;
10848 } else if (Op != NonPhiInVal)
10849 return false;
10850 }
10851
10852 return true;
10853}
10854
10855
Chris Lattner473945d2002-05-06 18:06:38 +000010856// PHINode simplification
10857//
Chris Lattner7e708292002-06-25 16:13:24 +000010858Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010859 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010860 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010861
Owen Anderson7e057142006-07-10 22:03:18 +000010862 if (Value *V = PN.hasConstantValue())
10863 return ReplaceInstUsesWith(PN, V);
10864
Owen Anderson7e057142006-07-10 22:03:18 +000010865 // If all PHI operands are the same operation, pull them through the PHI,
10866 // reducing code size.
10867 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010868 isa<Instruction>(PN.getIncomingValue(1)) &&
10869 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10870 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10871 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10872 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010873 PN.getIncomingValue(0)->hasOneUse())
10874 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10875 return Result;
10876
10877 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10878 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10879 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010880 if (PN.hasOneUse()) {
10881 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10882 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010883 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010884 PotentiallyDeadPHIs.insert(&PN);
10885 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010886 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010887 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010888
10889 // If this phi has a single use, and if that use just computes a value for
10890 // the next iteration of a loop, delete the phi. This occurs with unused
10891 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10892 // common case here is good because the only other things that catch this
10893 // are induction variable analysis (sometimes) and ADCE, which is only run
10894 // late.
10895 if (PHIUser->hasOneUse() &&
10896 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10897 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010898 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010899 }
10900 }
Owen Anderson7e057142006-07-10 22:03:18 +000010901
Chris Lattnercf5008a2007-11-06 21:52:06 +000010902 // We sometimes end up with phi cycles that non-obviously end up being the
10903 // same value, for example:
10904 // z = some value; x = phi (y, z); y = phi (x, z)
10905 // where the phi nodes don't necessarily need to be in the same block. Do a
10906 // quick check to see if the PHI node only contains a single non-phi value, if
10907 // so, scan to see if the phi cycle is actually equal to that value.
10908 {
10909 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10910 // Scan for the first non-phi operand.
10911 while (InValNo != NumOperandVals &&
10912 isa<PHINode>(PN.getIncomingValue(InValNo)))
10913 ++InValNo;
10914
10915 if (InValNo != NumOperandVals) {
10916 Value *NonPhiInVal = PN.getOperand(InValNo);
10917
10918 // Scan the rest of the operands to see if there are any conflicts, if so
10919 // there is no need to recursively scan other phis.
10920 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10921 Value *OpVal = PN.getIncomingValue(InValNo);
10922 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10923 break;
10924 }
10925
10926 // If we scanned over all operands, then we have one unique value plus
10927 // phi values. Scan PHI nodes to see if they all merge in each other or
10928 // the value.
10929 if (InValNo == NumOperandVals) {
10930 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10931 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10932 return ReplaceInstUsesWith(PN, NonPhiInVal);
10933 }
10934 }
10935 }
Chris Lattner60921c92003-12-19 05:58:40 +000010936 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010937}
10938
Reid Spencer17212df2006-12-12 09:18:51 +000010939static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10940 Instruction *InsertPoint,
10941 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010942 unsigned PtrSize = DTy->getScalarSizeInBits();
10943 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010944 // We must cast correctly to the pointer type. Ensure that we
10945 // sign extend the integer value if it is smaller as this is
10946 // used for address computation.
10947 Instruction::CastOps opcode =
10948 (VTySize < PtrSize ? Instruction::SExt :
10949 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10950 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010951}
10952
Chris Lattnera1be5662002-05-02 17:06:02 +000010953
Chris Lattner7e708292002-06-25 16:13:24 +000010954Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010955 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010956 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010957 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010958 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010959 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010960
Chris Lattnere87597f2004-10-16 18:11:37 +000010961 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000010962 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010963
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010964 bool HasZeroPointerIndex = false;
10965 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10966 HasZeroPointerIndex = C->isNullValue();
10967
10968 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010969 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010970
Chris Lattner28977af2004-04-05 01:30:19 +000010971 // Eliminate unneeded casts for indices.
10972 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010973
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010974 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010975 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10976 i != e; ++i, ++GTI) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010977 if (TD && isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010978 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010979 if (CI->getOpcode() == Instruction::ZExt ||
10980 CI->getOpcode() == Instruction::SExt) {
10981 const Type *SrcTy = CI->getOperand(0)->getType();
10982 // We can eliminate a cast from i32 to i64 iff the target
10983 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000010984 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010985 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010986 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010987 }
10988 }
10989 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010990 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010991 // to what we need. If narrower, sign-extend it to what we need.
10992 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010993 // insert it. This explicit cast can make subsequent optimizations more
10994 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010995 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010996 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010997 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010998 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010999 MadeChange = true;
11000 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011001 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11002 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011003 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011004 MadeChange = true;
11005 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011006 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11007 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011008 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011009 MadeChange = true;
11010 } else {
11011 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11012 GEP);
11013 *i = Op;
11014 MadeChange = true;
11015 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011016 }
Chris Lattner28977af2004-04-05 01:30:19 +000011017 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011018 }
Chris Lattner28977af2004-04-05 01:30:19 +000011019 if (MadeChange) return &GEP;
11020
Chris Lattner90ac28c2002-08-02 19:29:35 +000011021 // Combine Indices - If the source pointer to this getelementptr instruction
11022 // is a getelementptr instruction, combine the indices of the two
11023 // getelementptr instructions into a single instruction.
11024 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011025 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011026 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011027 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011028
11029 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011030 // Note that if our source is a gep chain itself that we wait for that
11031 // chain to be resolved before we perform this transformation. This
11032 // avoids us creating a TON of code in some cases.
11033 //
11034 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11035 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11036 return 0; // Wait until our source is folded to completion.
11037
Chris Lattner72588fc2007-02-15 22:48:32 +000011038 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011039
11040 // Find out whether the last index in the source GEP is a sequential idx.
11041 bool EndsWithSequential = false;
11042 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11043 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011044 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011045
Chris Lattner90ac28c2002-08-02 19:29:35 +000011046 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011047 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011048 // Replace: gep (gep %P, long B), long A, ...
11049 // With: T = long A+B; gep %P, T, ...
11050 //
Chris Lattner620ce142004-05-07 22:09:22 +000011051 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011052 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011053 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011054 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011055 Sum = SO1;
11056 } else {
11057 // If they aren't the same type, convert both to an integer of the
11058 // target's pointer size.
11059 if (SO1->getType() != GO1->getType()) {
11060 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011061 SO1 =
11062 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011063 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011064 GO1 =
11065 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011066 } else if (TD) {
Duncan Sands514ab342007-11-01 20:53:16 +000011067 unsigned PS = TD->getPointerSizeInBits();
11068 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011069 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011070 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011071
Duncan Sands514ab342007-11-01 20:53:16 +000011072 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011073 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011074 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011075 } else {
11076 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011077 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11078 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011079 }
11080 }
11081 }
Chris Lattner620ce142004-05-07 22:09:22 +000011082 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011083 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11084 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011085 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011086 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011087 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011088 }
Chris Lattner28977af2004-04-05 01:30:19 +000011089 }
Chris Lattner620ce142004-05-07 22:09:22 +000011090
11091 // Recycle the GEP we already have if possible.
11092 if (SrcGEPOperands.size() == 2) {
11093 GEP.setOperand(0, SrcGEPOperands[0]);
11094 GEP.setOperand(1, Sum);
11095 return &GEP;
11096 } else {
11097 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11098 SrcGEPOperands.end()-1);
11099 Indices.push_back(Sum);
11100 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11101 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011102 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011103 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011104 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011105 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011106 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11107 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011108 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11109 }
11110
11111 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011112 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11113 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011114
Chris Lattner620ce142004-05-07 22:09:22 +000011115 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011116 // GEP of global variable. If all of the indices for this GEP are
11117 // constants, we can promote this to a constexpr instead of an instruction.
11118
11119 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011120 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011121 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11122 for (; I != E && isa<Constant>(*I); ++I)
11123 Indices.push_back(cast<Constant>(*I));
11124
11125 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011126 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011127 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011128
11129 // Replace all uses of the GEP with the new constexpr...
11130 return ReplaceInstUsesWith(GEP, CE);
11131 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011132 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011133 if (!isa<PointerType>(X->getType())) {
11134 // Not interesting. Source pointer must be a cast from pointer.
11135 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011136 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11137 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011138 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011139 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11140 // into : GEP i8* X, ...
11141 //
Chris Lattnereed48272005-09-13 00:40:14 +000011142 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011143 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11144 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011145 if (const ArrayType *CATy =
11146 dyn_cast<ArrayType>(CPTy->getElementType())) {
11147 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11148 if (CATy->getElementType() == XTy->getElementType()) {
11149 // -> GEP i8* X, ...
11150 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11151 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11152 GEP.getName());
11153 } else if (const ArrayType *XATy =
11154 dyn_cast<ArrayType>(XTy->getElementType())) {
11155 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011156 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011157 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011158 // At this point, we know that the cast source type is a pointer
11159 // to an array of the same type as the destination pointer
11160 // array. Because the array type is never stepped over (there
11161 // is a leading zero) we can fold the cast into this GEP.
11162 GEP.setOperand(0, X);
11163 return &GEP;
11164 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011165 }
11166 }
Chris Lattnereed48272005-09-13 00:40:14 +000011167 } else if (GEP.getNumOperands() == 2) {
11168 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011169 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11170 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011171 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11172 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011173 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011174 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11175 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011176 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011177 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011178 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011179 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011180 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011181 // V and GEP are both pointer types --> BitCast
11182 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011183 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011184
11185 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011186 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011187 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011188 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011189
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011190 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011191 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011192 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011193
11194 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11195 // allow either a mul, shift, or constant here.
11196 Value *NewIdx = 0;
11197 ConstantInt *Scale = 0;
11198 if (ArrayEltSize == 1) {
11199 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011200 Scale =
11201 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011202 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011203 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011204 Scale = CI;
11205 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11206 if (Inst->getOpcode() == Instruction::Shl &&
11207 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011208 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11209 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011210 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011211 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011212 NewIdx = Inst->getOperand(0);
11213 } else if (Inst->getOpcode() == Instruction::Mul &&
11214 isa<ConstantInt>(Inst->getOperand(1))) {
11215 Scale = cast<ConstantInt>(Inst->getOperand(1));
11216 NewIdx = Inst->getOperand(0);
11217 }
11218 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011219
Chris Lattner7835cdd2005-09-13 18:36:04 +000011220 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011221 // out, perform the transformation. Note, we don't know whether Scale is
11222 // signed or not. We'll use unsigned version of division/modulo
11223 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011224 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011225 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011226 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011227 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011228 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011229 Constant *C =
11230 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011231 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011232 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011233 NewIdx = InsertNewInstBefore(Sc, GEP);
11234 }
11235
11236 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011237 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011238 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011239 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011240 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011241 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011242 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11243 // The NewGEP must be pointer typed, so must the old one -> BitCast
11244 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011245 }
11246 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011247 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011248 }
Chris Lattner58407792009-01-09 04:53:57 +000011249
Chris Lattner46cd5a12009-01-09 05:44:56 +000011250 /// See if we can simplify:
11251 /// X = bitcast A to B*
11252 /// Y = gep X, <...constant indices...>
11253 /// into a gep of the original struct. This is important for SROA and alias
11254 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011255 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011256 if (TD &&
11257 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011258 // Determine how much the GEP moves the pointer. We are guaranteed to get
11259 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011260 ConstantInt *OffsetV =
11261 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011262 int64_t Offset = OffsetV->getSExtValue();
11263
11264 // If this GEP instruction doesn't move the pointer, just replace the GEP
11265 // with a bitcast of the real input to the dest type.
11266 if (Offset == 0) {
11267 // If the bitcast is of an allocation, and the allocation will be
11268 // converted to match the type of the cast, don't touch this.
11269 if (isa<AllocationInst>(BCI->getOperand(0))) {
11270 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11271 if (Instruction *I = visitBitCast(*BCI)) {
11272 if (I != BCI) {
11273 I->takeName(BCI);
11274 BCI->getParent()->getInstList().insert(BCI, I);
11275 ReplaceInstUsesWith(*BCI, I);
11276 }
11277 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011278 }
Chris Lattner58407792009-01-09 04:53:57 +000011279 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011280 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011281 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011282
11283 // Otherwise, if the offset is non-zero, we need to find out if there is a
11284 // field at Offset in 'A's type. If so, we can pull the cast through the
11285 // GEP.
11286 SmallVector<Value*, 8> NewIndices;
11287 const Type *InTy =
11288 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011289 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011290 Instruction *NGEP =
11291 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11292 NewIndices.end());
11293 if (NGEP->getType() == GEP.getType()) return NGEP;
11294 InsertNewInstBefore(NGEP, GEP);
11295 NGEP->takeName(&GEP);
11296 return new BitCastInst(NGEP, GEP.getType());
11297 }
Chris Lattner58407792009-01-09 04:53:57 +000011298 }
11299 }
11300
Chris Lattner8a2a3112001-12-14 16:52:21 +000011301 return 0;
11302}
11303
Chris Lattner0864acf2002-11-04 16:18:53 +000011304Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11305 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011306 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011307 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11308 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011309 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011310 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011311
11312 // Create and insert the replacement instruction...
11313 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011314 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011315 else {
11316 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011317 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011318 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011319
11320 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011321
Chris Lattner0864acf2002-11-04 16:18:53 +000011322 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011323 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011324 //
11325 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011326 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011327
11328 // Now that I is pointing to the first non-allocation-inst in the block,
11329 // insert our getelementptr instruction...
11330 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011331 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011332 Value *Idx[2];
11333 Idx[0] = NullIdx;
11334 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011335 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11336 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011337
11338 // Now make everything use the getelementptr instead of the original
11339 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011340 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011341 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011342 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011343 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011344 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011345
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011346 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011347 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011348 // Note that we only do this for alloca's, because malloc should allocate
11349 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011350 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011351 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011352
11353 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11354 if (AI.getAlignment() == 0)
11355 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11356 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011357
Chris Lattner0864acf2002-11-04 16:18:53 +000011358 return 0;
11359}
11360
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011361Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11362 Value *Op = FI.getOperand(0);
11363
Chris Lattner17be6352004-10-18 02:59:09 +000011364 // free undef -> unreachable.
11365 if (isa<UndefValue>(Op)) {
11366 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersonb3056fa2009-07-21 18:03:38 +000011367 new StoreInst(Context->getTrue(),
Owen Andersond672ecb2009-07-03 00:17:18 +000011368 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011369 return EraseInstFromFunction(FI);
11370 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011371
Chris Lattner6160e852004-02-28 04:57:37 +000011372 // If we have 'free null' delete the instruction. This can happen in stl code
11373 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011374 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011375 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011376
11377 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11378 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11379 FI.setOperand(0, CI->getOperand(0));
11380 return &FI;
11381 }
11382
11383 // Change free (gep X, 0,0,0,0) into free(X)
11384 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11385 if (GEPI->hasAllZeroIndices()) {
11386 AddToWorkList(GEPI);
11387 FI.setOperand(0, GEPI->getOperand(0));
11388 return &FI;
11389 }
11390 }
11391
11392 // Change free(malloc) into nothing, if the malloc has a single use.
11393 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11394 if (MI->hasOneUse()) {
11395 EraseInstFromFunction(FI);
11396 return EraseInstFromFunction(*MI);
11397 }
Chris Lattner6160e852004-02-28 04:57:37 +000011398
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011399 return 0;
11400}
11401
11402
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011403/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011404static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011405 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011406 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011407 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011408 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011409
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011410 if (TD) {
11411 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11412 // Instead of loading constant c string, use corresponding integer value
11413 // directly if string length is small enough.
11414 std::string Str;
11415 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11416 unsigned len = Str.length();
11417 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11418 unsigned numBits = Ty->getPrimitiveSizeInBits();
11419 // Replace LI with immediate integer store.
11420 if ((numBits >> 3) == len + 1) {
11421 APInt StrVal(numBits, 0);
11422 APInt SingleChar(numBits, 0);
11423 if (TD->isLittleEndian()) {
11424 for (signed i = len-1; i >= 0; i--) {
11425 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11426 StrVal = (StrVal << 8) | SingleChar;
11427 }
11428 } else {
11429 for (unsigned i = 0; i < len; i++) {
11430 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11431 StrVal = (StrVal << 8) | SingleChar;
11432 }
11433 // Append NULL at the end.
11434 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011435 StrVal = (StrVal << 8) | SingleChar;
11436 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011437 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011438 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011439 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011440 }
11441 }
11442 }
11443
Mon P Wang6753f952009-02-07 22:19:29 +000011444 const PointerType *DestTy = cast<PointerType>(CI->getType());
11445 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011446 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011447
11448 // If the address spaces don't match, don't eliminate the cast.
11449 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11450 return 0;
11451
Chris Lattnerb89e0712004-07-13 01:49:43 +000011452 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011453
Reid Spencer42230162007-01-22 05:51:25 +000011454 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011455 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011456 // If the source is an array, the code below will not succeed. Check to
11457 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11458 // constants.
11459 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11460 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11461 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011462 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011463 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11464 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011465 SrcTy = cast<PointerType>(CastOp->getType());
11466 SrcPTy = SrcTy->getElementType();
11467 }
11468
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011469 if (IC.getTargetData() &&
11470 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011471 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011472 // Do not allow turning this into a load of an integer, which is then
11473 // casted to a pointer, this pessimizes pointer analysis a lot.
11474 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011475 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11476 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011477
Chris Lattnerf9527852005-01-31 04:50:46 +000011478 // Okay, we are casting from one integer or pointer type to another of
11479 // the same size. Instead of casting the pointer before the load, cast
11480 // the result of the loaded value.
11481 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11482 CI->getName(),
11483 LI.isVolatile()),LI);
11484 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011485 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011486 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011487 }
11488 }
11489 return 0;
11490}
11491
Chris Lattner833b8a42003-06-26 05:06:25 +000011492Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11493 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011494
Dan Gohman9941f742007-07-20 16:34:21 +000011495 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011496 if (TD) {
11497 unsigned KnownAlign =
11498 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11499 if (KnownAlign >
11500 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11501 LI.getAlignment()))
11502 LI.setAlignment(KnownAlign);
11503 }
Dan Gohman9941f742007-07-20 16:34:21 +000011504
Chris Lattner37366c12005-05-01 04:24:53 +000011505 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011506 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011507 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011508 return Res;
11509
11510 // None of the following transforms are legal for volatile loads.
11511 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011512
Dan Gohman2276a7b2008-10-15 23:19:35 +000011513 // Do really simple store-to-load forwarding and load CSE, to catch cases
11514 // where there are several consequtive memory accesses to the same location,
11515 // separated by a few arithmetic operations.
11516 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011517 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11518 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011519
Christopher Lambb15147e2007-12-29 07:56:53 +000011520 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11521 const Value *GEPI0 = GEPI->getOperand(0);
11522 // TODO: Consider a target hook for valid address spaces for this xform.
11523 if (isa<ConstantPointerNull>(GEPI0) &&
11524 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011525 // Insert a new store to null instruction before the load to indicate
11526 // that this code is not reachable. We do this instead of inserting
11527 // an unreachable instruction directly because we cannot modify the
11528 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011529 new StoreInst(Context->getUndef(LI.getType()),
11530 Context->getNullValue(Op->getType()), &LI);
11531 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011532 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011533 }
Chris Lattner37366c12005-05-01 04:24:53 +000011534
Chris Lattnere87597f2004-10-16 18:11:37 +000011535 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011536 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011537 // TODO: Consider a target hook for valid address spaces for this xform.
11538 if (isa<UndefValue>(C) || (C->isNullValue() &&
11539 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011540 // Insert a new store to null instruction before the load to indicate that
11541 // this code is not reachable. We do this instead of inserting an
11542 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011543 new StoreInst(Context->getUndef(LI.getType()),
11544 Context->getNullValue(Op->getType()), &LI);
11545 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011546 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011547
Chris Lattnere87597f2004-10-16 18:11:37 +000011548 // Instcombine load (constant global) into the value loaded.
11549 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011550 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011551 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011552
Chris Lattnere87597f2004-10-16 18:11:37 +000011553 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011554 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011555 if (CE->getOpcode() == Instruction::GetElementPtr) {
11556 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011557 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011558 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011559 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11560 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011561 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011562 if (CE->getOperand(0)->isNullValue()) {
11563 // Insert a new store to null instruction before the load to indicate
11564 // that this code is not reachable. We do this instead of inserting
11565 // an unreachable instruction directly because we cannot modify the
11566 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011567 new StoreInst(Context->getUndef(LI.getType()),
11568 Context->getNullValue(Op->getType()), &LI);
11569 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011570 }
11571
Reid Spencer3da59db2006-11-27 01:05:10 +000011572 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011573 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011574 return Res;
11575 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011576 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011577 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011578
11579 // If this load comes from anywhere in a constant global, and if the global
11580 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011581 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011582 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011583 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011584 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011585 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011586 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011587 }
11588 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011589
Chris Lattner37366c12005-05-01 04:24:53 +000011590 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011591 // Change select and PHI nodes to select values instead of addresses: this
11592 // helps alias analysis out a lot, allows many others simplifications, and
11593 // exposes redundancy in the code.
11594 //
11595 // Note that we cannot do the transformation unless we know that the
11596 // introduced loads cannot trap! Something like this is valid as long as
11597 // the condition is always false: load (select bool %C, int* null, int* %G),
11598 // but it would not be valid if we transformed it to load from null
11599 // unconditionally.
11600 //
11601 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11602 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011603 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11604 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011605 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011606 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011607 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011608 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011609 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011610 }
11611
Chris Lattner684fe212004-09-23 15:46:00 +000011612 // load (select (cond, null, P)) -> load P
11613 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11614 if (C->isNullValue()) {
11615 LI.setOperand(0, SI->getOperand(2));
11616 return &LI;
11617 }
11618
11619 // load (select (cond, P, null)) -> load P
11620 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11621 if (C->isNullValue()) {
11622 LI.setOperand(0, SI->getOperand(1));
11623 return &LI;
11624 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011625 }
11626 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011627 return 0;
11628}
11629
Reid Spencer55af2b52007-01-19 21:20:31 +000011630/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011631/// when possible. This makes it generally easy to do alias analysis and/or
11632/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011633static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11634 User *CI = cast<User>(SI.getOperand(1));
11635 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011636 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011637
11638 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011639 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11640 if (SrcTy == 0) return 0;
11641
11642 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011643
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011644 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11645 return 0;
11646
Chris Lattner3914f722009-01-24 01:00:13 +000011647 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11648 /// to its first element. This allows us to handle things like:
11649 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11650 /// on 32-bit hosts.
11651 SmallVector<Value*, 4> NewGEPIndices;
11652
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011653 // If the source is an array, the code below will not succeed. Check to
11654 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11655 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011656 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11657 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011658 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011659 NewGEPIndices.push_back(Zero);
11660
11661 while (1) {
11662 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011663 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011664 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011665 NewGEPIndices.push_back(Zero);
11666 SrcPTy = STy->getElementType(0);
11667 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11668 NewGEPIndices.push_back(Zero);
11669 SrcPTy = ATy->getElementType();
11670 } else {
11671 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011672 }
Chris Lattner3914f722009-01-24 01:00:13 +000011673 }
11674
Owen Andersond672ecb2009-07-03 00:17:18 +000011675 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011676 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011677
11678 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11679 return 0;
11680
Chris Lattner71759c42009-01-16 20:12:52 +000011681 // If the pointers point into different address spaces or if they point to
11682 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011683 if (!IC.getTargetData() ||
11684 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011685 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011686 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11687 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011688 return 0;
11689
11690 // Okay, we are casting from one integer or pointer type to another of
11691 // the same size. Instead of casting the pointer before
11692 // the store, cast the value to be stored.
11693 Value *NewCast;
11694 Value *SIOp0 = SI.getOperand(0);
11695 Instruction::CastOps opcode = Instruction::BitCast;
11696 const Type* CastSrcTy = SIOp0->getType();
11697 const Type* CastDstTy = SrcPTy;
11698 if (isa<PointerType>(CastDstTy)) {
11699 if (CastSrcTy->isInteger())
11700 opcode = Instruction::IntToPtr;
11701 } else if (isa<IntegerType>(CastDstTy)) {
11702 if (isa<PointerType>(SIOp0->getType()))
11703 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011704 }
Chris Lattner3914f722009-01-24 01:00:13 +000011705
11706 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11707 // emit a GEP to index into its first field.
11708 if (!NewGEPIndices.empty()) {
11709 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011710 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011711 NewGEPIndices.size());
11712 else
11713 CastOp = IC.InsertNewInstBefore(
11714 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11715 NewGEPIndices.end()), SI);
11716 }
11717
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011718 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011719 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011720 else
11721 NewCast = IC.InsertNewInstBefore(
11722 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11723 SI);
11724 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011725}
11726
Chris Lattner4aebaee2008-11-27 08:56:30 +000011727/// equivalentAddressValues - Test if A and B will obviously have the same
11728/// value. This includes recognizing that %t0 and %t1 will have the same
11729/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011730/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011731/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011732/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011733/// %t2 = load i32* %t1
11734///
11735static bool equivalentAddressValues(Value *A, Value *B) {
11736 // Test if the values are trivially equivalent.
11737 if (A == B) return true;
11738
11739 // Test if the values come form identical arithmetic instructions.
11740 if (isa<BinaryOperator>(A) ||
11741 isa<CastInst>(A) ||
11742 isa<PHINode>(A) ||
11743 isa<GetElementPtrInst>(A))
11744 if (Instruction *BI = dyn_cast<Instruction>(B))
11745 if (cast<Instruction>(A)->isIdenticalTo(BI))
11746 return true;
11747
11748 // Otherwise they may not be equivalent.
11749 return false;
11750}
11751
Dale Johannesen4945c652009-03-03 21:26:39 +000011752// If this instruction has two uses, one of which is a llvm.dbg.declare,
11753// return the llvm.dbg.declare.
11754DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11755 if (!V->hasNUses(2))
11756 return 0;
11757 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11758 UI != E; ++UI) {
11759 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11760 return DI;
11761 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11762 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11763 return DI;
11764 }
11765 }
11766 return 0;
11767}
11768
Chris Lattner2f503e62005-01-31 05:36:43 +000011769Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11770 Value *Val = SI.getOperand(0);
11771 Value *Ptr = SI.getOperand(1);
11772
11773 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011774 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011775 ++NumCombined;
11776 return 0;
11777 }
Chris Lattner836692d2007-01-15 06:51:56 +000011778
11779 // If the RHS is an alloca with a single use, zapify the store, making the
11780 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011781 // If the RHS is an alloca with a two uses, the other one being a
11782 // llvm.dbg.declare, zapify the store and the declare, making the
11783 // alloca dead. We must do this to prevent declare's from affecting
11784 // codegen.
11785 if (!SI.isVolatile()) {
11786 if (Ptr->hasOneUse()) {
11787 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011788 EraseInstFromFunction(SI);
11789 ++NumCombined;
11790 return 0;
11791 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011792 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11793 if (isa<AllocaInst>(GEP->getOperand(0))) {
11794 if (GEP->getOperand(0)->hasOneUse()) {
11795 EraseInstFromFunction(SI);
11796 ++NumCombined;
11797 return 0;
11798 }
11799 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11800 EraseInstFromFunction(*DI);
11801 EraseInstFromFunction(SI);
11802 ++NumCombined;
11803 return 0;
11804 }
11805 }
11806 }
11807 }
11808 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11809 EraseInstFromFunction(*DI);
11810 EraseInstFromFunction(SI);
11811 ++NumCombined;
11812 return 0;
11813 }
Chris Lattner836692d2007-01-15 06:51:56 +000011814 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011815
Dan Gohman9941f742007-07-20 16:34:21 +000011816 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011817 if (TD) {
11818 unsigned KnownAlign =
11819 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11820 if (KnownAlign >
11821 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11822 SI.getAlignment()))
11823 SI.setAlignment(KnownAlign);
11824 }
Dan Gohman9941f742007-07-20 16:34:21 +000011825
Dale Johannesenacb51a32009-03-03 01:43:03 +000011826 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011827 // stores to the same location, separated by a few arithmetic operations. This
11828 // situation often occurs with bitfield accesses.
11829 BasicBlock::iterator BBI = &SI;
11830 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11831 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011832 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011833 // Don't count debug info directives, lest they affect codegen,
11834 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11835 // It is necessary for correctness to skip those that feed into a
11836 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011837 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011838 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011839 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011840 continue;
11841 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011842
11843 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11844 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011845 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11846 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011847 ++NumDeadStore;
11848 ++BBI;
11849 EraseInstFromFunction(*PrevSI);
11850 continue;
11851 }
11852 break;
11853 }
11854
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011855 // If this is a load, we have to stop. However, if the loaded value is from
11856 // the pointer we're loading and is producing the pointer we're storing,
11857 // then *this* store is dead (X = load P; store X -> P).
11858 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011859 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11860 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011861 EraseInstFromFunction(SI);
11862 ++NumCombined;
11863 return 0;
11864 }
11865 // Otherwise, this is a load from some other location. Stores before it
11866 // may not be dead.
11867 break;
11868 }
11869
Chris Lattner9ca96412006-02-08 03:25:32 +000011870 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011871 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011872 break;
11873 }
11874
11875
11876 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011877
11878 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011879 if (isa<ConstantPointerNull>(Ptr) &&
11880 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011881 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011882 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011883 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011884 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011885 ++NumCombined;
11886 }
11887 return 0; // Do not modify these!
11888 }
11889
11890 // store undef, Ptr -> noop
11891 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011892 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011893 ++NumCombined;
11894 return 0;
11895 }
11896
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011897 // If the pointer destination is a cast, see if we can fold the cast into the
11898 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011899 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011900 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11901 return Res;
11902 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011903 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011904 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11905 return Res;
11906
Chris Lattner408902b2005-09-12 23:23:25 +000011907
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011908 // If this store is the last instruction in the basic block (possibly
11909 // excepting debug info instructions and the pointer bitcasts that feed
11910 // into them), and if the block ends with an unconditional branch, try
11911 // to move it to the successor block.
11912 BBI = &SI;
11913 do {
11914 ++BBI;
11915 } while (isa<DbgInfoIntrinsic>(BBI) ||
11916 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011917 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011918 if (BI->isUnconditional())
11919 if (SimplifyStoreAtEndOfBlock(SI))
11920 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011921
Chris Lattner2f503e62005-01-31 05:36:43 +000011922 return 0;
11923}
11924
Chris Lattner3284d1f2007-04-15 00:07:55 +000011925/// SimplifyStoreAtEndOfBlock - Turn things like:
11926/// if () { *P = v1; } else { *P = v2 }
11927/// into a phi node with a store in the successor.
11928///
Chris Lattner31755a02007-04-15 01:02:18 +000011929/// Simplify things like:
11930/// *P = v1; if () { *P = v2; }
11931/// into a phi node with a store in the successor.
11932///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011933bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11934 BasicBlock *StoreBB = SI.getParent();
11935
11936 // Check to see if the successor block has exactly two incoming edges. If
11937 // so, see if the other predecessor contains a store to the same location.
11938 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011939 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011940
11941 // Determine whether Dest has exactly two predecessors and, if so, compute
11942 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011943 pred_iterator PI = pred_begin(DestBB);
11944 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011945 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011946 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011947 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011948 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011949 return false;
11950
11951 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011952 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011953 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011954 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011955 }
Chris Lattner31755a02007-04-15 01:02:18 +000011956 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011957 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011958
11959 // Bail out if all the relevant blocks aren't distinct (this can happen,
11960 // for example, if SI is in an infinite loop)
11961 if (StoreBB == DestBB || OtherBB == DestBB)
11962 return false;
11963
Chris Lattner31755a02007-04-15 01:02:18 +000011964 // Verify that the other block ends in a branch and is not otherwise empty.
11965 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011966 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011967 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011968 return false;
11969
Chris Lattner31755a02007-04-15 01:02:18 +000011970 // If the other block ends in an unconditional branch, check for the 'if then
11971 // else' case. there is an instruction before the branch.
11972 StoreInst *OtherStore = 0;
11973 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011974 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011975 // Skip over debugging info.
11976 while (isa<DbgInfoIntrinsic>(BBI) ||
11977 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11978 if (BBI==OtherBB->begin())
11979 return false;
11980 --BBI;
11981 }
11982 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011983 OtherStore = dyn_cast<StoreInst>(BBI);
11984 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11985 return false;
11986 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011987 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011988 // destinations is StoreBB, then we have the if/then case.
11989 if (OtherBr->getSuccessor(0) != StoreBB &&
11990 OtherBr->getSuccessor(1) != StoreBB)
11991 return false;
11992
11993 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011994 // if/then triangle. See if there is a store to the same ptr as SI that
11995 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011996 for (;; --BBI) {
11997 // Check to see if we find the matching store.
11998 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11999 if (OtherStore->getOperand(1) != SI.getOperand(1))
12000 return false;
12001 break;
12002 }
Eli Friedman6903a242008-06-13 22:02:12 +000012003 // If we find something that may be using or overwriting the stored
12004 // value, or if we run out of instructions, we can't do the xform.
12005 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012006 BBI == OtherBB->begin())
12007 return false;
12008 }
12009
12010 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012011 // make sure nothing reads or overwrites the stored value in
12012 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012013 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12014 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012015 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012016 return false;
12017 }
12018 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012019
Chris Lattner31755a02007-04-15 01:02:18 +000012020 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012021 Value *MergedVal = OtherStore->getOperand(0);
12022 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012023 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012024 PN->reserveOperandSpace(2);
12025 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012026 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12027 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012028 }
12029
12030 // Advance to a place where it is safe to insert the new store and
12031 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012032 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012033 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12034 OtherStore->isVolatile()), *BBI);
12035
12036 // Nuke the old stores.
12037 EraseInstFromFunction(SI);
12038 EraseInstFromFunction(*OtherStore);
12039 ++NumCombined;
12040 return true;
12041}
12042
Chris Lattner2f503e62005-01-31 05:36:43 +000012043
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012044Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12045 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012046 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012047 BasicBlock *TrueDest;
12048 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012049 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012050 !isa<Constant>(X)) {
12051 // Swap Destinations and condition...
12052 BI.setCondition(X);
12053 BI.setSuccessor(0, FalseDest);
12054 BI.setSuccessor(1, TrueDest);
12055 return &BI;
12056 }
12057
Reid Spencere4d87aa2006-12-23 06:05:41 +000012058 // Cannonicalize fcmp_one -> fcmp_oeq
12059 FCmpInst::Predicate FPred; Value *Y;
12060 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012061 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012062 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12063 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12064 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012065 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012066 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012067 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012068 // Swap Destinations and condition...
12069 BI.setCondition(NewSCC);
12070 BI.setSuccessor(0, FalseDest);
12071 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012072 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012073 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012074 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012075 return &BI;
12076 }
12077
12078 // Cannonicalize icmp_ne -> icmp_eq
12079 ICmpInst::Predicate IPred;
12080 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012081 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012082 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12083 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12084 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12085 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012086 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012087 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012088 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012089 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012090 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012091 BI.setSuccessor(0, FalseDest);
12092 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012093 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012094 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012095 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012096 return &BI;
12097 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012098
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012099 return 0;
12100}
Chris Lattner0864acf2002-11-04 16:18:53 +000012101
Chris Lattner46238a62004-07-03 00:26:11 +000012102Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12103 Value *Cond = SI.getCondition();
12104 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12105 if (I->getOpcode() == Instruction::Add)
12106 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12107 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12108 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012109 SI.setOperand(i,
12110 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012111 AddRHS));
12112 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012113 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012114 return &SI;
12115 }
12116 }
12117 return 0;
12118}
12119
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012120Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012121 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012122
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012123 if (!EV.hasIndices())
12124 return ReplaceInstUsesWith(EV, Agg);
12125
12126 if (Constant *C = dyn_cast<Constant>(Agg)) {
12127 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012128 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012129
12130 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012131 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012132
12133 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12134 // Extract the element indexed by the first index out of the constant
12135 Value *V = C->getOperand(*EV.idx_begin());
12136 if (EV.getNumIndices() > 1)
12137 // Extract the remaining indices out of the constant indexed by the
12138 // first index
12139 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12140 else
12141 return ReplaceInstUsesWith(EV, V);
12142 }
12143 return 0; // Can't handle other constants
12144 }
12145 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12146 // We're extracting from an insertvalue instruction, compare the indices
12147 const unsigned *exti, *exte, *insi, *inse;
12148 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12149 exte = EV.idx_end(), inse = IV->idx_end();
12150 exti != exte && insi != inse;
12151 ++exti, ++insi) {
12152 if (*insi != *exti)
12153 // The insert and extract both reference distinctly different elements.
12154 // This means the extract is not influenced by the insert, and we can
12155 // replace the aggregate operand of the extract with the aggregate
12156 // operand of the insert. i.e., replace
12157 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12158 // %E = extractvalue { i32, { i32 } } %I, 0
12159 // with
12160 // %E = extractvalue { i32, { i32 } } %A, 0
12161 return ExtractValueInst::Create(IV->getAggregateOperand(),
12162 EV.idx_begin(), EV.idx_end());
12163 }
12164 if (exti == exte && insi == inse)
12165 // Both iterators are at the end: Index lists are identical. Replace
12166 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12167 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12168 // with "i32 42"
12169 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12170 if (exti == exte) {
12171 // The extract list is a prefix of the insert list. i.e. replace
12172 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12173 // %E = extractvalue { i32, { i32 } } %I, 1
12174 // with
12175 // %X = extractvalue { i32, { i32 } } %A, 1
12176 // %E = insertvalue { i32 } %X, i32 42, 0
12177 // by switching the order of the insert and extract (though the
12178 // insertvalue should be left in, since it may have other uses).
12179 Value *NewEV = InsertNewInstBefore(
12180 ExtractValueInst::Create(IV->getAggregateOperand(),
12181 EV.idx_begin(), EV.idx_end()),
12182 EV);
12183 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12184 insi, inse);
12185 }
12186 if (insi == inse)
12187 // The insert list is a prefix of the extract list
12188 // We can simply remove the common indices from the extract and make it
12189 // operate on the inserted value instead of the insertvalue result.
12190 // i.e., replace
12191 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12192 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12193 // with
12194 // %E extractvalue { i32 } { i32 42 }, 0
12195 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12196 exti, exte);
12197 }
12198 // Can't simplify extracts from other values. Note that nested extracts are
12199 // already simplified implicitely by the above (extract ( extract (insert) )
12200 // will be translated into extract ( insert ( extract ) ) first and then just
12201 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012202 return 0;
12203}
12204
Chris Lattner220b0cf2006-03-05 00:22:33 +000012205/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12206/// is to leave as a vector operation.
12207static bool CheapToScalarize(Value *V, bool isConstant) {
12208 if (isa<ConstantAggregateZero>(V))
12209 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012210 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012211 if (isConstant) return true;
12212 // If all elts are the same, we can extract.
12213 Constant *Op0 = C->getOperand(0);
12214 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12215 if (C->getOperand(i) != Op0)
12216 return false;
12217 return true;
12218 }
12219 Instruction *I = dyn_cast<Instruction>(V);
12220 if (!I) return false;
12221
12222 // Insert element gets simplified to the inserted element or is deleted if
12223 // this is constant idx extract element and its a constant idx insertelt.
12224 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12225 isa<ConstantInt>(I->getOperand(2)))
12226 return true;
12227 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12228 return true;
12229 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12230 if (BO->hasOneUse() &&
12231 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12232 CheapToScalarize(BO->getOperand(1), isConstant)))
12233 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012234 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12235 if (CI->hasOneUse() &&
12236 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12237 CheapToScalarize(CI->getOperand(1), isConstant)))
12238 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012239
12240 return false;
12241}
12242
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012243/// Read and decode a shufflevector mask.
12244///
12245/// It turns undef elements into values that are larger than the number of
12246/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012247static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12248 unsigned NElts = SVI->getType()->getNumElements();
12249 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12250 return std::vector<unsigned>(NElts, 0);
12251 if (isa<UndefValue>(SVI->getOperand(2)))
12252 return std::vector<unsigned>(NElts, 2*NElts);
12253
12254 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012255 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012256 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12257 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012258 Result.push_back(NElts*2); // undef -> 8
12259 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012260 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012261 return Result;
12262}
12263
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012264/// FindScalarElement - Given a vector and an element number, see if the scalar
12265/// value is already around as a register, for example if it were inserted then
12266/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012267static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012268 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012269 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12270 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012271 unsigned Width = PTy->getNumElements();
12272 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012273 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012274
12275 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012276 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012277 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012278 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012279 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012280 return CP->getOperand(EltNo);
12281 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12282 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012283 if (!isa<ConstantInt>(III->getOperand(2)))
12284 return 0;
12285 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012286
12287 // If this is an insert to the element we are looking for, return the
12288 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012289 if (EltNo == IIElt)
12290 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012291
12292 // Otherwise, the insertelement doesn't modify the value, recurse on its
12293 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012294 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012295 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012296 unsigned LHSWidth =
12297 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012298 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012299 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012300 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012301 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012302 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012303 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012304 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012305 }
12306
12307 // Otherwise, we don't know.
12308 return 0;
12309}
12310
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012311Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012312 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012313 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012314 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012315
Dan Gohman07a96762007-07-16 14:29:03 +000012316 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012317 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012318 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012319
Reid Spencer9d6565a2007-02-15 02:26:10 +000012320 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012321 // If vector val is constant with all elements the same, replace EI with
12322 // that element. When the elements are not identical, we cannot replace yet
12323 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012324 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012325 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012326 if (C->getOperand(i) != op0) {
12327 op0 = 0;
12328 break;
12329 }
12330 if (op0)
12331 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012332 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012333
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012334 // If extracting a specified index from the vector, see if we can recursively
12335 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012336 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012337 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012338 unsigned VectorWidth =
12339 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012340
12341 // If this is extracting an invalid index, turn this into undef, to avoid
12342 // crashing the code below.
12343 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012344 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012345
Chris Lattner867b99f2006-10-05 06:55:50 +000012346 // This instruction only demands the single element from the input vector.
12347 // If the input vector has a single use, simplify it based on this use
12348 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012349 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012350 APInt UndefElts(VectorWidth, 0);
12351 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012352 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012353 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012354 EI.setOperand(0, V);
12355 return &EI;
12356 }
12357 }
12358
Owen Andersond672ecb2009-07-03 00:17:18 +000012359 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012360 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012361
12362 // If the this extractelement is directly using a bitcast from a vector of
12363 // the same number of elements, see if we can find the source element from
12364 // it. In this case, we will end up needing to bitcast the scalars.
12365 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12366 if (const VectorType *VT =
12367 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12368 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012369 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12370 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012371 return new BitCastInst(Elt, EI.getType());
12372 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012373 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012374
Chris Lattner73fa49d2006-05-25 22:53:38 +000012375 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012376 if (I->hasOneUse()) {
12377 // Push extractelement into predecessor operation if legal and
12378 // profitable to do so
12379 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012380 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12381 if (CheapToScalarize(BO, isConstantElt)) {
12382 ExtractElementInst *newEI0 =
12383 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12384 EI.getName()+".lhs");
12385 ExtractElementInst *newEI1 =
12386 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12387 EI.getName()+".rhs");
12388 InsertNewInstBefore(newEI0, EI);
12389 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012390 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012391 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012392 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012393 unsigned AS =
12394 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012395 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012396 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012397 GetElementPtrInst *GEP =
12398 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012399 InsertNewInstBefore(GEP, EI);
12400 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012401 }
12402 }
12403 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12404 // Extracting the inserted element?
12405 if (IE->getOperand(2) == EI.getOperand(1))
12406 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12407 // If the inserted and extracted elements are constants, they must not
12408 // be the same value, extract from the pre-inserted value instead.
12409 if (isa<Constant>(IE->getOperand(2)) &&
12410 isa<Constant>(EI.getOperand(1))) {
12411 AddUsesToWorkList(EI);
12412 EI.setOperand(0, IE->getOperand(0));
12413 return &EI;
12414 }
12415 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12416 // If this is extracting an element from a shufflevector, figure out where
12417 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012418 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12419 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012420 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012421 unsigned LHSWidth =
12422 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12423
12424 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012425 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012426 else if (SrcIdx < LHSWidth*2) {
12427 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012428 Src = SVI->getOperand(1);
12429 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012430 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012431 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000012432 return new ExtractElementInst(Src,
12433 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012434 }
12435 }
Eli Friedman2451a642009-07-18 23:06:53 +000012436 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012437 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012438 return 0;
12439}
12440
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012441/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12442/// elements from either LHS or RHS, return the shuffle mask and true.
12443/// Otherwise, return false.
12444static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012445 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012446 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012447 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12448 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012449 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012450
12451 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012452 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012453 return true;
12454 } else if (V == LHS) {
12455 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012456 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012457 return true;
12458 } else if (V == RHS) {
12459 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012460 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012461 return true;
12462 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12463 // If this is an insert of an extract from some other vector, include it.
12464 Value *VecOp = IEI->getOperand(0);
12465 Value *ScalarOp = IEI->getOperand(1);
12466 Value *IdxOp = IEI->getOperand(2);
12467
Chris Lattnerd929f062006-04-27 21:14:21 +000012468 if (!isa<ConstantInt>(IdxOp))
12469 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012470 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012471
12472 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12473 // Okay, we can handle this if the vector we are insertinting into is
12474 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012475 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012476 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012477 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012478 return true;
12479 }
12480 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12481 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012482 EI->getOperand(0)->getType() == V->getType()) {
12483 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012484 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012485
12486 // This must be extracting from either LHS or RHS.
12487 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12488 // Okay, we can handle this if the vector we are insertinting into is
12489 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012490 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012491 // If so, update the mask to reflect the inserted value.
12492 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012493 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012494 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012495 } else {
12496 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012497 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012498 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012499
12500 }
12501 return true;
12502 }
12503 }
12504 }
12505 }
12506 }
12507 // TODO: Handle shufflevector here!
12508
12509 return false;
12510}
12511
12512/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12513/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12514/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012515static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012516 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012517 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012518 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012519 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012520 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012521
12522 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012523 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012524 return V;
12525 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012526 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012527 return V;
12528 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12529 // If this is an insert of an extract from some other vector, include it.
12530 Value *VecOp = IEI->getOperand(0);
12531 Value *ScalarOp = IEI->getOperand(1);
12532 Value *IdxOp = IEI->getOperand(2);
12533
12534 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12535 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12536 EI->getOperand(0)->getType() == V->getType()) {
12537 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012538 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12539 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012540
12541 // Either the extracted from or inserted into vector must be RHSVec,
12542 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012543 if (EI->getOperand(0) == RHS || RHS == 0) {
12544 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012545 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012546 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012547 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012548 return V;
12549 }
12550
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012551 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012552 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12553 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012554 // Everything but the extracted element is replaced with the RHS.
12555 for (unsigned i = 0; i != NumElts; ++i) {
12556 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012557 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012558 }
12559 return V;
12560 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012561
12562 // If this insertelement is a chain that comes from exactly these two
12563 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012564 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12565 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012566 return EI->getOperand(0);
12567
Chris Lattnerefb47352006-04-15 01:39:45 +000012568 }
12569 }
12570 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012571 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012572
12573 // Otherwise, can't do anything fancy. Return an identity vector.
12574 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012575 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012576 return V;
12577}
12578
12579Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12580 Value *VecOp = IE.getOperand(0);
12581 Value *ScalarOp = IE.getOperand(1);
12582 Value *IdxOp = IE.getOperand(2);
12583
Chris Lattner599ded12007-04-09 01:11:16 +000012584 // Inserting an undef or into an undefined place, remove this.
12585 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12586 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012587
Chris Lattnerefb47352006-04-15 01:39:45 +000012588 // If the inserted element was extracted from some other vector, and if the
12589 // indexes are constant, try to turn this into a shufflevector operation.
12590 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12591 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12592 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012593 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012594 unsigned ExtractedIdx =
12595 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012596 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012597
12598 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12599 return ReplaceInstUsesWith(IE, VecOp);
12600
12601 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012602 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012603
12604 // If we are extracting a value from a vector, then inserting it right
12605 // back into the same place, just use the input vector.
12606 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12607 return ReplaceInstUsesWith(IE, VecOp);
12608
12609 // We could theoretically do this for ANY input. However, doing so could
12610 // turn chains of insertelement instructions into a chain of shufflevector
12611 // instructions, and right now we do not merge shufflevectors. As such,
12612 // only do this in a situation where it is clear that there is benefit.
12613 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12614 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12615 // the values of VecOp, except then one read from EIOp0.
12616 // Build a new shuffle mask.
12617 std::vector<Constant*> Mask;
12618 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012619 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012620 else {
12621 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012622 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012623 NumVectorElts));
12624 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012625 Mask[InsertedIdx] =
12626 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012627 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012628 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012629 }
12630
12631 // If this insertelement isn't used by some other insertelement, turn it
12632 // (and any insertelements it points to), into one big shuffle.
12633 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12634 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012635 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012636 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12637 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012638 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012639 return new ShuffleVectorInst(LHS, RHS,
12640 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012641 }
12642 }
12643 }
12644
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012645 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12646 APInt UndefElts(VWidth, 0);
12647 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12648 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12649 return &IE;
12650
Chris Lattnerefb47352006-04-15 01:39:45 +000012651 return 0;
12652}
12653
12654
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012655Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12656 Value *LHS = SVI.getOperand(0);
12657 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012658 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012659
12660 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012661
Chris Lattner867b99f2006-10-05 06:55:50 +000012662 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012663 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012664 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012665
Dan Gohman488fbfc2008-09-09 18:11:14 +000012666 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012667
12668 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12669 return 0;
12670
Evan Cheng388df622009-02-03 10:05:09 +000012671 APInt UndefElts(VWidth, 0);
12672 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12673 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012674 LHS = SVI.getOperand(0);
12675 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012676 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012677 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012678
Chris Lattner863bcff2006-05-25 23:48:38 +000012679 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12680 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12681 if (LHS == RHS || isa<UndefValue>(LHS)) {
12682 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012683 // shuffle(undef,undef,mask) -> undef.
12684 return ReplaceInstUsesWith(SVI, LHS);
12685 }
12686
Chris Lattner863bcff2006-05-25 23:48:38 +000012687 // Remap any references to RHS to use LHS.
12688 std::vector<Constant*> Elts;
12689 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012690 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012691 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012692 else {
12693 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012694 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012695 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012696 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012697 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012698 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012699 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012700 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012701 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012702 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012703 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012704 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12705 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012706 LHS = SVI.getOperand(0);
12707 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012708 MadeChange = true;
12709 }
12710
Chris Lattner7b2e27922006-05-26 00:29:06 +000012711 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012712 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012713
Chris Lattner863bcff2006-05-25 23:48:38 +000012714 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12715 if (Mask[i] >= e*2) continue; // Ignore undef values.
12716 // Is this an identity shuffle of the LHS value?
12717 isLHSID &= (Mask[i] == i);
12718
12719 // Is this an identity shuffle of the RHS value?
12720 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012721 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012722
Chris Lattner863bcff2006-05-25 23:48:38 +000012723 // Eliminate identity shuffles.
12724 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12725 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012726
Chris Lattner7b2e27922006-05-26 00:29:06 +000012727 // If the LHS is a shufflevector itself, see if we can combine it with this
12728 // one without producing an unusual shuffle. Here we are really conservative:
12729 // we are absolutely afraid of producing a shuffle mask not in the input
12730 // program, because the code gen may not be smart enough to turn a merged
12731 // shuffle into two specific shuffles: it may produce worse code. As such,
12732 // we only merge two shuffles if the result is one of the two input shuffle
12733 // masks. In this case, merging the shuffles just removes one instruction,
12734 // which we know is safe. This is good for things like turning:
12735 // (splat(splat)) -> splat.
12736 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12737 if (isa<UndefValue>(RHS)) {
12738 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12739
12740 std::vector<unsigned> NewMask;
12741 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12742 if (Mask[i] >= 2*e)
12743 NewMask.push_back(2*e);
12744 else
12745 NewMask.push_back(LHSMask[Mask[i]]);
12746
12747 // If the result mask is equal to the src shuffle or this shuffle mask, do
12748 // the replacement.
12749 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012750 unsigned LHSInNElts =
12751 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012752 std::vector<Constant*> Elts;
12753 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012754 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012755 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012756 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012757 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012758 }
12759 }
12760 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12761 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012762 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012763 }
12764 }
12765 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012766
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012767 return MadeChange ? &SVI : 0;
12768}
12769
12770
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012771
Chris Lattnerea1c4542004-12-08 23:43:58 +000012772
12773/// TryToSinkInstruction - Try to move the specified instruction from its
12774/// current block into the beginning of DestBlock, which can only happen if it's
12775/// safe to move the instruction past all of the instructions between it and the
12776/// end of its block.
12777static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12778 assert(I->hasOneUse() && "Invariants didn't hold!");
12779
Chris Lattner108e9022005-10-27 17:13:11 +000012780 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012781 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012782 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012783
Chris Lattnerea1c4542004-12-08 23:43:58 +000012784 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012785 if (isa<AllocaInst>(I) && I->getParent() ==
12786 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012787 return false;
12788
Chris Lattner96a52a62004-12-09 07:14:34 +000012789 // We can only sink load instructions if there is nothing between the load and
12790 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012791 if (I->mayReadFromMemory()) {
12792 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012793 Scan != E; ++Scan)
12794 if (Scan->mayWriteToMemory())
12795 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012796 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012797
Dan Gohman02dea8b2008-05-23 21:05:58 +000012798 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012799
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012800 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012801 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012802 ++NumSunkInst;
12803 return true;
12804}
12805
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012806
12807/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12808/// all reachable code to the worklist.
12809///
12810/// This has a couple of tricks to make the code faster and more powerful. In
12811/// particular, we constant fold and DCE instructions as we go, to avoid adding
12812/// them to the worklist (this significantly speeds up instcombine on code where
12813/// many instructions are dead or constant). Additionally, if we find a branch
12814/// whose condition is a known constant, we only visit the reachable successors.
12815///
12816static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012817 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012818 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012819 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012820 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012821 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012822
Chris Lattner2c7718a2007-03-23 19:17:18 +000012823 while (!Worklist.empty()) {
12824 BB = Worklist.back();
12825 Worklist.pop_back();
12826
12827 // We have now visited this block! If we've already been here, ignore it.
12828 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012829
12830 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012831 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12832 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012833
Chris Lattner2c7718a2007-03-23 19:17:18 +000012834 // DCE instruction if trivially dead.
12835 if (isInstructionTriviallyDead(Inst)) {
12836 ++NumDeadInst;
12837 DOUT << "IC: DCE: " << *Inst;
12838 Inst->eraseFromParent();
12839 continue;
12840 }
12841
12842 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012843 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012844 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12845 Inst->replaceAllUsesWith(C);
12846 ++NumConstProp;
12847 Inst->eraseFromParent();
12848 continue;
12849 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012850
Devang Patel7fe1dec2008-11-19 18:56:50 +000012851 // If there are two consecutive llvm.dbg.stoppoint calls then
12852 // it is likely that the optimizer deleted code in between these
12853 // two intrinsics.
12854 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12855 if (DBI_Next) {
12856 if (DBI_Prev
12857 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12858 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12859 IC.RemoveFromWorkList(DBI_Prev);
12860 DBI_Prev->eraseFromParent();
12861 }
12862 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012863 } else {
12864 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012865 }
12866
Chris Lattner2c7718a2007-03-23 19:17:18 +000012867 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012868 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012869
12870 // Recursively visit successors. If this is a branch or switch on a
12871 // constant, only visit the reachable successor.
12872 TerminatorInst *TI = BB->getTerminator();
12873 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12874 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12875 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012876 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012877 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012878 continue;
12879 }
12880 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12881 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12882 // See if this is an explicit destination.
12883 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12884 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012885 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012886 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012887 continue;
12888 }
12889
12890 // Otherwise it is the default destination.
12891 Worklist.push_back(SI->getSuccessor(0));
12892 continue;
12893 }
12894 }
12895
12896 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12897 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012898 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012899}
12900
Chris Lattnerec9c3582007-03-03 02:04:50 +000012901bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012902 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012903 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012904
12905 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12906 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012907
Chris Lattnerb3d59702005-07-07 20:40:38 +000012908 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012909 // Do a depth-first traversal of the function, populate the worklist with
12910 // the reachable instructions. Ignore blocks that are not reachable. Keep
12911 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012912 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012913 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012914
Chris Lattnerb3d59702005-07-07 20:40:38 +000012915 // Do a quick scan over the function. If we find any blocks that are
12916 // unreachable, remove any instructions inside of them. This prevents
12917 // the instcombine code from having to deal with some bad special cases.
12918 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12919 if (!Visited.count(BB)) {
12920 Instruction *Term = BB->getTerminator();
12921 while (Term != BB->begin()) { // Remove instrs bottom-up
12922 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012923
Bill Wendlingb7427032006-11-26 09:46:52 +000012924 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012925 // A debug intrinsic shouldn't force another iteration if we weren't
12926 // going to do one without it.
12927 if (!isa<DbgInfoIntrinsic>(I)) {
12928 ++NumDeadInst;
12929 Changed = true;
12930 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012931 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012932 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012933 I->eraseFromParent();
12934 }
12935 }
12936 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012937
Chris Lattnerdbab3862007-03-02 21:28:56 +000012938 while (!Worklist.empty()) {
12939 Instruction *I = RemoveOneFromWorkList();
12940 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012941
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012942 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012943 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012944 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012945 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012946 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012947 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012948
Bill Wendlingb7427032006-11-26 09:46:52 +000012949 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012950
12951 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012952 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012953 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012954 continue;
12955 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012956
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012957 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012958 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012959 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012960
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012961 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012962 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012963 ReplaceInstUsesWith(*I, C);
12964
Chris Lattner62b14df2002-09-02 04:59:56 +000012965 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012966 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012967 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012968 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012969 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012970 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012971
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012972 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012973 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012974 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12975 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012976 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12977 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012978 if (NewC != CE) {
12979 i->set(NewC);
12980 Changed = true;
12981 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012982 }
12983
Chris Lattnerea1c4542004-12-08 23:43:58 +000012984 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012985 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012986 BasicBlock *BB = I->getParent();
12987 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12988 if (UserParent != BB) {
12989 bool UserIsSuccessor = false;
12990 // See if the user is one of our successors.
12991 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12992 if (*SI == UserParent) {
12993 UserIsSuccessor = true;
12994 break;
12995 }
12996
12997 // If the user is one of our immediate successors, and if that successor
12998 // only has us as a predecessors (we'd have to split the critical edge
12999 // otherwise), we can keep going.
13000 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13001 next(pred_begin(UserParent)) == pred_end(UserParent))
13002 // Okay, the CFG is simple enough, try to sink this instruction.
13003 Changed |= TryToSinkInstruction(I, UserParent);
13004 }
13005 }
13006
Chris Lattner8a2a3112001-12-14 16:52:21 +000013007 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013008#ifndef NDEBUG
13009 std::string OrigI;
13010#endif
13011 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013012 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013013 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013014 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013015 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013016 DOUT << "IC: Old = " << *I
13017 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013018
Chris Lattnerf523d062004-06-09 05:08:07 +000013019 // Everything uses the new instruction now.
13020 I->replaceAllUsesWith(Result);
13021
13022 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013023 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013024 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013025
Chris Lattner6934a042007-02-11 01:23:03 +000013026 // Move the name to the new instruction first.
13027 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013028
13029 // Insert the new instruction into the basic block...
13030 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013031 BasicBlock::iterator InsertPos = I;
13032
13033 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13034 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13035 ++InsertPos;
13036
13037 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013038
Chris Lattner00d51312004-05-01 23:27:23 +000013039 // Make sure that we reprocess all operands now that we reduced their
13040 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013041 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013042
Chris Lattnerf523d062004-06-09 05:08:07 +000013043 // Instructions can end up on the worklist more than once. Make sure
13044 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013045 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013046
13047 // Erase the old instruction.
13048 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013049 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013050#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013051 DOUT << "IC: Mod = " << OrigI
13052 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013053#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013054
Chris Lattner90ac28c2002-08-02 19:29:35 +000013055 // If the instruction was modified, it's possible that it is now dead.
13056 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013057 if (isInstructionTriviallyDead(I)) {
13058 // Make sure we process all operands now that we are reducing their
13059 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013060 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013061
Chris Lattner00d51312004-05-01 23:27:23 +000013062 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013063 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013064 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013065 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013066 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013067 AddToWorkList(I);
13068 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013069 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013070 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013071 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013072 }
13073 }
13074
Chris Lattnerec9c3582007-03-03 02:04:50 +000013075 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013076
13077 // Do an explicit clear, this shrinks the map if needed.
13078 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013079 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013080}
13081
Chris Lattnerec9c3582007-03-03 02:04:50 +000013082
13083bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013084 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13085
Chris Lattnerec9c3582007-03-03 02:04:50 +000013086 bool EverMadeChange = false;
13087
13088 // Iterate while there is work to do.
13089 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013090 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013091 EverMadeChange = true;
13092 return EverMadeChange;
13093}
13094
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013095FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013096 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013097}