blob: 0c010cfa9fe943e7787d86a3b4a0d931a331b38e [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 {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000160 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000161 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000162 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000163 }
164
Chris Lattner28977af2004-04-05 01:30:19 +0000165 TargetData &getTargetData() const { return *TD; }
166
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // Visitation implementation - Implement instruction combining for different
168 // instruction types. The semantics are as follows:
169 // Return Value:
170 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000171 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000172 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000173 //
Chris Lattner7e708292002-06-25 16:13:24 +0000174 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000175 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000176 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000177 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000178 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000179 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000180 Instruction *visitURem(BinaryOperator &I);
181 Instruction *visitSRem(BinaryOperator &I);
182 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000183 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000184 Instruction *commonRemTransforms(BinaryOperator &I);
185 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000186 Instruction *commonDivTransforms(BinaryOperator &I);
187 Instruction *commonIDivTransforms(BinaryOperator &I);
188 Instruction *visitUDiv(BinaryOperator &I);
189 Instruction *visitSDiv(BinaryOperator &I);
190 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000191 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000192 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000193 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000194 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000195 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000196 Instruction *visitOr (BinaryOperator &I);
197 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000198 Instruction *visitShl(BinaryOperator &I);
199 Instruction *visitAShr(BinaryOperator &I);
200 Instruction *visitLShr(BinaryOperator &I);
201 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000202 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
203 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000204 Instruction *visitFCmpInst(FCmpInst &I);
205 Instruction *visitICmpInst(ICmpInst &I);
206 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000207 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
208 Instruction *LHS,
209 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000210 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
211 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000212
Reid Spencere4d87aa2006-12-23 06:05:41 +0000213 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
214 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000215 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000216 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000217 Instruction *commonCastTransforms(CastInst &CI);
218 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000219 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000220 Instruction *visitTrunc(TruncInst &CI);
221 Instruction *visitZExt(ZExtInst &CI);
222 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000223 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000224 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000225 Instruction *visitFPToUI(FPToUIInst &FI);
226 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000227 Instruction *visitUIToFP(CastInst &CI);
228 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000229 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000230 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000231 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000232 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
233 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000234 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000235 Instruction *visitSelectInst(SelectInst &SI);
236 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 Instruction *visitCallInst(CallInst &CI);
238 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitPHINode(PHINode &PN);
240 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000241 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000242 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000243 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000244 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000245 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000246 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000247 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000248 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000249 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000250 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000251
252 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000253 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000254
Chris Lattner9fe38862003-06-19 17:00:31 +0000255 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000256 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000257 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000258 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000259 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
260 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000261 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000262 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
263
Chris Lattner9fe38862003-06-19 17:00:31 +0000264
Chris Lattner28977af2004-04-05 01:30:19 +0000265 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000266 // InsertNewInstBefore - insert an instruction New before instruction Old
267 // in the program. Add the new instruction to the worklist.
268 //
Chris Lattner955f3312004-09-28 21:48:02 +0000269 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000270 assert(New && New->getParent() == 0 &&
271 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000272 BasicBlock *BB = Old.getParent();
273 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000274 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000275 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000276 }
277
Chris Lattner0c967662004-09-24 15:21:34 +0000278 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
279 /// This also adds the cast to the worklist. Finally, this returns the
280 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000281 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
282 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000283 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000284
Chris Lattnere2ed0572006-04-06 19:19:17 +0000285 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +0000286 return Context->getConstantExprCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000287
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000288 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000289 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000290 return C;
291 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000292
293 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
294 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
295 }
296
Chris Lattner0c967662004-09-24 15:21:34 +0000297
Chris Lattner8b170942002-08-09 23:47:40 +0000298 // ReplaceInstUsesWith - This method is to be used when an instruction is
299 // found to be dead, replacable with another preexisting expression. Here
300 // we add all uses of I to the worklist, replace all uses of I with the new
301 // value, then return I, so that the inst combiner will know that I was
302 // modified.
303 //
304 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000305 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000306 if (&I != V) {
307 I.replaceAllUsesWith(V);
308 return &I;
309 } else {
310 // If we are replacing the instruction with itself, this must be in a
311 // segment of unreachable code, so just clobber the instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +0000312 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000313 return &I;
314 }
Chris Lattner8b170942002-08-09 23:47:40 +0000315 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000316
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
320 // this function.
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000324 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000325 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000326 return 0; // Don't do anything with FI
327 }
Chris Lattner173234a2008-06-02 01:18:21 +0000328
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 }
333
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337 }
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
340 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000341
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000342 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000343
Reid Spencere4d87aa2006-12-23 06:05:41 +0000344 /// SimplifyCommutative - This performs a few simplifications for
345 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000346 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000347
Reid Spencere4d87aa2006-12-23 06:05:41 +0000348 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
349 /// most-complex to least-complex order.
350 bool SimplifyCompare(CmpInst &I);
351
Chris Lattner886ab6c2009-01-31 08:15:18 +0000352 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
353 /// based on the demanded bits.
354 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
355 APInt& KnownZero, APInt& KnownOne,
356 unsigned Depth);
357 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000358 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000359 unsigned Depth=0);
360
361 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
362 /// SimplifyDemandedBits knows about. See if the instruction has any
363 /// properties that allow us to simplify its operands.
364 bool SimplifyDemandedInstructionBits(Instruction &Inst);
365
Evan Cheng388df622009-02-03 10:05:09 +0000366 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
367 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000368
Chris Lattner4e998b22004-09-29 05:07:12 +0000369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
373
Chris Lattnerbac32862004-11-14 19:13:23 +0000374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000379 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380
Chris Lattner7da52b22006-11-01 04:51:18 +0000381
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000382 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000385 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000386 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000387 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000388 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000389 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000390 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000391 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000393 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000394
Chris Lattnerafe91a52006-06-15 19:07:26 +0000395
Reid Spencerc55b2432006-12-13 18:21:21 +0000396 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000397
Dan Gohman6de29f82009-06-15 22:12:54 +0000398 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000399 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000402
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000403 };
404}
405
Dan Gohman844731a2008-05-13 00:00:25 +0000406char InstCombiner::ID = 0;
407static RegisterPass<InstCombiner>
408X("instcombine", "Combine redundant instructions");
409
Chris Lattner4f98c562003-03-10 21:43:22 +0000410// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000411// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Owen Anderson0a5372e2009-07-13 04:09:18 +0000412static unsigned getComplexity(LLVMContext *Context, Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000413 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000414 if (BinaryOperator::isNeg(V) ||
415 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000416 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000417 return 3;
418 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000419 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000420 if (isa<Argument>(V)) return 3;
421 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000422}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000423
Chris Lattnerc8802d22003-03-11 00:12:48 +0000424// isOnlyUse - Return true if this instruction will be deleted if we stop using
425// it.
426static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000427 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000428}
429
Chris Lattner4cb170c2004-02-23 06:38:22 +0000430// getPromotedType - Return the specified type promoted as it would be to pass
431// though a va_arg area...
432static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000433 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
434 if (ITy->getBitWidth() < 32)
435 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000436 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000437 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000438}
439
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000440/// getBitCastOperand - If the specified operand is a CastInst, a constant
441/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
442/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000443static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000444 if (Operator *O = dyn_cast<Operator>(V)) {
445 if (O->getOpcode() == Instruction::BitCast)
446 return O->getOperand(0);
447 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
448 if (GEP->hasAllZeroIndices())
449 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000450 }
Chris Lattnereed48272005-09-13 00:40:14 +0000451 return 0;
452}
453
Reid Spencer3da59db2006-11-27 01:05:10 +0000454/// This function is a wrapper around CastInst::isEliminableCastPair. It
455/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000456static Instruction::CastOps
457isEliminableCastPair(
458 const CastInst *CI, ///< The first cast instruction
459 unsigned opcode, ///< The opcode of the second cast instruction
460 const Type *DstTy, ///< The target type for the second cast instruction
461 TargetData *TD ///< The target data for pointer size
462) {
463
464 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
465 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 // Get the opcodes of the two Cast instructions
468 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
469 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000470
Chris Lattnera0e69692009-03-24 18:35:40 +0000471 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
472 DstTy, TD->getIntPtrType());
473
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))
Reid Spencere4d87aa2006-12-23 06:05:41 +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
Reid Spencer1628cec2006-10-26 06:15:43 +00002279 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002280 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002281 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002282 CastInst *CI = dyn_cast<CastInst>(LHS);
2283 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002284 if (!CI) {
2285 CI = dyn_cast<CastInst>(RHS);
2286 Other = LHS;
2287 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002288 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002289 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002290 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002291 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002292 unsigned AS =
2293 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002294 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002295 Context->getPointerType(Type::Int8Ty, AS), I);
Dan Gohman3a7a68c2009-07-17 22:25:10 +00002296 GetElementPtrInst *GEP = GetElementPtrInst::Create(I2, Other, "ctg2");
2297 // A GEP formed from an arbitrary add may overflow.
2298 cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
2299 I2 = InsertNewInstBefore(GEP, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002300 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002301 }
2302 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002303
Chris Lattner42790482007-12-20 01:56:58 +00002304 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002305 {
2306 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002307 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002308 if (!SI) {
2309 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002310 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002311 }
Chris Lattner42790482007-12-20 01:56:58 +00002312 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002313 Value *TV = SI->getTrueValue();
2314 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002315 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002316
2317 // Can we fold the add into the argument of the select?
2318 // We check both true and false select arguments for a matching subtract.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002319 if (match(FV, m_Zero(), *Context) &&
2320 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002321 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002322 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002323 if (match(TV, m_Zero(), *Context) &&
2324 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner6046fb72008-11-16 04:46:19 +00002325 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002326 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002327 }
2328 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002329
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002330 // Check for (add (sext x), y), see if we can merge this into an
2331 // integer add followed by a sext.
2332 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2333 // (add (sext x), cst) --> (sext (add x, cst'))
2334 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2335 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002336 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002337 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002338 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002339 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2340 // Insert the new, smaller add.
2341 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2342 CI, "addconv");
2343 InsertNewInstBefore(NewAdd, I);
2344 return new SExtInst(NewAdd, I.getType());
2345 }
2346 }
2347
2348 // (add (sext x), (sext y)) --> (sext (add int x, y))
2349 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2350 // Only do this if x/y have the same type, if at last one of them has a
2351 // single use (so we don't increase the number of sexts), and if the
2352 // integer add will not overflow.
2353 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2354 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2355 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2356 RHSConv->getOperand(0))) {
2357 // Insert the new integer add.
2358 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2359 RHSConv->getOperand(0),
2360 "addconv");
2361 InsertNewInstBefore(NewAdd, I);
2362 return new SExtInst(NewAdd, I.getType());
2363 }
2364 }
2365 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002366
2367 return Changed ? &I : 0;
2368}
2369
2370Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2371 bool Changed = SimplifyCommutative(I);
2372 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2373
2374 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2375 // X + 0 --> X
2376 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002377 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002378 (I.getType())->getValueAPF()))
2379 return ReplaceInstUsesWith(I, LHS);
2380 }
2381
2382 if (isa<PHINode>(LHS))
2383 if (Instruction *NV = FoldOpIntoPhi(I))
2384 return NV;
2385 }
2386
2387 // -A + B --> B - A
2388 // -A + -B --> -(A + B)
Owen Andersond672ecb2009-07-03 00:17:18 +00002389 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002390 return BinaryOperator::CreateFSub(RHS, LHSV);
2391
2392 // A + -B --> A - B
2393 if (!isa<Constant>(RHS))
Owen Andersond672ecb2009-07-03 00:17:18 +00002394 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002395 return BinaryOperator::CreateFSub(LHS, V);
2396
2397 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2398 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2399 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2400 return ReplaceInstUsesWith(I, LHS);
2401
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002402 // Check for (add double (sitofp x), y), see if we can merge this into an
2403 // integer add followed by a promotion.
2404 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2405 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2406 // ... if the constant fits in the integer value. This is useful for things
2407 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2408 // requires a constant pool load, and generally allows the add to be better
2409 // instcombined.
2410 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2411 Constant *CI =
Owen Andersond672ecb2009-07-03 00:17:18 +00002412 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002413 if (LHSConv->hasOneUse() &&
Owen Andersond672ecb2009-07-03 00:17:18 +00002414 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002415 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2416 // Insert the new integer add.
2417 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2418 CI, "addconv");
2419 InsertNewInstBefore(NewAdd, I);
2420 return new SIToFPInst(NewAdd, I.getType());
2421 }
2422 }
2423
2424 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2425 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2426 // Only do this if x/y have the same type, if at last one of them has a
2427 // single use (so we don't increase the number of int->fp conversions),
2428 // and if the integer add will not overflow.
2429 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2430 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2431 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2432 RHSConv->getOperand(0))) {
2433 // Insert the new integer add.
2434 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2435 RHSConv->getOperand(0),
2436 "addconv");
2437 InsertNewInstBefore(NewAdd, I);
2438 return new SIToFPInst(NewAdd, I.getType());
2439 }
2440 }
2441 }
2442
Chris Lattner7e708292002-06-25 16:13:24 +00002443 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002444}
2445
Chris Lattner7e708292002-06-25 16:13:24 +00002446Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002447 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002448
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002449 if (Op0 == Op1) // sub X, X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002450 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002451
Chris Lattner233f7dc2002-08-12 21:17:25 +00002452 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002453 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002455
Chris Lattnere87597f2004-10-16 18:11:37 +00002456 if (isa<UndefValue>(Op0))
2457 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2458 if (isa<UndefValue>(Op1))
2459 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2460
Chris Lattnerd65460f2003-11-05 01:06:05 +00002461 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2462 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002463 if (C->isAllOnesValue())
Owen Anderson73c6b712009-07-13 20:58:05 +00002464 return BinaryOperator::CreateNot(*Context, Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002465
Chris Lattnerd65460f2003-11-05 01:06:05 +00002466 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002467 Value *X = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002468 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Andersond672ecb2009-07-03 00:17:18 +00002469 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002470
Chris Lattner76b7a062007-01-15 07:02:54 +00002471 // -(X >>u 31) -> (X >>s 31)
2472 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002473 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002474 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002475 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002476 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002477 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002478 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002479 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002480 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002481 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002482 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002483 }
2484 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002485 }
2486 else if (SI->getOpcode() == Instruction::AShr) {
2487 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2488 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002489 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002490 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002491 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002492 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002493 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002494 }
2495 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002496 }
2497 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002498 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002499
2500 // Try to fold constant sub into select arguments.
2501 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002502 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002503 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002504
2505 // C - zext(bool) -> bool ? C - 1 : C
2506 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2507 if (ZI->getSrcTy() == Type::Int1Ty)
2508 return SelectInst::Create(ZI->getOperand(0), SubOne(C, Context), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002509 }
2510
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002511 if (I.getType() == Type::Int1Ty)
2512 return BinaryOperator::CreateXor(Op0, Op1);
2513
Chris Lattner43d84d62005-04-07 16:15:25 +00002514 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002515 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002516 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002517 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(1),
2518 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002519 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002520 return BinaryOperator::CreateNeg(*Context, Op1I->getOperand(0),
2521 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002522 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2523 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2524 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002525 return BinaryOperator::CreateSub(
2526 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002527 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002528 }
2529
Chris Lattnerfd059242003-10-15 16:48:29 +00002530 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002531 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2532 // is not used by anyone else...
2533 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002534 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002535 // Swap the two operands of the subexpr...
2536 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2537 Op1I->setOperand(0, IIOp1);
2538 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002539
Chris Lattnera2881962003-02-18 19:28:33 +00002540 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002541 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002542 }
2543
2544 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2545 //
2546 if (Op1I->getOpcode() == Instruction::And &&
2547 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2548 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2549
Chris Lattnerf523d062004-06-09 05:08:07 +00002550 Value *NewNot =
Owen Anderson73c6b712009-07-13 20:58:05 +00002551 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
2552 OtherOp, "B.not"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002553 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002554 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002555
Reid Spencerac5209e2006-10-16 23:08:08 +00002556 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002557 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002558 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002559 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002560 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002561 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002562 Context->getConstantExprNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002563
Chris Lattnerad3448c2003-02-18 19:57:07 +00002564 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002565 ConstantInt *C2 = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00002566 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2567 Constant *CP1 =
2568 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002569 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002570 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002571 }
Chris Lattner40371712002-05-09 01:29:19 +00002572 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002573 }
Chris Lattnera2881962003-02-18 19:28:33 +00002574
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002575 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2576 if (Op0I->getOpcode() == Instruction::Add) {
2577 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2578 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2579 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2580 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2581 } else if (Op0I->getOpcode() == Instruction::Sub) {
2582 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002583 return BinaryOperator::CreateNeg(*Context, Op0I->getOperand(1),
2584 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002585 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002586 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002587
Chris Lattner50af16a2004-11-13 19:50:12 +00002588 ConstantInt *C1;
Owen Andersond672ecb2009-07-03 00:17:18 +00002589 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002590 if (X == Op1) // X*C - X --> X * (C-1)
Owen Andersond672ecb2009-07-03 00:17:18 +00002591 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002592
Chris Lattner50af16a2004-11-13 19:50:12 +00002593 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Andersond672ecb2009-07-03 00:17:18 +00002594 if (X == dyn_castFoldableMul(Op1, C2, Context))
2595 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002596 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002597 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002598}
2599
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002600Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2601 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2602
2603 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Andersond672ecb2009-07-03 00:17:18 +00002604 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002605 return BinaryOperator::CreateFAdd(Op0, V);
2606
2607 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2608 if (Op1I->getOpcode() == Instruction::FAdd) {
2609 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002610 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(1),
2611 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002612 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Owen Anderson0a5372e2009-07-13 04:09:18 +00002613 return BinaryOperator::CreateFNeg(*Context, Op1I->getOperand(0),
2614 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002615 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002616 }
2617
2618 return 0;
2619}
2620
Chris Lattnera0141b92007-07-15 20:42:37 +00002621/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2622/// comparison only checks the sign bit. If it only checks the sign bit, set
2623/// TrueIfSigned if the result of the comparison is true when the input value is
2624/// signed.
2625static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2626 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002627 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002628 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2629 TrueIfSigned = true;
2630 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002631 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2632 TrueIfSigned = true;
2633 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002634 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2635 TrueIfSigned = false;
2636 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002637 case ICmpInst::ICMP_UGT:
2638 // True if LHS u> RHS and RHS == high-bit-mask - 1
2639 TrueIfSigned = true;
2640 return RHS->getValue() ==
2641 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2642 case ICmpInst::ICMP_UGE:
2643 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2644 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002645 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002646 default:
2647 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002648 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002649}
2650
Chris Lattner7e708292002-06-25 16:13:24 +00002651Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002652 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002653 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002654
Eli Friedman1694e092009-07-18 09:12:15 +00002655 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00002656 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002657
Chris Lattner233f7dc2002-08-12 21:17:25 +00002658 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002659 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2660 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002661
2662 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002663 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002664 if (SI->getOpcode() == Instruction::Shl)
2665 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002666 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002667 Context->getConstantExprShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002668
Zhou Sheng843f07672007-04-19 05:39:12 +00002669 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002670 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2671 if (CI->equalsInt(1)) // X * 1 == X
2672 return ReplaceInstUsesWith(I, Op0);
2673 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002674 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002675
Zhou Sheng97b52c22007-03-29 01:57:21 +00002676 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002677 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002678 return BinaryOperator::CreateShl(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00002679 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002680 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002681 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002682 if (Op1->isNullValue())
2683 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002684
2685 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2686 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Owen Anderson0a5372e2009-07-13 04:09:18 +00002687 return BinaryOperator::CreateNeg(*Context, Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002688
2689 // As above, vector X*splat(1.0) -> X in all defined cases.
2690 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002691 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2692 if (CI->equalsInt(1))
2693 return ReplaceInstUsesWith(I, Op0);
2694 }
2695 }
Chris Lattnera2881962003-02-18 19:28:33 +00002696 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002697
2698 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2699 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002700 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002701 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002702 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002703 Op1, "tmp");
2704 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00002705 Value *C1C2 = Context->getConstantExprMul(Op1,
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002706 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002707 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002708
2709 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002710
2711 // Try to fold constant mul into select arguments.
2712 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002713 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002714 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002715
2716 if (isa<PHINode>(Op0))
2717 if (Instruction *NV = FoldOpIntoPhi(I))
2718 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002719 }
2720
Owen Andersond672ecb2009-07-03 00:17:18 +00002721 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2722 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002723 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002724
Nick Lewycky0c730792008-11-21 07:33:58 +00002725 // (X / Y) * Y = X - (X % Y)
2726 // (X / Y) * -Y = (X % Y) - X
2727 {
2728 Value *Op1 = I.getOperand(1);
2729 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2730 if (!BO ||
2731 (BO->getOpcode() != Instruction::UDiv &&
2732 BO->getOpcode() != Instruction::SDiv)) {
2733 Op1 = Op0;
2734 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2735 }
Owen Andersond672ecb2009-07-03 00:17:18 +00002736 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky0c730792008-11-21 07:33:58 +00002737 if (BO && BO->hasOneUse() &&
2738 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2739 (BO->getOpcode() == Instruction::UDiv ||
2740 BO->getOpcode() == Instruction::SDiv)) {
2741 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2742
2743 Instruction *Rem;
2744 if (BO->getOpcode() == Instruction::UDiv)
2745 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2746 else
2747 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2748
2749 InsertNewInstBefore(Rem, I);
2750 Rem->takeName(BO);
2751
2752 if (Op1BO == Op1)
2753 return BinaryOperator::CreateSub(Op0BO, Rem);
2754 else
2755 return BinaryOperator::CreateSub(Rem, Op0BO);
2756 }
2757 }
2758
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002759 if (I.getType() == Type::Int1Ty)
2760 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2761
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002762 // If one of the operands of the multiply is a cast from a boolean value, then
2763 // we know the bool is either zero or one, so this is a 'masking' multiply.
2764 // See if we can simplify things based on how the boolean was originally
2765 // formed.
2766 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002767 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002768 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002769 BoolCast = CI;
2770 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002771 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002772 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002773 BoolCast = CI;
2774 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002775 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002776 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2777 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002778 bool TIS = false;
2779
Reid Spencere4d87aa2006-12-23 06:05:41 +00002780 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002781 // multiply into a shift/and combination.
2782 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002783 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2784 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002785 // Shift the X value right to turn it into "all signbits".
Owen Andersond672ecb2009-07-03 00:17:18 +00002786 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002787 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002788 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002789 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002790 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002791 BoolCast->getOperand(0)->getName()+
2792 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002793
2794 // If the multiply type is not the same as the source type, sign extend
2795 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002796 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002797 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2798 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002799 Instruction::CastOps opcode =
2800 (SrcBits == DstBits ? Instruction::BitCast :
2801 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2802 V = InsertCastBefore(opcode, V, I.getType(), I);
2803 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002804
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002805 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002806 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002807 }
2808 }
2809 }
2810
Chris Lattner7e708292002-06-25 16:13:24 +00002811 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002812}
2813
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002814Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2815 bool Changed = SimplifyCommutative(I);
2816 Value *Op0 = I.getOperand(0);
2817
2818 // Simplify mul instructions with a constant RHS...
2819 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2820 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2821 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2822 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2823 if (Op1F->isExactlyValue(1.0))
2824 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2825 } else if (isa<VectorType>(Op1->getType())) {
2826 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2827 // As above, vector X*splat(1.0) -> X in all defined cases.
2828 if (Constant *Splat = Op1V->getSplatValue()) {
2829 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2830 if (F->isExactlyValue(1.0))
2831 return ReplaceInstUsesWith(I, Op0);
2832 }
2833 }
2834 }
2835
2836 // Try to fold constant mul into select arguments.
2837 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2838 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2839 return R;
2840
2841 if (isa<PHINode>(Op0))
2842 if (Instruction *NV = FoldOpIntoPhi(I))
2843 return NV;
2844 }
2845
Owen Andersond672ecb2009-07-03 00:17:18 +00002846 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2847 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002848 return BinaryOperator::CreateFMul(Op0v, Op1v);
2849
2850 return Changed ? &I : 0;
2851}
2852
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002853/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2854/// instruction.
2855bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2856 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2857
2858 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2859 int NonNullOperand = -1;
2860 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2861 if (ST->isNullValue())
2862 NonNullOperand = 2;
2863 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2864 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2865 if (ST->isNullValue())
2866 NonNullOperand = 1;
2867
2868 if (NonNullOperand == -1)
2869 return false;
2870
2871 Value *SelectCond = SI->getOperand(0);
2872
2873 // Change the div/rem to use 'Y' instead of the select.
2874 I.setOperand(1, SI->getOperand(NonNullOperand));
2875
2876 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2877 // problem. However, the select, or the condition of the select may have
2878 // multiple uses. Based on our knowledge that the operand must be non-zero,
2879 // propagate the known value for the select into other uses of it, and
2880 // propagate a known value of the condition into its other users.
2881
2882 // If the select and condition only have a single use, don't bother with this,
2883 // early exit.
2884 if (SI->use_empty() && SelectCond->hasOneUse())
2885 return true;
2886
2887 // Scan the current block backward, looking for other uses of SI.
2888 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2889
2890 while (BBI != BBFront) {
2891 --BBI;
2892 // If we found a call to a function, we can't assume it will return, so
2893 // information from below it cannot be propagated above it.
2894 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2895 break;
2896
2897 // Replace uses of the select or its condition with the known values.
2898 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2899 I != E; ++I) {
2900 if (*I == SI) {
2901 *I = SI->getOperand(NonNullOperand);
2902 AddToWorkList(BBI);
2903 } else if (*I == SelectCond) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002904 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2905 Context->getConstantIntFalse();
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002906 AddToWorkList(BBI);
2907 }
2908 }
2909
2910 // If we past the instruction, quit looking for it.
2911 if (&*BBI == SI)
2912 SI = 0;
2913 if (&*BBI == SelectCond)
2914 SelectCond = 0;
2915
2916 // If we ran out of things to eliminate, break out of the loop.
2917 if (SelectCond == 0 && SI == 0)
2918 break;
2919
2920 }
2921 return true;
2922}
2923
2924
Reid Spencer1628cec2006-10-26 06:15:43 +00002925/// This function implements the transforms on div instructions that work
2926/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2927/// used by the visitors to those instructions.
2928/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002929Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002930 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002931
Chris Lattner50b2ca42008-02-19 06:12:18 +00002932 // undef / X -> 0 for integer.
2933 // undef / X -> undef for FP (the undef could be a snan).
2934 if (isa<UndefValue>(Op0)) {
2935 if (Op0->getType()->isFPOrFPVector())
2936 return ReplaceInstUsesWith(I, Op0);
Owen Andersond672ecb2009-07-03 00:17:18 +00002937 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002938 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002939
2940 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002941 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002942 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002943
Reid Spencer1628cec2006-10-26 06:15:43 +00002944 return 0;
2945}
Misha Brukmanfd939082005-04-21 23:48:37 +00002946
Reid Spencer1628cec2006-10-26 06:15:43 +00002947/// This function implements the transforms common to both integer division
2948/// instructions (udiv and sdiv). It is called by the visitors to those integer
2949/// division instructions.
2950/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002951Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002952 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2953
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002954 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002955 if (Op0 == Op1) {
2956 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002957 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002958 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00002959 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002960 }
2961
Owen Andersond672ecb2009-07-03 00:17:18 +00002962 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002963 return ReplaceInstUsesWith(I, CI);
2964 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002965
Reid Spencer1628cec2006-10-26 06:15:43 +00002966 if (Instruction *Common = commonDivTransforms(I))
2967 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002968
2969 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2970 // This does not apply for fdiv.
2971 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2972 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002973
2974 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2975 // div X, 1 == X
2976 if (RHS->equalsInt(1))
2977 return ReplaceInstUsesWith(I, Op0);
2978
2979 // (X / C1) / C2 -> X / (C1*C2)
2980 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2981 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2982 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002983 if (MultiplyOverflows(RHS, LHSRHS,
2984 I.getOpcode()==Instruction::SDiv, Context))
2985 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002986 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002987 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00002988 Context->getConstantExprMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002989 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002990
Reid Spencerbca0e382007-03-23 20:05:17 +00002991 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994 return R;
2995 if (isa<PHINode>(Op0))
2996 if (Instruction *NV = FoldOpIntoPhi(I))
2997 return NV;
2998 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002999 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003000
Chris Lattnera2881962003-02-18 19:28:33 +00003001 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003002 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003003 if (LHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003004 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003005
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003006 // It can't be division by zero, hence it must be division by one.
3007 if (I.getType() == Type::Int1Ty)
3008 return ReplaceInstUsesWith(I, Op0);
3009
Nick Lewycky895f0852008-11-27 20:21:08 +00003010 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3011 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3012 // div X, 1 == X
3013 if (X->isOne())
3014 return ReplaceInstUsesWith(I, Op0);
3015 }
3016
Reid Spencer1628cec2006-10-26 06:15:43 +00003017 return 0;
3018}
3019
3020Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3022
3023 // Handle the integer div common cases
3024 if (Instruction *Common = commonIDivTransforms(I))
3025 return Common;
3026
Reid Spencer1628cec2006-10-26 06:15:43 +00003027 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003028 // X udiv C^2 -> X >> C
3029 // Check to see if this is an unsigned division with an exact power of 2,
3030 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003031 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003032 return BinaryOperator::CreateLShr(Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00003033 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003034
3035 // X udiv C, where C >= signbit
3036 if (C->getValue().isNegative()) {
Owen Anderson333c4002009-07-09 23:48:35 +00003037 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3038 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky8ca52482008-11-27 22:41:10 +00003039 I);
Owen Andersond672ecb2009-07-03 00:17:18 +00003040 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3041 Context->getConstantInt(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003042 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003043 }
3044
3045 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003046 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003047 if (RHSI->getOpcode() == Instruction::Shl &&
3048 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003049 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003050 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003051 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003052 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003053 if (uint32_t C2 = C1.logBase2()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003054 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003055 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003056 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003057 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003058 }
3059 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003060 }
3061
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3063 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003064 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003065 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003066 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003067 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003068 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003069 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003070 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003071 // Construct the "on true" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003072 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003073 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003074 Op0, TC, SI->getName()+".t");
3075 TSI = InsertNewInstBefore(TSI, I);
3076
3077 // Construct the "on false" case of the select
Owen Andersond672ecb2009-07-03 00:17:18 +00003078 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003079 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003080 Op0, FC, SI->getName()+".f");
3081 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003082
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003083 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003084 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003085 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003086 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003087 return 0;
3088}
3089
Reid Spencer1628cec2006-10-26 06:15:43 +00003090Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3091 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3092
3093 // Handle the integer div common cases
3094 if (Instruction *Common = commonIDivTransforms(I))
3095 return Common;
3096
3097 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3098 // sdiv X, -1 == -X
3099 if (RHS->isAllOnesValue())
Owen Anderson0a5372e2009-07-13 04:09:18 +00003100 return BinaryOperator::CreateNeg(*Context, Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003101 }
3102
3103 // If the sign bits of both operands are zero (i.e. we can prove they are
3104 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003105 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003106 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003107 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003108 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003109 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003110 }
3111 }
3112
3113 return 0;
3114}
3115
3116Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3117 return commonDivTransforms(I);
3118}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003119
Reid Spencer0a783f72006-11-02 01:53:59 +00003120/// This function implements the transforms on rem instructions that work
3121/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3122/// is used by the visitors to those instructions.
3123/// @brief Transforms common to all three rem instructions
3124Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003126
Chris Lattner50b2ca42008-02-19 06:12:18 +00003127 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3128 if (I.getType()->isFPOrFPVector())
3129 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersond672ecb2009-07-03 00:17:18 +00003130 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003131 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003132 if (isa<UndefValue>(Op1))
3133 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003134
3135 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003136 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3137 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003138
Reid Spencer0a783f72006-11-02 01:53:59 +00003139 return 0;
3140}
3141
3142/// This function implements the transforms common to both integer remainder
3143/// instructions (urem and srem). It is called by the visitors to those integer
3144/// remainder instructions.
3145/// @brief Common integer remainder transforms
3146Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3147 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3148
3149 if (Instruction *common = commonRemTransforms(I))
3150 return common;
3151
Dale Johannesened6af242009-01-21 00:35:19 +00003152 // 0 % X == 0 for integer, we don't need to preserve faults!
3153 if (Constant *LHS = dyn_cast<Constant>(Op0))
3154 if (LHS->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00003155 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003156
Chris Lattner857e8cd2004-12-12 21:48:58 +00003157 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003158 // X % 0 == undef, we don't need to preserve faults!
3159 if (RHS->equalsInt(0))
Owen Andersond672ecb2009-07-03 00:17:18 +00003160 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003161
Chris Lattnera2881962003-02-18 19:28:33 +00003162 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003163 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003164
Chris Lattner97943922006-02-28 05:49:21 +00003165 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3166 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3167 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3168 return R;
3169 } else if (isa<PHINode>(Op0I)) {
3170 if (Instruction *NV = FoldOpIntoPhi(I))
3171 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003172 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003173
3174 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003175 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003176 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003177 }
Chris Lattnera2881962003-02-18 19:28:33 +00003178 }
3179
Reid Spencer0a783f72006-11-02 01:53:59 +00003180 return 0;
3181}
3182
3183Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3184 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3185
3186 if (Instruction *common = commonIRemTransforms(I))
3187 return common;
3188
3189 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3190 // X urem C^2 -> X and C
3191 // Check to see if this is an unsigned remainder with an exact power of 2,
3192 // if so, convert to a bitwise and.
3193 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003194 if (C->getValue().isPowerOf2())
Owen Andersond672ecb2009-07-03 00:17:18 +00003195 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Reid Spencer0a783f72006-11-02 01:53:59 +00003196 }
3197
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003198 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3200 if (RHSI->getOpcode() == Instruction::Shl &&
3201 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003202 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson73c6b712009-07-13 20:58:05 +00003203 Constant *N1 = Context->getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003204 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003205 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003206 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003207 }
3208 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003209 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003210
Reid Spencer0a783f72006-11-02 01:53:59 +00003211 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3212 // where C1&C2 are powers of two.
3213 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3214 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3215 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3216 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003217 if ((STO->getValue().isPowerOf2()) &&
3218 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003219 Value *TrueAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003220 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3221 SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003222 Value *FalseAnd = InsertNewInstBefore(
Owen Andersond672ecb2009-07-03 00:17:18 +00003223 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3224 SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003225 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003226 }
3227 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003228 }
3229
Chris Lattner3f5b8772002-05-06 16:14:14 +00003230 return 0;
3231}
3232
Reid Spencer0a783f72006-11-02 01:53:59 +00003233Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3234 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3235
Dan Gohmancff55092007-11-05 23:16:33 +00003236 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003237 if (Instruction *common = commonIRemTransforms(I))
3238 return common;
3239
Owen Andersond672ecb2009-07-03 00:17:18 +00003240 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewycky23c04302008-09-03 06:24:21 +00003241 if (!isa<Constant>(RHSNeg) ||
3242 (isa<ConstantInt>(RHSNeg) &&
3243 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003244 // X % -Y -> X % Y
3245 AddUsesToWorkList(I);
3246 I.setOperand(1, RHSNeg);
3247 return &I;
3248 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003249
Dan Gohmancff55092007-11-05 23:16:33 +00003250 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003251 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003252 if (I.getType()->isInteger()) {
3253 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3254 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3255 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003256 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003257 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003258 }
3259
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003260 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003261 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3262 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003263
Nick Lewycky9dce8732008-12-20 16:48:00 +00003264 bool hasNegative = false;
3265 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3266 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3267 if (RHS->getValue().isNegative())
3268 hasNegative = true;
3269
3270 if (hasNegative) {
3271 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003272 for (unsigned i = 0; i != VWidth; ++i) {
3273 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3274 if (RHS->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00003275 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003276 else
3277 Elts[i] = RHS;
3278 }
3279 }
3280
Owen Andersond672ecb2009-07-03 00:17:18 +00003281 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003282 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003283 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003284 I.setOperand(1, NewRHSV);
3285 return &I;
3286 }
3287 }
3288 }
3289
Reid Spencer0a783f72006-11-02 01:53:59 +00003290 return 0;
3291}
3292
3293Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003294 return commonRemTransforms(I);
3295}
3296
Chris Lattner457dd822004-06-09 07:59:58 +00003297// isOneBitSet - Return true if there is exactly one bit set in the specified
3298// constant.
3299static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003300 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003301}
3302
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003303// isHighOnes - Return true if the constant is of the form 1+0+.
3304// This is the same as lowones(~X).
3305static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003306 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003307}
3308
Reid Spencere4d87aa2006-12-23 06:05:41 +00003309/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003310/// are carefully arranged to allow folding of expressions such as:
3311///
3312/// (A < B) | (A > B) --> (A != B)
3313///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003314/// Note that this is only valid if the first and second predicates have the
3315/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003316///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003317/// Three bits are used to represent the condition, as follows:
3318/// 0 A > B
3319/// 1 A == B
3320/// 2 A < B
3321///
3322/// <=> Value Definition
3323/// 000 0 Always false
3324/// 001 1 A > B
3325/// 010 2 A == B
3326/// 011 3 A >= B
3327/// 100 4 A < B
3328/// 101 5 A != B
3329/// 110 6 A <= B
3330/// 111 7 Always true
3331///
3332static unsigned getICmpCode(const ICmpInst *ICI) {
3333 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003334 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003335 case ICmpInst::ICMP_UGT: return 1; // 001
3336 case ICmpInst::ICMP_SGT: return 1; // 001
3337 case ICmpInst::ICMP_EQ: return 2; // 010
3338 case ICmpInst::ICMP_UGE: return 3; // 011
3339 case ICmpInst::ICMP_SGE: return 3; // 011
3340 case ICmpInst::ICMP_ULT: return 4; // 100
3341 case ICmpInst::ICMP_SLT: return 4; // 100
3342 case ICmpInst::ICMP_NE: return 5; // 101
3343 case ICmpInst::ICMP_ULE: return 6; // 110
3344 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003345 // True -> 7
3346 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003347 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003348 return 0;
3349 }
3350}
3351
Evan Cheng8db90722008-10-14 17:15:11 +00003352/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3353/// predicate into a three bit mask. It also returns whether it is an ordered
3354/// predicate by reference.
3355static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3356 isOrdered = false;
3357 switch (CC) {
3358 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3359 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003360 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3361 case FCmpInst::FCMP_UGT: return 1; // 001
3362 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3363 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003364 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3365 case FCmpInst::FCMP_UGE: return 3; // 011
3366 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3367 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003368 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3369 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003370 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3371 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003372 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003373 default:
3374 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003375 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003376 return 0;
3377 }
3378}
3379
Reid Spencere4d87aa2006-12-23 06:05:41 +00003380/// getICmpValue - This is the complement of getICmpCode, which turns an
3381/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003382/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003383/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003384static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003385 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003387 default: llvm_unreachable("Illegal ICmp code!");
Owen Andersond672ecb2009-07-03 00:17:18 +00003388 case 0: return Context->getConstantIntFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 case 1:
3390 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003391 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392 else
Owen Anderson333c4002009-07-09 23:48:35 +00003393 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3394 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 case 3:
3396 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003397 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003398 else
Owen Anderson333c4002009-07-09 23:48:35 +00003399 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 case 4:
3401 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003402 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403 else
Owen Anderson333c4002009-07-09 23:48:35 +00003404 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3405 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003406 case 6:
3407 if (sign)
Owen Anderson333c4002009-07-09 23:48:35 +00003408 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003409 else
Owen Anderson333c4002009-07-09 23:48:35 +00003410 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003411 case 7: return Context->getConstantIntTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003412 }
3413}
3414
Evan Cheng8db90722008-10-14 17:15:11 +00003415/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3416/// opcode and two operands into either a FCmp instruction. isordered is passed
3417/// in to determine which kind of predicate to use in the new fcmp instruction.
3418static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003419 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003420 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003421 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003422 case 0:
3423 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003424 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003425 else
Owen Anderson333c4002009-07-09 23:48:35 +00003426 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003427 case 1:
3428 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003429 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003430 else
Owen Anderson333c4002009-07-09 23:48:35 +00003431 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003432 case 2:
3433 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003434 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003435 else
Owen Anderson333c4002009-07-09 23:48:35 +00003436 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003437 case 3:
3438 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003439 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003440 else
Owen Anderson333c4002009-07-09 23:48:35 +00003441 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003442 case 4:
3443 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003444 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003445 else
Owen Anderson333c4002009-07-09 23:48:35 +00003446 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003447 case 5:
3448 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003449 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003450 else
Owen Anderson333c4002009-07-09 23:48:35 +00003451 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003452 case 6:
3453 if (isordered)
Owen Anderson333c4002009-07-09 23:48:35 +00003454 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003455 else
Owen Anderson333c4002009-07-09 23:48:35 +00003456 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00003457 case 7: return Context->getConstantIntTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003458 }
3459}
3460
Chris Lattnerb9553d62008-11-16 04:55:20 +00003461/// PredicatesFoldable - Return true if both predicates match sign or if at
3462/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003463static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3464 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003465 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3466 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467}
3468
3469namespace {
3470// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3471struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003472 InstCombiner &IC;
3473 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003474 ICmpInst::Predicate pred;
3475 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3476 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3477 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3480 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003481 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3482 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003483 return false;
3484 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003485 Instruction *apply(Instruction &Log) const {
3486 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3487 if (ICI->getOperand(0) != LHS) {
3488 assert(ICI->getOperand(1) == LHS);
3489 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003490 }
3491
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003492 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003494 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 unsigned Code;
3496 switch (Log.getOpcode()) {
3497 case Instruction::And: Code = LHSCode & RHSCode; break;
3498 case Instruction::Or: Code = LHSCode | RHSCode; break;
3499 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003500 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501 }
3502
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003503 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3504 ICmpInst::isSignedPredicate(ICI->getPredicate());
3505
Owen Andersond672ecb2009-07-03 00:17:18 +00003506 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003507 if (Instruction *I = dyn_cast<Instruction>(RV))
3508 return I;
3509 // Otherwise, it's a constant boolean value...
3510 return IC.ReplaceInstUsesWith(Log, RV);
3511 }
3512};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003513} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003514
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3516// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003517// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003519 ConstantInt *OpRHS,
3520 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 BinaryOperator &TheAnd) {
3522 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003523 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003524 if (!Op->isShift())
Owen Andersond672ecb2009-07-03 00:17:18 +00003525 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003526
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 switch (Op->getOpcode()) {
3528 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003529 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003530 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003531 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003532 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003533 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003534 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535 }
3536 break;
3537 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003538 if (Together == AndRHS) // (X | C) & C --> C
3539 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003540
Chris Lattner6e7ba452005-01-01 16:22:27 +00003541 if (Op->hasOneUse() && Together != OpRHS) {
3542 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003543 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003544 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003545 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003546 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547 }
3548 break;
3549 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003550 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003551 // Adding a one to a single bit bit-field should be turned into an XOR
3552 // of the bit. First thing to check is to see if this AND is with a
3553 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003554 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555
3556 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003557 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003558 // Ok, at this point, we know that we are masking the result of the
3559 // ADD down to exactly one bit. If the constant we are adding has
3560 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003561 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003562
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003563 // Check to see if any bits below the one bit set in AndRHSV are set.
3564 if ((AddRHS & (AndRHSV-1)) == 0) {
3565 // If not, the only thing that can effect the output of the AND is
3566 // the bit specified by AndRHSV. If that bit is set, the effect of
3567 // the XOR is to toggle the bit. If it is clear, then the ADD has
3568 // no effect.
3569 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3570 TheAnd.setOperand(0, X);
3571 return &TheAnd;
3572 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003573 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003574 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003575 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003576 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003577 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003578 }
3579 }
3580 }
3581 }
3582 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003583
3584 case Instruction::Shl: {
3585 // We know that the AND will not produce any of the bits shifted in, so if
3586 // the anded constant includes them, clear them now!
3587 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003588 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003589 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003590 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003591 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003592
Zhou Sheng290bec52007-03-29 08:15:12 +00003593 if (CI->getValue() == ShlMask) {
3594 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003595 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3596 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003597 TheAnd.setOperand(1, CI);
3598 return &TheAnd;
3599 }
3600 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003601 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003602 case Instruction::LShr:
3603 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003604 // We know that the AND will not produce any of the bits shifted in, so if
3605 // the anded constant includes them, clear them now! This only applies to
3606 // unsigned shifts, because a signed shr may bring in set bits!
3607 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003608 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003609 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003610 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003611 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003612
Zhou Sheng290bec52007-03-29 08:15:12 +00003613 if (CI->getValue() == ShrMask) {
3614 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003615 return ReplaceInstUsesWith(TheAnd, Op);
3616 } else if (CI != AndRHS) {
3617 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3618 return &TheAnd;
3619 }
3620 break;
3621 }
3622 case Instruction::AShr:
3623 // Signed shr.
3624 // See if this is shifting in some sign extension, then masking it out
3625 // with an and.
3626 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003627 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003628 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003629 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00003630 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003631 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003632 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003633 // Make the argument unsigned.
3634 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003635 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003636 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003637 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003638 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003639 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003640 }
3641 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003642 }
3643 return 0;
3644}
3645
Chris Lattner8b170942002-08-09 23:47:40 +00003646
Chris Lattnera96879a2004-09-29 17:40:11 +00003647/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3648/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3650/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003651/// insert new instructions.
3652Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 bool isSigned, bool Inside,
3654 Instruction &IB) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003655 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003656 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003657 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658
Chris Lattnera96879a2004-09-29 17:40:11 +00003659 if (Inside) {
3660 if (Lo == Hi) // Trivially false.
Owen Anderson333c4002009-07-09 23:48:35 +00003661 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003662
Reid Spencere4d87aa2006-12-23 06:05:41 +00003663 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003664 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003665 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003666 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson333c4002009-07-09 23:48:35 +00003667 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668 }
3669
3670 // Emit V-Lo <u Hi-Lo
Owen Andersond672ecb2009-07-03 00:17:18 +00003671 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003672 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003673 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003674 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003675 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003676 }
3677
3678 if (Lo == Hi) // Trivially true.
Owen Anderson333c4002009-07-09 23:48:35 +00003679 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003680
Reid Spencere4e40032007-03-21 23:19:50 +00003681 // V < Min || V >= Hi -> V > Hi-1
Owen Andersond672ecb2009-07-03 00:17:18 +00003682 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003683 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 ICmpInst::Predicate pred = (isSigned ?
3685 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson333c4002009-07-09 23:48:35 +00003686 return new ICmpInst(*Context, pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003687 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003688
Reid Spencere4e40032007-03-21 23:19:50 +00003689 // Emit V-Lo >u Hi-1-Lo
3690 // Note that Hi has already had one subtracted from it, above.
Owen Andersond672ecb2009-07-03 00:17:18 +00003691 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003692 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003693 InsertNewInstBefore(Add, IB);
Owen Andersond672ecb2009-07-03 00:17:18 +00003694 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson333c4002009-07-09 23:48:35 +00003695 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003696}
3697
Chris Lattner7203e152005-09-18 07:22:02 +00003698// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3699// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3700// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3701// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003702static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003703 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003704 uint32_t BitWidth = Val->getType()->getBitWidth();
3705 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003706
3707 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003708 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003709 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003710 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003711 return true;
3712}
3713
Chris Lattner7203e152005-09-18 07:22:02 +00003714/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3715/// where isSub determines whether the operator is a sub. If we can fold one of
3716/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003717///
3718/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3719/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3720/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3721///
3722/// return (A +/- B).
3723///
3724Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003725 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003726 Instruction &I) {
3727 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3728 if (!LHSI || LHSI->getNumOperands() != 2 ||
3729 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3730
3731 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3732
3733 switch (LHSI->getOpcode()) {
3734 default: return 0;
3735 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00003736 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003737 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003738 if ((Mask->getValue().countLeadingZeros() +
3739 Mask->getValue().countPopulation()) ==
3740 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003741 break;
3742
3743 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3744 // part, we don't need any explicit masks to take them out of A. If that
3745 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003746 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003747 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003748 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003749 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003750 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003751 break;
3752 }
3753 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003754 return 0;
3755 case Instruction::Or:
3756 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003757 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003758 if ((Mask->getValue().countLeadingZeros() +
3759 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersond672ecb2009-07-03 00:17:18 +00003760 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003761 break;
3762 return 0;
3763 }
3764
3765 Instruction *New;
3766 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003767 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003768 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003769 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003770 return InsertNewInstBefore(New, I);
3771}
3772
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003773/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3774Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3775 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003776 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003777 ConstantInt *LHSCst, *RHSCst;
3778 ICmpInst::Predicate LHSCC, RHSCC;
3779
Chris Lattnerea065fb2008-11-16 05:10:52 +00003780 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003781 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3782 m_ConstantInt(LHSCst)), *Context) ||
3783 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3784 m_ConstantInt(RHSCst)), *Context))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003785 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003786
3787 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3788 // where C is a power of 2
3789 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3790 LHSCst->getValue().isPowerOf2()) {
3791 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3792 InsertNewInstBefore(NewOr, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003793 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003794 }
3795
3796 // From here on, we only handle:
3797 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3798 if (Val != Val2) return 0;
3799
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003800 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3801 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3802 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3803 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3804 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3805 return 0;
3806
3807 // We can't fold (ugt x, C) & (sgt x, C2).
3808 if (!PredicatesFoldable(LHSCC, RHSCC))
3809 return 0;
3810
3811 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003812 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003813 if (ICmpInst::isSignedPredicate(LHSCC) ||
3814 (ICmpInst::isEquality(LHSCC) &&
3815 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003816 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003817 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003818 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3819
3820 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003821 std::swap(LHS, RHS);
3822 std::swap(LHSCst, RHSCst);
3823 std::swap(LHSCC, RHSCC);
3824 }
3825
3826 // At this point, we know we have have two icmp instructions
3827 // comparing a value against two constants and and'ing the result
3828 // together. Because of the above check, we know that we only have
3829 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3830 // (from the FoldICmpLogical check above), that the two constants
3831 // are not equal and that the larger constant is on the RHS
3832 assert(LHSCst != RHSCst && "Compares not folded above?");
3833
3834 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003835 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003836 case ICmpInst::ICMP_EQ:
3837 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003838 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003839 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3840 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3841 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003842 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003843 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3844 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3845 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3846 return ReplaceInstUsesWith(I, LHS);
3847 }
3848 case ICmpInst::ICMP_NE:
3849 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003850 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003851 case ICmpInst::ICMP_ULT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003852 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003853 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003854 break; // (X != 13 & X u< 15) -> no change
3855 case ICmpInst::ICMP_SLT:
Owen Andersond672ecb2009-07-03 00:17:18 +00003856 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson333c4002009-07-09 23:48:35 +00003857 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 break; // (X != 13 & X s< 15) -> no change
3859 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3860 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3861 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3862 return ReplaceInstUsesWith(I, RHS);
3863 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003864 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3865 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003866 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3867 Val->getName()+".off");
3868 InsertNewInstBefore(Add, I);
Owen Anderson333c4002009-07-09 23:48:35 +00003869 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Andersond672ecb2009-07-03 00:17:18 +00003870 Context->getConstantInt(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003871 }
3872 break; // (X != 13 & X != 15) -> no change
3873 }
3874 break;
3875 case ICmpInst::ICMP_ULT:
3876 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003877 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003878 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3879 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003880 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3882 break;
3883 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3884 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3885 return ReplaceInstUsesWith(I, LHS);
3886 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3887 break;
3888 }
3889 break;
3890 case ICmpInst::ICMP_SLT:
3891 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003892 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003893 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3894 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Andersond672ecb2009-07-03 00:17:18 +00003895 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003896 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3897 break;
3898 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3899 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3900 return ReplaceInstUsesWith(I, LHS);
3901 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3902 break;
3903 }
3904 break;
3905 case ICmpInst::ICMP_UGT:
3906 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003907 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003908 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3909 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3910 return ReplaceInstUsesWith(I, RHS);
3911 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3912 break;
3913 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003914 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003915 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003916 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003917 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003918 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3919 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003920 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3921 break;
3922 }
3923 break;
3924 case ICmpInst::ICMP_SGT:
3925 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003926 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003927 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3928 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3929 return ReplaceInstUsesWith(I, RHS);
3930 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3931 break;
3932 case ICmpInst::ICMP_NE:
Owen Andersond672ecb2009-07-03 00:17:18 +00003933 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson333c4002009-07-09 23:48:35 +00003934 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003935 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003936 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Andersond672ecb2009-07-03 00:17:18 +00003937 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3938 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003939 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3940 break;
3941 }
3942 break;
3943 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003944
3945 return 0;
3946}
3947
3948
Chris Lattner7e708292002-06-25 16:13:24 +00003949Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003950 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003951 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003952
Chris Lattnere87597f2004-10-16 18:11:37 +00003953 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00003954 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003955
Chris Lattner6e7ba452005-01-01 16:22:27 +00003956 // and X, X = X
3957 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003958 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003959
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003960 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003961 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003962 if (SimplifyDemandedInstructionBits(I))
3963 return &I;
3964 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003965 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003966 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003967 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003968 } else if (isa<ConstantAggregateZero>(Op1)) {
3969 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003970 }
3971 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003972
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003973 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003974 const APInt& AndRHSMask = AndRHS->getValue();
3975 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003976
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003977 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003978 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003979 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003980 Value *Op0LHS = Op0I->getOperand(0);
3981 Value *Op0RHS = Op0I->getOperand(1);
3982 switch (Op0I->getOpcode()) {
3983 case Instruction::Xor:
3984 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003985 // If the mask is only needed on one incoming arm, push it up.
3986 if (Op0I->hasOneUse()) {
3987 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3988 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003989 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003990 Op0RHS->getName()+".masked");
3991 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003992 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003993 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003994 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003995 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003996 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3997 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003998 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003999 Op0LHS->getName()+".masked");
4000 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004001 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004002 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4003 }
4004 }
4005
Chris Lattner6e7ba452005-01-01 16:22:27 +00004006 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004007 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004008 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4009 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4010 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4011 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004012 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004013 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004014 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004015 break;
4016
4017 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004018 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4019 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4020 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4021 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004022 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004023
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004024 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4025 // has 1's for all bits that the subtraction with A might affect.
4026 if (Op0I->hasOneUse()) {
4027 uint32_t BitWidth = AndRHSMask.getBitWidth();
4028 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4029 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4030
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004031 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004032 if (!(A && A->isZero()) && // avoid infinite recursion.
4033 MaskedValueIsZero(Op0LHS, Mask)) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00004034 Instruction *NewNeg = BinaryOperator::CreateNeg(*Context, Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004035 InsertNewInstBefore(NewNeg, I);
4036 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4037 }
4038 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004039 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004040
4041 case Instruction::Shl:
4042 case Instruction::LShr:
4043 // (1 << x) & 1 --> zext(x == 0)
4044 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004045 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson333c4002009-07-09 23:48:35 +00004046 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4047 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004048 InsertNewInstBefore(NewICmp, I);
4049 return new ZExtInst(NewICmp, I.getType());
4050 }
4051 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004052 }
4053
Chris Lattner58403262003-07-23 19:25:52 +00004054 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004055 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004056 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004057 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004058 // If this is an integer truncation or change from signed-to-unsigned, and
4059 // if the source is an and/or with immediate, transform it. This
4060 // frequently occurs for bitfield accesses.
4061 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004062 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004063 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004064 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004065 if (CastOp->getOpcode() == Instruction::And) {
4066 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004067 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4068 // This will fold the two constants together, which may allow
4069 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004070 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004071 CastOp->getOperand(0), I.getType(),
4072 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004073 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004074 // trunc_or_bitcast(C1)&C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004075 Constant *C3 =
4076 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4077 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004078 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004079 } else if (CastOp->getOpcode() == Instruction::Or) {
4080 // Change: and (cast (or X, C1) to T), C2
4081 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Andersond672ecb2009-07-03 00:17:18 +00004082 Constant *C3 =
4083 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4084 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4085 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004086 return ReplaceInstUsesWith(I, AndRHS);
4087 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004088 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004089 }
Chris Lattner06782f82003-07-23 19:36:21 +00004090 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004091
4092 // Try to fold constant and into select arguments.
4093 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004095 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004096 if (isa<PHINode>(Op0))
4097 if (Instruction *NV = FoldOpIntoPhi(I))
4098 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004099 }
4100
Owen Andersond672ecb2009-07-03 00:17:18 +00004101 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4102 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Chris Lattnera2881962003-02-18 19:28:33 +00004103
Chris Lattner5b62aa72004-06-18 06:07:51 +00004104 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00004105 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004106
Misha Brukmancb6267b2004-07-30 12:50:08 +00004107 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004108 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004109 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004110 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004111 InsertNewInstBefore(Or, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004112 return BinaryOperator::CreateNot(*Context, Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004113 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004114
4115 {
Chris Lattner003b6202007-06-15 05:58:24 +00004116 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004117 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004118 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4119 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004120
4121 // (A|B) & ~(A&B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004122 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004123 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004124 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004125 }
4126 }
4127
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004128 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004129 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4130 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004131
4132 // ~(A&B) & (A|B) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004133 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Chris Lattner003b6202007-06-15 05:58:24 +00004134 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004136 }
4137 }
Chris Lattner64daab52006-04-01 08:03:55 +00004138
4139 if (Op0->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004140 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004141 if (A == Op1) { // (A^B)&A -> A&(A^B)
4142 I.swapOperands(); // Simplify below
4143 std::swap(Op0, Op1);
4144 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4145 cast<BinaryOperator>(Op0)->swapOperands();
4146 I.swapOperands(); // Simplify below
4147 std::swap(Op0, Op1);
4148 }
4149 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004150
Chris Lattner64daab52006-04-01 08:03:55 +00004151 if (Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004152 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner64daab52006-04-01 08:03:55 +00004153 if (B == Op0) { // B&(A^B) -> B&(B^A)
4154 cast<BinaryOperator>(Op1)->swapOperands();
4155 std::swap(A, B);
4156 }
4157 if (A == Op0) { // A&(A^B) -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00004158 Instruction *NotB = BinaryOperator::CreateNot(*Context, B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004159 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004160 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004161 }
4162 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004163
4164 // (A&((~A)|B)) -> A&B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004165 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4166 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004167 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004168 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4169 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004170 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004171 }
4172
Reid Spencere4d87aa2006-12-23 06:05:41 +00004173 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4174 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004175 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004176 return R;
4177
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004178 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4179 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4180 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004181 }
4182
Chris Lattner6fc205f2006-05-05 06:39:07 +00004183 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004184 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4185 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4186 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4187 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004188 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004189 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004190 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4191 I.getType(), TD) &&
4192 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4193 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004194 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004195 Op1C->getOperand(0),
4196 I.getName());
4197 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004198 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004199 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004200 }
Chris Lattnere511b742006-11-14 07:46:50 +00004201
4202 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004203 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4204 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4205 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004206 SI0->getOperand(1) == SI1->getOperand(1) &&
4207 (SI0->hasOneUse() || SI1->hasOneUse())) {
4208 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004209 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004210 SI1->getOperand(0),
4211 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004212 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004213 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004214 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004215 }
4216
Evan Cheng8db90722008-10-14 17:15:11 +00004217 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004218 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4219 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4220 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004221 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4222 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004223 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4224 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4225 // If either of the constants are nans, then the whole thing returns
4226 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004227 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004228 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00004229 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4230 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004231 }
Evan Cheng8db90722008-10-14 17:15:11 +00004232 } else {
4233 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4234 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004235 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4236 m_Value(Op0RHS)), *Context) &&
4237 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4238 m_Value(Op1RHS)), *Context)) {
Evan Cheng4990b252008-10-14 18:13:38 +00004239 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4240 // Swap RHS operands to match LHS.
4241 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4242 std::swap(Op1LHS, Op1RHS);
4243 }
Evan Cheng8db90722008-10-14 17:15:11 +00004244 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4245 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4246 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004247 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4248 Op0LHS, Op0RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00004249 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4250 Op1CC == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004251 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004252 else if (Op0CC == FCmpInst::FCMP_TRUE)
4253 return ReplaceInstUsesWith(I, Op1);
4254 else if (Op1CC == FCmpInst::FCMP_TRUE)
4255 return ReplaceInstUsesWith(I, Op0);
4256 bool Op0Ordered;
4257 bool Op1Ordered;
4258 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4259 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4260 if (Op1Pred == 0) {
4261 std::swap(Op0, Op1);
4262 std::swap(Op0Pred, Op1Pred);
4263 std::swap(Op0Ordered, Op1Ordered);
4264 }
4265 if (Op0Pred == 0) {
4266 // uno && ueq -> uno && (uno || eq) -> ueq
4267 // ord && olt -> ord && (ord && lt) -> olt
4268 if (Op0Ordered == Op1Ordered)
4269 return ReplaceInstUsesWith(I, Op1);
4270 // uno && oeq -> uno && (ord && eq) -> false
4271 // uno && ord -> false
4272 if (!Op0Ordered)
Owen Andersond672ecb2009-07-03 00:17:18 +00004273 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng8db90722008-10-14 17:15:11 +00004274 // ord && ueq -> ord && (uno || eq) -> oeq
4275 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004276 Op0LHS, Op0RHS, Context));
Evan Cheng8db90722008-10-14 17:15:11 +00004277 }
4278 }
4279 }
4280 }
Chris Lattner99c65742007-10-24 05:38:08 +00004281 }
4282 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004283
Chris Lattner7e708292002-06-25 16:13:24 +00004284 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004285}
4286
Chris Lattner8c34cd22008-10-05 02:13:19 +00004287/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4288/// capable of providing pieces of a bswap. The subexpression provides pieces
4289/// of a bswap if it is proven that each of the non-zero bytes in the output of
4290/// the expression came from the corresponding "byte swapped" byte in some other
4291/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4292/// we know that the expression deposits the low byte of %X into the high byte
4293/// of the bswap result and that all other bytes are zero. This expression is
4294/// accepted, the high byte of ByteValues is set to X to indicate a correct
4295/// match.
4296///
4297/// This function returns true if the match was unsuccessful and false if so.
4298/// On entry to the function the "OverallLeftShift" is a signed integer value
4299/// indicating the number of bytes that the subexpression is later shifted. For
4300/// example, if the expression is later right shifted by 16 bits, the
4301/// OverallLeftShift value would be -2 on entry. This is used to specify which
4302/// byte of ByteValues is actually being set.
4303///
4304/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4305/// byte is masked to zero by a user. For example, in (X & 255), X will be
4306/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4307/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4308/// always in the local (OverallLeftShift) coordinate space.
4309///
4310static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4311 SmallVector<Value*, 8> &ByteValues) {
4312 if (Instruction *I = dyn_cast<Instruction>(V)) {
4313 // If this is an or instruction, it may be an inner node of the bswap.
4314 if (I->getOpcode() == Instruction::Or) {
4315 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4316 ByteValues) ||
4317 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4318 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004319 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004320
4321 // If this is a logical shift by a constant multiple of 8, recurse with
4322 // OverallLeftShift and ByteMask adjusted.
4323 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4324 unsigned ShAmt =
4325 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4326 // Ensure the shift amount is defined and of a byte value.
4327 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4328 return true;
4329
4330 unsigned ByteShift = ShAmt >> 3;
4331 if (I->getOpcode() == Instruction::Shl) {
4332 // X << 2 -> collect(X, +2)
4333 OverallLeftShift += ByteShift;
4334 ByteMask >>= ByteShift;
4335 } else {
4336 // X >>u 2 -> collect(X, -2)
4337 OverallLeftShift -= ByteShift;
4338 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004339 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004340 }
4341
4342 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4343 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4344
4345 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4346 ByteValues);
4347 }
4348
4349 // If this is a logical 'and' with a mask that clears bytes, clear the
4350 // corresponding bytes in ByteMask.
4351 if (I->getOpcode() == Instruction::And &&
4352 isa<ConstantInt>(I->getOperand(1))) {
4353 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4354 unsigned NumBytes = ByteValues.size();
4355 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4356 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4357
4358 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4359 // If this byte is masked out by a later operation, we don't care what
4360 // the and mask is.
4361 if ((ByteMask & (1 << i)) == 0)
4362 continue;
4363
4364 // If the AndMask is all zeros for this byte, clear the bit.
4365 APInt MaskB = AndMask & Byte;
4366 if (MaskB == 0) {
4367 ByteMask &= ~(1U << i);
4368 continue;
4369 }
4370
4371 // If the AndMask is not all ones for this byte, it's not a bytezap.
4372 if (MaskB != Byte)
4373 return true;
4374
4375 // Otherwise, this byte is kept.
4376 }
4377
4378 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4379 ByteValues);
4380 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004381 }
4382
Chris Lattner8c34cd22008-10-05 02:13:19 +00004383 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4384 // the input value to the bswap. Some observations: 1) if more than one byte
4385 // is demanded from this input, then it could not be successfully assembled
4386 // into a byteswap. At least one of the two bytes would not be aligned with
4387 // their ultimate destination.
4388 if (!isPowerOf2_32(ByteMask)) return true;
4389 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004390
Chris Lattner8c34cd22008-10-05 02:13:19 +00004391 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4392 // is demanded, it needs to go into byte 0 of the result. This means that the
4393 // byte needs to be shifted until it lands in the right byte bucket. The
4394 // shift amount depends on the position: if the byte is coming from the high
4395 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4396 // low part, it must be shifted left.
4397 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4398 if (InputByteNo < ByteValues.size()/2) {
4399 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4400 return true;
4401 } else {
4402 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4403 return true;
4404 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004405
4406 // If the destination byte value is already defined, the values are or'd
4407 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004408 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004410 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004411 return false;
4412}
4413
4414/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4415/// If so, insert the new bswap intrinsic and return it.
4416Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004417 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004418 if (!ITy || ITy->getBitWidth() % 16 ||
4419 // ByteMask only allows up to 32-byte values.
4420 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004421 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004422
4423 /// ByteValues - For each byte of the result, we keep track of which value
4424 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004425 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004426 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004427
4428 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004429 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4430 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004431 return 0;
4432
4433 // Check to see if all of the bytes come from the same value.
4434 Value *V = ByteValues[0];
4435 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4436
4437 // Check to make sure that all of the bytes come from the same value.
4438 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4439 if (ByteValues[i] != V)
4440 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004441 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004443 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004444 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004445}
4446
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004447/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4448/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4449/// we can simplify this expression to "cond ? C : D or B".
4450static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004451 Value *C, Value *D,
4452 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004453 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004454 Value *Cond = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004455 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004456 return 0;
4457
Chris Lattnera6a474d2008-11-16 04:26:55 +00004458 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004459 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004460 return SelectInst::Create(Cond, C, B);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004461 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004462 return SelectInst::Create(Cond, C, B);
4463 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004464 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004465 return SelectInst::Create(Cond, C, D);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004466 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004467 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004468 return 0;
4469}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004470
Chris Lattner69d4ced2008-11-16 05:20:07 +00004471/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4472Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4473 ICmpInst *LHS, ICmpInst *RHS) {
4474 Value *Val, *Val2;
4475 ConstantInt *LHSCst, *RHSCst;
4476 ICmpInst::Predicate LHSCC, RHSCC;
4477
4478 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004479 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4480 m_ConstantInt(LHSCst)), *Context) ||
4481 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4482 m_ConstantInt(RHSCst)), *Context))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004483 return 0;
4484
4485 // From here on, we only handle:
4486 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4487 if (Val != Val2) return 0;
4488
4489 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4490 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4491 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4492 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4493 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4494 return 0;
4495
4496 // We can't fold (ugt x, C) | (sgt x, C2).
4497 if (!PredicatesFoldable(LHSCC, RHSCC))
4498 return 0;
4499
4500 // Ensure that the larger constant is on the RHS.
4501 bool ShouldSwap;
4502 if (ICmpInst::isSignedPredicate(LHSCC) ||
4503 (ICmpInst::isEquality(LHSCC) &&
4504 ICmpInst::isSignedPredicate(RHSCC)))
4505 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4506 else
4507 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4508
4509 if (ShouldSwap) {
4510 std::swap(LHS, RHS);
4511 std::swap(LHSCst, RHSCst);
4512 std::swap(LHSCC, RHSCC);
4513 }
4514
4515 // At this point, we know we have have two icmp instructions
4516 // comparing a value against two constants and or'ing the result
4517 // together. Because of the above check, we know that we only have
4518 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4519 // FoldICmpLogical check above), that the two constants are not
4520 // equal.
4521 assert(LHSCst != RHSCst && "Compares not folded above?");
4522
4523 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004524 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004525 case ICmpInst::ICMP_EQ:
4526 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004527 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004528 case ICmpInst::ICMP_EQ:
Owen Andersond672ecb2009-07-03 00:17:18 +00004529 if (LHSCst == SubOne(RHSCst, Context)) {
4530 // (X == 13 | X == 14) -> X-13 <u 2
4531 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004532 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4533 Val->getName()+".off");
4534 InsertNewInstBefore(Add, I);
Owen Andersond672ecb2009-07-03 00:17:18 +00004535 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson333c4002009-07-09 23:48:35 +00004536 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004537 }
4538 break; // (X == 13 | X == 15) -> no change
4539 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4540 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4541 break;
4542 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4543 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4544 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4545 return ReplaceInstUsesWith(I, RHS);
4546 }
4547 break;
4548 case ICmpInst::ICMP_NE:
4549 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004550 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004551 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4552 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4553 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4554 return ReplaceInstUsesWith(I, LHS);
4555 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4556 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4557 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004558 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004559 }
4560 break;
4561 case ICmpInst::ICMP_ULT:
4562 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004563 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004564 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4565 break;
4566 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4567 // If RHSCst is [us]MAXINT, it is always false. Not handling
4568 // this can cause overflow.
4569 if (RHSCst->isMaxValue(false))
4570 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004571 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4572 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004573 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4574 break;
4575 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4576 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4577 return ReplaceInstUsesWith(I, RHS);
4578 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4579 break;
4580 }
4581 break;
4582 case ICmpInst::ICMP_SLT:
4583 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004584 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004585 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4586 break;
4587 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4588 // If RHSCst is [us]MAXINT, it is always false. Not handling
4589 // this can cause overflow.
4590 if (RHSCst->isMaxValue(true))
4591 return ReplaceInstUsesWith(I, LHS);
Owen Andersond672ecb2009-07-03 00:17:18 +00004592 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4593 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004594 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4595 break;
4596 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4597 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4598 return ReplaceInstUsesWith(I, RHS);
4599 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4600 break;
4601 }
4602 break;
4603 case ICmpInst::ICMP_UGT:
4604 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004605 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004606 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4607 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4608 return ReplaceInstUsesWith(I, LHS);
4609 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4610 break;
4611 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4612 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004613 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004614 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4615 break;
4616 }
4617 break;
4618 case ICmpInst::ICMP_SGT:
4619 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004620 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004621 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4622 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4623 return ReplaceInstUsesWith(I, LHS);
4624 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4625 break;
4626 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4627 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Andersond672ecb2009-07-03 00:17:18 +00004628 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner69d4ced2008-11-16 05:20:07 +00004629 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4630 break;
4631 }
4632 break;
4633 }
4634 return 0;
4635}
4636
Bill Wendlinga698a472008-12-01 08:23:25 +00004637/// FoldOrWithConstants - This helper function folds:
4638///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004639/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004640///
4641/// into:
4642///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004643/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004644///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004645/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004646Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004647 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004648 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4649 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004650
Bill Wendling286a0542008-12-02 06:24:20 +00004651 Value *V1 = 0;
4652 ConstantInt *CI2 = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004653 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004654
Bill Wendling29976b92008-12-02 06:18:11 +00004655 APInt Xor = CI1->getValue() ^ CI2->getValue();
4656 if (!Xor.isAllOnesValue()) return 0;
4657
Bill Wendling286a0542008-12-02 06:24:20 +00004658 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004659 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004660 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4661 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004662 }
4663
4664 return 0;
4665}
4666
Chris Lattner7e708292002-06-25 16:13:24 +00004667Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004668 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004669 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004670
Chris Lattner42593e62007-03-24 23:56:43 +00004671 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004672 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004673
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004674 // or X, X = X
4675 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004676 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004677
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004678 // See if we can simplify any instructions used by the instruction whose sole
4679 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004680 if (SimplifyDemandedInstructionBits(I))
4681 return &I;
4682 if (isa<VectorType>(I.getType())) {
4683 if (isa<ConstantAggregateZero>(Op1)) {
4684 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4685 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4686 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4687 return ReplaceInstUsesWith(I, I.getOperand(1));
4688 }
Chris Lattner42593e62007-03-24 23:56:43 +00004689 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004690
Chris Lattner3f5b8772002-05-06 16:14:14 +00004691 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004692 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004693 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004694 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004695 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4696 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004697 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004698 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004699 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004700 return BinaryOperator::CreateAnd(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004701 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004702 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004703
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004704 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004705 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4706 isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004707 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004708 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004709 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004710 return BinaryOperator::CreateXor(Or,
Owen Andersond672ecb2009-07-03 00:17:18 +00004711 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004712 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004713
4714 // Try to fold constant and into select arguments.
4715 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004716 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004717 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004718 if (isa<PHINode>(Op0))
4719 if (Instruction *NV = FoldOpIntoPhi(I))
4720 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004721 }
4722
Chris Lattner4f637d42006-01-06 17:59:59 +00004723 Value *A = 0, *B = 0;
4724 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004725
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004726 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004727 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4728 return ReplaceInstUsesWith(I, Op1);
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004729 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004730 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4731 return ReplaceInstUsesWith(I, Op0);
4732
Chris Lattner6423d4c2006-07-10 20:25:24 +00004733 // (A | B) | C and A | (B | C) -> bswap if possible.
4734 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004735 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4736 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4737 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4738 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004739 if (Instruction *BSwap = MatchBSwap(I))
4740 return BSwap;
4741 }
4742
Chris Lattner6e4c6492005-05-09 04:58:36 +00004743 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004744 if (Op0->hasOneUse() &&
4745 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004746 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004747 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004748 InsertNewInstBefore(NOr, I);
4749 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004750 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004751 }
4752
4753 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004754 if (Op1->hasOneUse() &&
4755 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004756 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004757 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004758 InsertNewInstBefore(NOr, I);
4759 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004760 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004761 }
4762
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004763 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004764 Value *C = 0, *D = 0;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004765 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4766 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004767 Value *V1 = 0, *V2 = 0, *V3 = 0;
4768 C1 = dyn_cast<ConstantInt>(C);
4769 C2 = dyn_cast<ConstantInt>(D);
4770 if (C1 && C2) { // (A & C1)|(B & C2)
4771 // If we have: ((V + N) & C1) | (V & C2)
4772 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4773 // replace with V+N.
4774 if (C1->getValue() == ~C2->getValue()) {
4775 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004776 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004777 // Add commutes, try both ways.
4778 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4779 return ReplaceInstUsesWith(I, A);
4780 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4781 return ReplaceInstUsesWith(I, A);
4782 }
4783 // Or commutes, try both ways.
4784 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004785 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004786 // Add commutes, try both ways.
4787 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4788 return ReplaceInstUsesWith(I, B);
4789 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4790 return ReplaceInstUsesWith(I, B);
4791 }
4792 }
Chris Lattner044e5332007-04-08 08:01:49 +00004793 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004794 }
4795
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004796 // Check to see if we have any common things being and'ed. If so, find the
4797 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004798 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4799 if (A == B) // (A & C)|(A & D) == A & (C|D)
4800 V1 = A, V2 = C, V3 = D;
4801 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4802 V1 = A, V2 = B, V3 = C;
4803 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4804 V1 = C, V2 = A, V3 = D;
4805 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4806 V1 = C, V2 = A, V3 = B;
4807
4808 if (V1) {
4809 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004810 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4811 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004812 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004813 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004814
Dan Gohman1975d032008-10-30 20:40:10 +00004815 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004816 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004817 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004818 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004819 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004820 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004821 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004822 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004823 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004824
Bill Wendlingb01865c2008-11-30 13:52:49 +00004825 // ((A&~B)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004826 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4827 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004828 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004829 // ((~B&A)|(~A&B)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004830 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4831 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004832 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004833 // ((A&~B)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004834 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4835 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004836 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004837 // ((~B&A)|(B&~A)) -> A^B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004838 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4839 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004840 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004841 }
Chris Lattnere511b742006-11-14 07:46:50 +00004842
4843 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004844 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4845 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4846 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004847 SI0->getOperand(1) == SI1->getOperand(1) &&
4848 (SI0->hasOneUse() || SI1->hasOneUse())) {
4849 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004850 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004851 SI1->getOperand(0),
4852 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004853 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004854 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004855 }
4856 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004857
Bill Wendlingb3833d12008-12-01 01:07:11 +00004858 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004859 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4860 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004861 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004862 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004863 }
4864 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004865 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4866 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004867 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004868 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004869 }
4870
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004871 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004872 if (A == Op1) // ~A | A == -1
Owen Andersond672ecb2009-07-03 00:17:18 +00004873 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004874 } else {
4875 A = 0;
4876 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004877 // Note, A is still live here!
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004878 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004879 if (Op0 == B)
Owen Andersond672ecb2009-07-03 00:17:18 +00004880 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004881
Misha Brukmancb6267b2004-07-30 12:50:08 +00004882 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004883 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004884 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004885 I.getName()+".demorgan"), I);
Owen Anderson73c6b712009-07-13 20:58:05 +00004886 return BinaryOperator::CreateNot(*Context, And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004887 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004888 }
Chris Lattnera2881962003-02-18 19:28:33 +00004889
Reid Spencere4d87aa2006-12-23 06:05:41 +00004890 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4891 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004892 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004893 return R;
4894
Chris Lattner69d4ced2008-11-16 05:20:07 +00004895 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4896 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4897 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004898 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004899
4900 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004901 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004902 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004903 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004904 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4905 !isa<ICmpInst>(Op1C->getOperand(0))) {
4906 const Type *SrcTy = Op0C->getOperand(0)->getType();
4907 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4908 // Only do this if the casts both really cause code to be
4909 // generated.
4910 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4911 I.getType(), TD) &&
4912 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4913 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004914 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004915 Op1C->getOperand(0),
4916 I.getName());
4917 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004918 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004919 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004920 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004921 }
Chris Lattner99c65742007-10-24 05:38:08 +00004922 }
4923
4924
4925 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4926 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4927 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4928 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004929 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004930 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004931 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4932 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4933 // If either of the constants are nans, then the whole thing returns
4934 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004935 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Andersond672ecb2009-07-03 00:17:18 +00004936 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner99c65742007-10-24 05:38:08 +00004937
4938 // Otherwise, no need to compare the two constants, compare the
4939 // rest.
Owen Anderson333c4002009-07-09 23:48:35 +00004940 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4941 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner99c65742007-10-24 05:38:08 +00004942 }
Evan Cheng40300622008-10-14 18:44:08 +00004943 } else {
4944 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4945 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004946 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4947 m_Value(Op0RHS)), *Context) &&
4948 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4949 m_Value(Op1RHS)), *Context)) {
Evan Cheng40300622008-10-14 18:44:08 +00004950 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4951 // Swap RHS operands to match LHS.
4952 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4953 std::swap(Op1LHS, Op1RHS);
4954 }
4955 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4956 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4957 if (Op0CC == Op1CC)
Owen Anderson333c4002009-07-09 23:48:35 +00004958 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4959 Op0LHS, Op0RHS);
Evan Cheng40300622008-10-14 18:44:08 +00004960 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4961 Op1CC == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00004962 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng40300622008-10-14 18:44:08 +00004963 else if (Op0CC == FCmpInst::FCMP_FALSE)
4964 return ReplaceInstUsesWith(I, Op1);
4965 else if (Op1CC == FCmpInst::FCMP_FALSE)
4966 return ReplaceInstUsesWith(I, Op0);
4967 bool Op0Ordered;
4968 bool Op1Ordered;
4969 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4970 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4971 if (Op0Ordered == Op1Ordered) {
4972 // If both are ordered or unordered, return a new fcmp with
4973 // or'ed predicates.
4974 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Andersond672ecb2009-07-03 00:17:18 +00004975 Op0LHS, Op0RHS, Context);
Evan Cheng40300622008-10-14 18:44:08 +00004976 if (Instruction *I = dyn_cast<Instruction>(RV))
4977 return I;
4978 // Otherwise, it's a constant boolean value...
4979 return ReplaceInstUsesWith(I, RV);
4980 }
4981 }
4982 }
4983 }
Chris Lattner99c65742007-10-24 05:38:08 +00004984 }
4985 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004986
Chris Lattner7e708292002-06-25 16:13:24 +00004987 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004988}
4989
Dan Gohman844731a2008-05-13 00:00:25 +00004990namespace {
4991
Chris Lattnerc317d392004-02-16 01:20:27 +00004992// XorSelf - Implements: X ^ X --> 0
4993struct XorSelf {
4994 Value *RHS;
4995 XorSelf(Value *rhs) : RHS(rhs) {}
4996 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4997 Instruction *apply(BinaryOperator &Xor) const {
4998 return &Xor;
4999 }
5000};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005001
Dan Gohman844731a2008-05-13 00:00:25 +00005002}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005003
Chris Lattner7e708292002-06-25 16:13:24 +00005004Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005005 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005006 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005007
Evan Chengd34af782008-03-25 20:07:13 +00005008 if (isa<UndefValue>(Op1)) {
5009 if (isa<UndefValue>(Op0))
5010 // Handle undef ^ undef -> 0 special case. This is a common
5011 // idiom (misuse).
Owen Andersond672ecb2009-07-03 00:17:18 +00005012 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005013 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005014 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005015
Chris Lattnerc317d392004-02-16 01:20:27 +00005016 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Andersond672ecb2009-07-03 00:17:18 +00005017 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005018 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersond672ecb2009-07-03 00:17:18 +00005019 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005020 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005021
5022 // See if we can simplify any instructions used by the instruction whose sole
5023 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005024 if (SimplifyDemandedInstructionBits(I))
5025 return &I;
5026 if (isa<VectorType>(I.getType()))
5027 if (isa<ConstantAggregateZero>(Op1))
5028 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005029
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005030 // Is this a ~ operation?
Owen Andersond672ecb2009-07-03 00:17:18 +00005031 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005032 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5033 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5034 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5035 if (Op0I->getOpcode() == Instruction::And ||
5036 Op0I->getOpcode() == Instruction::Or) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005037 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5038 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005039 Instruction *NotY =
Owen Anderson73c6b712009-07-13 20:58:05 +00005040 BinaryOperator::CreateNot(*Context, Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005041 Op0I->getOperand(1)->getName()+".not");
5042 InsertNewInstBefore(NotY, I);
5043 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005044 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005045 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005046 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005047 }
5048 }
5049 }
5050 }
5051
5052
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005053 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005054 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005055 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005056 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005057 return new ICmpInst(*Context, ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005058 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005059
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005060 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson333c4002009-07-09 23:48:35 +00005061 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005062 FCI->getOperand(0), FCI->getOperand(1));
5063 }
5064
Nick Lewycky517e1f52008-05-31 19:01:33 +00005065 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5066 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5067 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5068 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5069 Instruction::CastOps Opcode = Op0C->getOpcode();
5070 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005071 if (RHS == Context->getConstantExprCast(Opcode,
5072 Context->getConstantIntTrue(),
Nick Lewycky517e1f52008-05-31 19:01:33 +00005073 Op0C->getDestTy())) {
5074 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson333c4002009-07-09 23:48:35 +00005075 *Context,
Nick Lewycky517e1f52008-05-31 19:01:33 +00005076 CI->getOpcode(), CI->getInversePredicate(),
5077 CI->getOperand(0), CI->getOperand(1)), I);
5078 NewCI->takeName(CI);
5079 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5080 }
5081 }
5082 }
5083 }
5084 }
5085
Reid Spencere4d87aa2006-12-23 06:05:41 +00005086 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005087 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005088 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5089 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005090 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5091 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5092 Context->getConstantInt(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005093 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005094 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005095
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005096 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005097 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005098 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005099 if (RHS->isAllOnesValue()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005100 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005101 return BinaryOperator::CreateSub(
Owen Andersond672ecb2009-07-03 00:17:18 +00005102 Context->getConstantExprSub(NegOp0CI,
5103 Context->getConstantInt(I.getType(), 1)),
5104 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005105 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005106 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersond672ecb2009-07-03 00:17:18 +00005107 Constant *C =
5108 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005109 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005110
Chris Lattner7c4049c2004-01-12 19:35:11 +00005111 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005112 } else if (Op0I->getOpcode() == Instruction::Or) {
5113 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005114 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005115 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005116 // Anything in both C1 and C2 is known to be zero, remove it from
5117 // NewRHS.
Owen Andersond672ecb2009-07-03 00:17:18 +00005118 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5119 NewRHS = Context->getConstantExprAnd(NewRHS,
5120 Context->getConstantExprNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005121 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005122 I.setOperand(0, Op0I->getOperand(0));
5123 I.setOperand(1, NewRHS);
5124 return &I;
5125 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005126 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005127 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005128 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005129
5130 // Try to fold constant and into select arguments.
5131 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005132 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005133 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005134 if (isa<PHINode>(Op0))
5135 if (Instruction *NV = FoldOpIntoPhi(I))
5136 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005137 }
5138
Owen Andersond672ecb2009-07-03 00:17:18 +00005139 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005140 if (X == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005141 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005142
Owen Andersond672ecb2009-07-03 00:17:18 +00005143 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005144 if (X == Op0)
Owen Andersond672ecb2009-07-03 00:17:18 +00005145 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005146
Chris Lattner318bf792007-03-18 22:51:34 +00005147
5148 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5149 if (Op1I) {
5150 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005151 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005152 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005153 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005154 I.swapOperands();
5155 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005156 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005157 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005158 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005159 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005160 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005161 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005162 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005163 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005164 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5165 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005166 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005167 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005168 std::swap(A, B);
5169 }
Chris Lattner318bf792007-03-18 22:51:34 +00005170 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005171 I.swapOperands(); // Simplified below.
5172 std::swap(Op0, Op1);
5173 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005174 }
Chris Lattner318bf792007-03-18 22:51:34 +00005175 }
5176
5177 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5178 if (Op0I) {
5179 Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005180 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5181 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005182 if (A == Op1) // (B|A)^B == (A|B)^B
5183 std::swap(A, B);
5184 if (B == Op1) { // (A|B)^B == A & ~B
5185 Instruction *NotB =
Owen Anderson73c6b712009-07-13 20:58:05 +00005186 InsertNewInstBefore(BinaryOperator::CreateNot(*Context,
5187 Op1, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005188 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005189 }
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005190 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005191 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005192 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005193 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005194 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5195 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005196 if (A == Op1) // (A&B)^A -> (B&A)^A
5197 std::swap(A, B);
5198 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005199 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005200 Instruction *N =
Owen Anderson73c6b712009-07-13 20:58:05 +00005201 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, A, "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005202 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005203 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005204 }
Chris Lattner318bf792007-03-18 22:51:34 +00005205 }
5206
5207 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5208 if (Op0I && Op1I && Op0I->isShift() &&
5209 Op0I->getOpcode() == Op1I->getOpcode() &&
5210 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5211 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5212 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005213 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005214 Op1I->getOperand(0),
5215 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005216 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005217 Op1I->getOperand(1));
5218 }
5219
5220 if (Op0I && Op1I) {
5221 Value *A, *B, *C, *D;
5222 // (A & B)^(A | B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005223 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5224 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005225 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005226 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005227 }
5228 // (A | B)^(A & B) -> A ^ B
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005229 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5230 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005231 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005232 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005233 }
5234
5235 // (A & B)^(C & D)
5236 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005237 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5238 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner318bf792007-03-18 22:51:34 +00005239 // (X & Y)^(X & Y) -> (Y^Z) & X
5240 Value *X = 0, *Y = 0, *Z = 0;
5241 if (A == C)
5242 X = A, Y = B, Z = D;
5243 else if (A == D)
5244 X = A, Y = B, Z = C;
5245 else if (B == C)
5246 X = B, Y = A, Z = D;
5247 else if (B == D)
5248 X = B, Y = A, Z = C;
5249
5250 if (X) {
5251 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005252 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5253 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005254 }
5255 }
5256 }
5257
Reid Spencere4d87aa2006-12-23 06:05:41 +00005258 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5259 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005260 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005261 return R;
5262
Chris Lattner6fc205f2006-05-05 06:39:07 +00005263 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005264 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005265 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005266 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5267 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005268 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005269 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005270 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5271 I.getType(), TD) &&
5272 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5273 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005274 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005275 Op1C->getOperand(0),
5276 I.getName());
5277 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005278 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005279 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005280 }
Chris Lattner99c65742007-10-24 05:38:08 +00005281 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005282
Chris Lattner7e708292002-06-25 16:13:24 +00005283 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005284}
5285
Owen Andersond672ecb2009-07-03 00:17:18 +00005286static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005287 LLVMContext *Context) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005288 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005289}
Chris Lattnera96879a2004-09-29 17:40:11 +00005290
Dan Gohman6de29f82009-06-15 22:12:54 +00005291static bool HasAddOverflow(ConstantInt *Result,
5292 ConstantInt *In1, ConstantInt *In2,
5293 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005294 if (IsSigned)
5295 if (In2->getValue().isNegative())
5296 return Result->getValue().sgt(In1->getValue());
5297 else
5298 return Result->getValue().slt(In1->getValue());
5299 else
5300 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005301}
5302
Dan Gohman6de29f82009-06-15 22:12:54 +00005303/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005304/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005305static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005306 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005307 bool IsSigned = false) {
5308 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005309
Dan Gohman6de29f82009-06-15 22:12:54 +00005310 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5311 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005312 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5313 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5314 ExtractElement(In1, Idx, Context),
5315 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005316 IsSigned))
5317 return true;
5318 }
5319 return false;
5320 }
5321
5322 return HasAddOverflow(cast<ConstantInt>(Result),
5323 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5324 IsSigned);
5325}
5326
5327static bool HasSubOverflow(ConstantInt *Result,
5328 ConstantInt *In1, ConstantInt *In2,
5329 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005330 if (IsSigned)
5331 if (In2->getValue().isNegative())
5332 return Result->getValue().slt(In1->getValue());
5333 else
5334 return Result->getValue().sgt(In1->getValue());
5335 else
5336 return Result->getValue().ugt(In1->getValue());
5337}
5338
Dan Gohman6de29f82009-06-15 22:12:54 +00005339/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5340/// overflowed for this type.
5341static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005342 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005343 bool IsSigned = false) {
5344 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005345
5346 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5347 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005348 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5349 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5350 ExtractElement(In1, Idx, Context),
5351 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005352 IsSigned))
5353 return true;
5354 }
5355 return false;
5356 }
5357
5358 return HasSubOverflow(cast<ConstantInt>(Result),
5359 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5360 IsSigned);
5361}
5362
Chris Lattner574da9b2005-01-13 20:14:25 +00005363/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5364/// code necessary to compute the offset from the base pointer (without adding
5365/// in the base pointer). Return the result as a signed integer of intptr size.
5366static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5367 TargetData &TD = IC.getTargetData();
5368 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005369 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson07cf79e2009-07-06 23:00:19 +00005370 LLVMContext *Context = IC.getContext();
Owen Andersond672ecb2009-07-03 00:17:18 +00005371 Value *Result = Context->getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005372
5373 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005374 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005375 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005376
Gabor Greif177dd3f2008-06-12 21:37:33 +00005377 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5378 ++i, ++GTI) {
5379 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005380 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005381 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5382 if (OpC->isZero()) continue;
5383
5384 // Handle a struct index, which adds its field offset to the pointer.
5385 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5386 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5387
5388 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005389 Result =
5390 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005391 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005392 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005393 BinaryOperator::CreateAdd(Result,
Owen Andersond672ecb2009-07-03 00:17:18 +00005394 Context->getConstantInt(IntPtrTy, Size),
Chris Lattnere62f0212007-04-28 04:52:43 +00005395 GEP->getName()+".offs"), I);
5396 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005397 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005398
Owen Andersond672ecb2009-07-03 00:17:18 +00005399 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5400 Constant *OC =
5401 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5402 Scale = Context->getConstantExprMul(OC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005403 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005404 Result = Context->getConstantExprAdd(RC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005405 else {
5406 // Emit an add instruction.
5407 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005408 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005409 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005410 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005411 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005412 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005413 // Convert to correct type.
5414 if (Op->getType() != IntPtrTy) {
5415 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005416 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005417 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005418 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5419 true,
5420 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005421 }
5422 if (Size != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00005423 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Chris Lattnere62f0212007-04-28 04:52:43 +00005424 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Andersond672ecb2009-07-03 00:17:18 +00005425 Op = Context->getConstantExprMul(OpC, Scale);
Chris Lattnere62f0212007-04-28 04:52:43 +00005426 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005427 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005428 GEP->getName()+".idx"), I);
5429 }
5430
5431 // Emit an add instruction.
5432 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00005433 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Chris Lattnere62f0212007-04-28 04:52:43 +00005434 cast<Constant>(Result));
5435 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005436 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005437 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005438 }
5439 return Result;
5440}
5441
Chris Lattner10c0d912008-04-22 02:53:33 +00005442
Dan Gohman8f080f02009-07-17 22:16:21 +00005443/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5444/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5445/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5446/// be complex, and scales are involved. The above expression would also be
5447/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5448/// This later form is less amenable to optimization though, and we are allowed
5449/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005450///
5451/// If we can't emit an optimized form for this expression, this returns null.
5452///
5453static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5454 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005455 TargetData &TD = IC.getTargetData();
5456 gep_type_iterator GTI = gep_type_begin(GEP);
5457
5458 // Check to see if this gep only has a single variable index. If so, and if
5459 // any constant indices are a multiple of its scale, then we can compute this
5460 // in terms of the scale of the variable index. For example, if the GEP
5461 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5462 // because the expression will cross zero at the same point.
5463 unsigned i, e = GEP->getNumOperands();
5464 int64_t Offset = 0;
5465 for (i = 1; i != e; ++i, ++GTI) {
5466 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5467 // Compute the aggregate offset of constant indices.
5468 if (CI->isZero()) continue;
5469
5470 // Handle a struct index, which adds its field offset to the pointer.
5471 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5472 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5473 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005474 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005475 Offset += Size*CI->getSExtValue();
5476 }
5477 } else {
5478 // Found our variable index.
5479 break;
5480 }
5481 }
5482
5483 // If there are no variable indices, we must have a constant offset, just
5484 // evaluate it the general way.
5485 if (i == e) return 0;
5486
5487 Value *VariableIdx = GEP->getOperand(i);
5488 // Determine the scale factor of the variable element. For example, this is
5489 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005490 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005491
5492 // Verify that there are no other variable indices. If so, emit the hard way.
5493 for (++i, ++GTI; i != e; ++i, ++GTI) {
5494 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5495 if (!CI) return 0;
5496
5497 // Compute the aggregate offset of constant indices.
5498 if (CI->isZero()) continue;
5499
5500 // Handle a struct index, which adds its field offset to the pointer.
5501 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5502 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5503 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005504 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005505 Offset += Size*CI->getSExtValue();
5506 }
5507 }
5508
5509 // Okay, we know we have a single variable index, which must be a
5510 // pointer/array/vector index. If there is no offset, life is simple, return
5511 // the index.
5512 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5513 if (Offset == 0) {
5514 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5515 // we don't need to bother extending: the extension won't affect where the
5516 // computation crosses zero.
5517 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5518 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5519 VariableIdx->getNameStart(), &I);
5520 return VariableIdx;
5521 }
5522
5523 // Otherwise, there is an index. The computation we will do will be modulo
5524 // the pointer size, so get it.
5525 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5526
5527 Offset &= PtrSizeMask;
5528 VariableScale &= PtrSizeMask;
5529
5530 // To do this transformation, any constant index must be a multiple of the
5531 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5532 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5533 // multiple of the variable scale.
5534 int64_t NewOffs = Offset / (int64_t)VariableScale;
5535 if (Offset != NewOffs*(int64_t)VariableScale)
5536 return 0;
5537
5538 // Okay, we can do this evaluation. Start by converting the index to intptr.
5539 const Type *IntPtrTy = TD.getIntPtrType();
5540 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005541 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005542 true /*SExt*/,
5543 VariableIdx->getNameStart(), &I);
Owen Andersond672ecb2009-07-03 00:17:18 +00005544 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005545 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005546}
5547
5548
Reid Spencere4d87aa2006-12-23 06:05:41 +00005549/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005550/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005551Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5552 ICmpInst::Predicate Cond,
5553 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005554 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005555
Chris Lattner10c0d912008-04-22 02:53:33 +00005556 // Look through bitcasts.
5557 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5558 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005559
Chris Lattner574da9b2005-01-13 20:14:25 +00005560 Value *PtrBase = GEPLHS->getOperand(0);
5561 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005562 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005563 // This transformation (ignoring the base and scales) is valid because we
5564 // know pointers can't overflow. See if we can output an optimized form.
5565 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5566
5567 // If not, synthesize the offset the hard way.
5568 if (Offset == 0)
5569 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005570 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersond672ecb2009-07-03 00:17:18 +00005571 Context->getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005572 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005573 // If the base pointers are different, but the indices are the same, just
5574 // compare the base pointer.
5575 if (PtrBase != GEPRHS->getOperand(0)) {
5576 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005577 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005578 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005579 if (IndicesTheSame)
5580 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5581 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5582 IndicesTheSame = false;
5583 break;
5584 }
5585
5586 // If all indices are the same, just compare the base pointers.
5587 if (IndicesTheSame)
Owen Anderson333c4002009-07-09 23:48:35 +00005588 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005589 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005590
5591 // Otherwise, the base pointers are different and the indices are
5592 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005593 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005594 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005595
Chris Lattnere9d782b2005-01-13 22:25:21 +00005596 // If one of the GEPs has all zero indices, recurse.
5597 bool AllZeros = true;
5598 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5599 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5600 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5601 AllZeros = false;
5602 break;
5603 }
5604 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005605 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5606 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005607
5608 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005609 AllZeros = true;
5610 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5611 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5612 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5613 AllZeros = false;
5614 break;
5615 }
5616 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005617 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005618
Chris Lattner4401c9c2005-01-14 00:20:05 +00005619 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5620 // If the GEPs only differ by one index, compare it.
5621 unsigned NumDifferences = 0; // Keep track of # differences.
5622 unsigned DiffOperand = 0; // The operand that differs.
5623 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5624 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005625 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5626 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005627 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005628 NumDifferences = 2;
5629 break;
5630 } else {
5631 if (NumDifferences++) break;
5632 DiffOperand = i;
5633 }
5634 }
5635
5636 if (NumDifferences == 0) // SAME GEP?
5637 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Andersond672ecb2009-07-03 00:17:18 +00005638 Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005639 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005640
Chris Lattner4401c9c2005-01-14 00:20:05 +00005641 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005642 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5643 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005644 // Make sure we do a signed comparison here.
Owen Anderson333c4002009-07-09 23:48:35 +00005645 return new ICmpInst(*Context,
5646 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005647 }
5648 }
5649
Reid Spencere4d87aa2006-12-23 06:05:41 +00005650 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005651 // the result to fold to a constant!
5652 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5653 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5654 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5655 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5656 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson333c4002009-07-09 23:48:35 +00005657 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005658 }
5659 }
5660 return 0;
5661}
5662
Chris Lattnera5406232008-05-19 20:18:56 +00005663/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5664///
5665Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5666 Instruction *LHSI,
5667 Constant *RHSC) {
5668 if (!isa<ConstantFP>(RHSC)) return 0;
5669 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5670
5671 // Get the width of the mantissa. We don't want to hack on conversions that
5672 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005673 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005674 if (MantissaWidth == -1) return 0; // Unknown.
5675
5676 // Check to see that the input is converted from an integer type that is small
5677 // enough that preserves all bits. TODO: check here for "known" sign bits.
5678 // 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 +00005679 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005680
5681 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005682 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5683 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005684 ++InputSize;
5685
5686 // If the conversion would lose info, don't hack on this.
5687 if ((int)InputSize > MantissaWidth)
5688 return 0;
5689
5690 // Otherwise, we can potentially simplify the comparison. We know that it
5691 // will always come through as an integer value and we know the constant is
5692 // not a NAN (it would have been previously simplified).
5693 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5694
5695 ICmpInst::Predicate Pred;
5696 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005697 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005698 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005699 case FCmpInst::FCMP_OEQ:
5700 Pred = ICmpInst::ICMP_EQ;
5701 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005702 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005703 case FCmpInst::FCMP_OGT:
5704 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5705 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005706 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005707 case FCmpInst::FCMP_OGE:
5708 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5709 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005710 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005711 case FCmpInst::FCMP_OLT:
5712 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5713 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005714 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005715 case FCmpInst::FCMP_OLE:
5716 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5717 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005718 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005719 case FCmpInst::FCMP_ONE:
5720 Pred = ICmpInst::ICMP_NE;
5721 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005722 case FCmpInst::FCMP_ORD:
Owen Andersond672ecb2009-07-03 00:17:18 +00005723 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_UNO:
Owen Andersond672ecb2009-07-03 00:17:18 +00005725 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005726 }
5727
5728 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5729
5730 // Now we know that the APFloat is a normal number, zero or inf.
5731
Chris Lattner85162782008-05-20 03:50:52 +00005732 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005733 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005734 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005735
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005736 if (!LHSUnsigned) {
5737 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5738 // and large values.
5739 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5740 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5741 APFloat::rmNearestTiesToEven);
5742 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5743 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5744 Pred == ICmpInst::ICMP_SLE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005745 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5746 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005747 }
5748 } else {
5749 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5750 // +INF and large values.
5751 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5752 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5753 APFloat::rmNearestTiesToEven);
5754 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5755 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5756 Pred == ICmpInst::ICMP_ULE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005757 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5758 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
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 if (!LHSUnsigned) {
5763 // See if the RHS value is < SignedMin.
5764 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5765 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5766 APFloat::rmNearestTiesToEven);
5767 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5768 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5769 Pred == ICmpInst::ICMP_SGE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005770 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5771 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005772 }
Chris Lattnera5406232008-05-19 20:18:56 +00005773 }
5774
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005775 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5776 // [0, UMAX], but it may still be fractional. See if it is fractional by
5777 // casting the FP value to the integer value and back, checking for equality.
5778 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005779 Constant *RHSInt = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005780 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5781 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005782 if (!RHS.isZero()) {
5783 bool Equal = LHSUnsigned
Owen Andersond672ecb2009-07-03 00:17:18 +00005784 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5785 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005786 if (!Equal) {
5787 // If we had a comparison against a fractional value, we have to adjust
5788 // the compare predicate and sometimes the value. RHSC is rounded towards
5789 // zero at this point.
5790 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005791 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005792 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00005793 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005794 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Andersond672ecb2009-07-03 00:17:18 +00005795 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005796 case ICmpInst::ICMP_ULE:
5797 // (float)int <= 4.4 --> int <= 4
5798 // (float)int <= -4.4 --> false
5799 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005800 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005801 break;
5802 case ICmpInst::ICMP_SLE:
5803 // (float)int <= 4.4 --> int <= 4
5804 // (float)int <= -4.4 --> int < -4
5805 if (RHS.isNegative())
5806 Pred = ICmpInst::ICMP_SLT;
5807 break;
5808 case ICmpInst::ICMP_ULT:
5809 // (float)int < -4.4 --> false
5810 // (float)int < 4.4 --> int <= 4
5811 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005812 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005813 Pred = ICmpInst::ICMP_ULE;
5814 break;
5815 case ICmpInst::ICMP_SLT:
5816 // (float)int < -4.4 --> int < -4
5817 // (float)int < 4.4 --> int <= 4
5818 if (!RHS.isNegative())
5819 Pred = ICmpInst::ICMP_SLE;
5820 break;
5821 case ICmpInst::ICMP_UGT:
5822 // (float)int > 4.4 --> int > 4
5823 // (float)int > -4.4 --> true
5824 if (RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005825 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005826 break;
5827 case ICmpInst::ICMP_SGT:
5828 // (float)int > 4.4 --> int > 4
5829 // (float)int > -4.4 --> int >= -4
5830 if (RHS.isNegative())
5831 Pred = ICmpInst::ICMP_SGE;
5832 break;
5833 case ICmpInst::ICMP_UGE:
5834 // (float)int >= -4.4 --> true
5835 // (float)int >= 4.4 --> int > 4
5836 if (!RHS.isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00005837 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005838 Pred = ICmpInst::ICMP_UGT;
5839 break;
5840 case ICmpInst::ICMP_SGE:
5841 // (float)int >= -4.4 --> int >= -4
5842 // (float)int >= 4.4 --> int > 4
5843 if (!RHS.isNegative())
5844 Pred = ICmpInst::ICMP_SGT;
5845 break;
5846 }
Chris Lattnera5406232008-05-19 20:18:56 +00005847 }
5848 }
5849
5850 // Lower this FP comparison into an appropriate integer version of the
5851 // comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00005852 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005853}
5854
Reid Spencere4d87aa2006-12-23 06:05:41 +00005855Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5856 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005857 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005858
Chris Lattner58e97462007-01-14 19:42:17 +00005859 // Fold trivial predicates.
5860 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005861 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005862 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Andersond672ecb2009-07-03 00:17:18 +00005863 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005864
5865 // Simplify 'fcmp pred X, X'
5866 if (Op0 == Op1) {
5867 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005868 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005869 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5870 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5871 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Andersond672ecb2009-07-03 00:17:18 +00005872 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005873 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5874 case FCmpInst::FCMP_OLT: // True if ordered and less than
5875 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Andersond672ecb2009-07-03 00:17:18 +00005876 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005877
5878 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5879 case FCmpInst::FCMP_ULT: // True if unordered or less than
5880 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5881 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5882 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5883 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersond672ecb2009-07-03 00:17:18 +00005884 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005885 return &I;
5886
5887 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5888 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5889 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5890 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5891 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5892 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersond672ecb2009-07-03 00:17:18 +00005893 I.setOperand(1, Context->getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005894 return &I;
5895 }
5896 }
5897
Reid Spencere4d87aa2006-12-23 06:05:41 +00005898 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005899 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005900
Reid Spencere4d87aa2006-12-23 06:05:41 +00005901 // Handle fcmp with constant RHS
5902 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005903 // If the constant is a nan, see if we can fold the comparison based on it.
5904 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5905 if (CFP->getValueAPF().isNaN()) {
5906 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Andersond672ecb2009-07-03 00:17:18 +00005907 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005908 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5909 "Comparison must be either ordered or unordered!");
5910 // True if unordered.
Owen Andersond672ecb2009-07-03 00:17:18 +00005911 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005912 }
5913 }
5914
Reid Spencere4d87aa2006-12-23 06:05:41 +00005915 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5916 switch (LHSI->getOpcode()) {
5917 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005918 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5919 // block. If in the same block, we're encouraging jump threading. If
5920 // not, we are just pessimizing the code by making an i1 phi.
5921 if (LHSI->getParent() == I.getParent())
5922 if (Instruction *NV = FoldOpIntoPhi(I))
5923 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005924 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005925 case Instruction::SIToFP:
5926 case Instruction::UIToFP:
5927 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5928 return NV;
5929 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005930 case Instruction::Select:
5931 // If either operand of the select is a constant, we can fold the
5932 // comparison into the select arms, which will cause one to be
5933 // constant folded and the select turned into a bitwise or.
5934 Value *Op1 = 0, *Op2 = 0;
5935 if (LHSI->hasOneUse()) {
5936 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5937 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005938 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005939 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005940 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005941 LHSI->getOperand(2), RHSC,
5942 I.getName()), I);
5943 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5944 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00005945 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 // Insert a new FCmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00005947 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005948 LHSI->getOperand(1), RHSC,
5949 I.getName()), I);
5950 }
5951 }
5952
5953 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005954 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005955 break;
5956 }
5957 }
5958
5959 return Changed ? &I : 0;
5960}
5961
5962Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5963 bool Changed = SimplifyCompare(I);
5964 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5965 const Type *Ty = Op0->getType();
5966
5967 // icmp X, X
5968 if (Op0 == Op1)
Owen Andersond672ecb2009-07-03 00:17:18 +00005969 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005970 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971
5972 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Andersond672ecb2009-07-03 00:17:18 +00005973 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005974
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005976 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005977 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5978 isa<ConstantPointerNull>(Op0)) &&
5979 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005980 isa<ConstantPointerNull>(Op1)))
Owen Andersond672ecb2009-07-03 00:17:18 +00005981 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005982 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005983
Reid Spencere4d87aa2006-12-23 06:05:41 +00005984 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005985 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005987 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005988 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005989 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005990 InsertNewInstBefore(Xor, I);
Owen Anderson73c6b712009-07-13 20:58:05 +00005991 return BinaryOperator::CreateNot(*Context, Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005992 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005993 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005994 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005995
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005997 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005998 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005999 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Owen Anderson73c6b712009-07-13 20:58:05 +00006000 Instruction *Not = BinaryOperator::CreateNot(*Context,
6001 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006002 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006003 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006004 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006005 case ICmpInst::ICMP_SGT:
6006 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006007 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006008 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006009 Instruction *Not = BinaryOperator::CreateNot(*Context,
6010 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006011 InsertNewInstBefore(Not, I);
6012 return BinaryOperator::CreateAnd(Not, Op0);
6013 }
6014 case ICmpInst::ICMP_UGE:
6015 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6016 // FALL THROUGH
6017 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Owen Anderson73c6b712009-07-13 20:58:05 +00006018 Instruction *Not = BinaryOperator::CreateNot(*Context,
6019 Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00006020 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006021 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006022 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006023 case ICmpInst::ICMP_SGE:
6024 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6025 // FALL THROUGH
6026 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Owen Anderson73c6b712009-07-13 20:58:05 +00006027 Instruction *Not = BinaryOperator::CreateNot(*Context,
6028 Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006029 InsertNewInstBefore(Not, I);
6030 return BinaryOperator::CreateOr(Not, Op0);
6031 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006032 }
Chris Lattner8b170942002-08-09 23:47:40 +00006033 }
6034
Dan Gohman1c8491e2009-04-25 17:12:48 +00006035 unsigned BitWidth = 0;
6036 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006037 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6038 else if (Ty->isIntOrIntVector())
6039 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006040
6041 bool isSignBit = false;
6042
Dan Gohman81b28ce2008-09-16 18:46:06 +00006043 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006044 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006045 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006046
Chris Lattnerb6566012008-01-05 01:18:20 +00006047 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6048 if (I.isEquality() && CI->isNullValue() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006049 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006050 // (icmp cond A B) if cond is equality
Owen Anderson333c4002009-07-09 23:48:35 +00006051 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006052 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006053
Dan Gohman81b28ce2008-09-16 18:46:06 +00006054 // If we have an icmp le or icmp ge instruction, turn it into the
6055 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6056 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006057 switch (I.getPredicate()) {
6058 default: break;
6059 case ICmpInst::ICMP_ULE:
6060 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006061 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006062 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6063 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006064 case ICmpInst::ICMP_SLE:
6065 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006066 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006067 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6068 AddOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006069 case ICmpInst::ICMP_UGE:
6070 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006071 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006072 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6073 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006074 case ICmpInst::ICMP_SGE:
6075 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Andersond672ecb2009-07-03 00:17:18 +00006076 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson333c4002009-07-09 23:48:35 +00006077 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6078 SubOne(CI, Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006079 }
6080
Chris Lattner183661e2008-07-11 05:40:05 +00006081 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006082 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006083 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6085 }
6086
6087 // See if we can fold the comparison based on range information we can get
6088 // by checking whether bits are known to be zero or one in the input.
6089 if (BitWidth != 0) {
6090 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6091 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6092
6093 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006094 isSignBit ? APInt::getSignBit(BitWidth)
6095 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006097 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098 if (SimplifyDemandedBits(I.getOperandUse(1),
6099 APInt::getAllOnesValue(BitWidth),
6100 Op1KnownZero, Op1KnownOne, 0))
6101 return &I;
6102
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006103 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006104 // in. Compute the Min, Max and RHS values based on the known bits. For the
6105 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006106 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6107 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6108 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6109 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6110 Op0Min, Op0Max);
6111 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6112 Op1Min, Op1Max);
6113 } else {
6114 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6115 Op0Min, Op0Max);
6116 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6117 Op1Min, Op1Max);
6118 }
6119
Chris Lattner183661e2008-07-11 05:40:05 +00006120 // If Min and Max are known to be the same, then SimplifyDemandedBits
6121 // figured out that the LHS is a constant. Just constant fold this now so
6122 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006123 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006124 return new ICmpInst(*Context, I.getPredicate(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006125 Context->getConstantInt(Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson333c4002009-07-09 23:48:35 +00006127 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006128 Context->getConstantInt(Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129
Chris Lattner183661e2008-07-11 05:40:05 +00006130 // Based on the range information we know about the LHS, see if we can
6131 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006133 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006134 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006136 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006137 break;
6138 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Andersond672ecb2009-07-03 00:17:18 +00006140 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner84dff672008-07-11 05:08:55 +00006141 break;
6142 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006144 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006146 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006148 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6150 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006151 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6152 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153
6154 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6155 if (CI->isMinValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006156 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson73c6b712009-07-13 20:58:05 +00006157 Context->getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158 }
Chris Lattner84dff672008-07-11 05:08:55 +00006159 break;
6160 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006162 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006164 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006165
6166 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006167 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6169 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006170 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6171 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172
6173 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6174 if (CI->isMaxValue(true))
Owen Anderson333c4002009-07-09 23:48:35 +00006175 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Andersond672ecb2009-07-03 00:17:18 +00006176 Context->getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 }
Chris Lattner84dff672008-07-11 05:08:55 +00006178 break;
6179 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006181 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Andersond672ecb2009-07-03 00:17:18 +00006183 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006185 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6187 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006188 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6189 SubOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 }
Chris Lattner84dff672008-07-11 05:08:55 +00006191 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006192 case ICmpInst::ICMP_SGT:
6193 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006194 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006195 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006196 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197
6198 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson333c4002009-07-09 23:48:35 +00006199 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6201 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson333c4002009-07-09 23:48:35 +00006202 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6203 AddOne(CI, Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006204 }
6205 break;
6206 case ICmpInst::ICMP_SGE:
6207 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6208 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006209 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006210 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006211 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006212 break;
6213 case ICmpInst::ICMP_SLE:
6214 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6215 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006216 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006217 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006218 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219 break;
6220 case ICmpInst::ICMP_UGE:
6221 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6222 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006223 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006224 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006225 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 break;
6227 case ICmpInst::ICMP_ULE:
6228 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6229 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006230 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006231 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Andersond672ecb2009-07-03 00:17:18 +00006232 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006233 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006234 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006235
6236 // Turn a signed comparison into an unsigned one if both operands
6237 // are known to have the same sign.
6238 if (I.isSignedPredicate() &&
6239 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6240 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson333c4002009-07-09 23:48:35 +00006241 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006242 }
6243
6244 // Test if the ICmpInst instruction is used exclusively by a select as
6245 // part of a minimum or maximum operation. If so, refrain from doing
6246 // any other folding. This helps out other analyses which understand
6247 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6248 // and CodeGen. And in this case, at least one of the comparison
6249 // operands has at least one user besides the compare (the select),
6250 // which would often largely negate the benefit of folding anyway.
6251 if (I.hasOneUse())
6252 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6253 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6254 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6255 return 0;
6256
6257 // See if we are doing a comparison between a constant and an instruction that
6258 // can be folded into the comparison.
6259 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006260 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006261 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006262 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006263 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006264 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6265 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006266 }
6267
Chris Lattner01deb9d2007-04-03 17:43:25 +00006268 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006269 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6270 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6271 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006272 case Instruction::GetElementPtr:
6273 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006274 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006275 bool isAllZeros = true;
6276 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6277 if (!isa<Constant>(LHSI->getOperand(i)) ||
6278 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6279 isAllZeros = false;
6280 break;
6281 }
6282 if (isAllZeros)
Owen Anderson333c4002009-07-09 23:48:35 +00006283 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006284 Context->getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006285 }
6286 break;
6287
Chris Lattner6970b662005-04-23 15:31:55 +00006288 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006289 // Only fold icmp into the PHI if the phi and fcmp are in the same
6290 // block. If in the same block, we're encouraging jump threading. If
6291 // not, we are just pessimizing the code by making an i1 phi.
6292 if (LHSI->getParent() == I.getParent())
6293 if (Instruction *NV = FoldOpIntoPhi(I))
6294 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006295 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006296 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006297 // If either operand of the select is a constant, we can fold the
6298 // comparison into the select arms, which will cause one to be
6299 // constant folded and the select turned into a bitwise or.
6300 Value *Op1 = 0, *Op2 = 0;
6301 if (LHSI->hasOneUse()) {
6302 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6303 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006304 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006305 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006306 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006307 LHSI->getOperand(2), RHSC,
6308 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006309 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6310 // Fold the known value into the constant operand.
Owen Andersond672ecb2009-07-03 00:17:18 +00006311 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006312 // Insert a new ICmp of the other select operand.
Owen Anderson333c4002009-07-09 23:48:35 +00006313 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00006314 LHSI->getOperand(1), RHSC,
6315 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006316 }
6317 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006318
Chris Lattner6970b662005-04-23 15:31:55 +00006319 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006320 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006321 break;
6322 }
Chris Lattner4802d902007-04-06 18:57:34 +00006323 case Instruction::Malloc:
6324 // If we have (malloc != null), and if the malloc has a single use, we
6325 // can assume it is successful and remove the malloc.
6326 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6327 AddToWorkList(LHSI);
Owen Andersond672ecb2009-07-03 00:17:18 +00006328 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006329 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006330 }
6331 break;
6332 }
Chris Lattner6970b662005-04-23 15:31:55 +00006333 }
6334
Reid Spencere4d87aa2006-12-23 06:05:41 +00006335 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006336 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006337 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006338 return NI;
6339 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006340 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6341 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006342 return NI;
6343
Reid Spencere4d87aa2006-12-23 06:05:41 +00006344 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006345 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6346 // now.
6347 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6348 if (isa<PointerType>(Op0->getType()) &&
6349 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006350 // We keep moving the cast from the left operand over to the right
6351 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006352 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006353
Chris Lattner57d86372007-01-06 01:45:59 +00006354 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6355 // so eliminate it as well.
6356 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6357 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006358
Chris Lattnerde90b762003-11-03 04:25:02 +00006359 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006360 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006361 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006362 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006363 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006364 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006365 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006366 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006367 }
Owen Anderson333c4002009-07-09 23:48:35 +00006368 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006369 }
Chris Lattner57d86372007-01-06 01:45:59 +00006370 }
6371
6372 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006373 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006374 // This comes up when you have code like
6375 // int X = A < B;
6376 // if (X) ...
6377 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006378 // with a constant or another cast from the same type.
6379 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006380 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006381 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006382 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006383
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006384 // See if it's the same type of instruction on the left and right.
6385 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6386 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006387 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006388 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006389 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006390 default: break;
6391 case Instruction::Add:
6392 case Instruction::Sub:
6393 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006394 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson333c4002009-07-09 23:48:35 +00006395 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006396 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006397 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6398 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6399 if (CI->getValue().isSignBit()) {
6400 ICmpInst::Predicate Pred = I.isSignedPredicate()
6401 ? I.getUnsignedPredicate()
6402 : I.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006403 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006404 Op1I->getOperand(0));
6405 }
6406
6407 if (CI->getValue().isMaxSignedValue()) {
6408 ICmpInst::Predicate Pred = I.isSignedPredicate()
6409 ? I.getUnsignedPredicate()
6410 : I.getSignedPredicate();
6411 Pred = I.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006412 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006413 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006414 }
6415 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006416 break;
6417 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006418 if (!I.isEquality())
6419 break;
6420
Nick Lewycky5d52c452008-08-21 05:56:10 +00006421 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6422 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6423 // Mask = -1 >> count-trailing-zeros(Cst).
6424 if (!CI->isZero() && !CI->isOne()) {
6425 const APInt &AP = CI->getValue();
Owen Andersond672ecb2009-07-03 00:17:18 +00006426 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky5d52c452008-08-21 05:56:10 +00006427 APInt::getLowBitsSet(AP.getBitWidth(),
6428 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006429 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006430 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6431 Mask);
6432 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6433 Mask);
6434 InsertNewInstBefore(And1, I);
6435 InsertNewInstBefore(And2, I);
Owen Anderson333c4002009-07-09 23:48:35 +00006436 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006437 }
6438 }
6439 break;
6440 }
6441 }
6442 }
6443 }
6444
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006445 // ~x < ~y --> y < x
6446 { Value *A, *B;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006447 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6448 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006449 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006450 }
6451
Chris Lattner65b72ba2006-09-18 04:22:48 +00006452 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006453 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006454
6455 // -x == -y --> x == y
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006456 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6457 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006458 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006459
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006460 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006461 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6462 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006463 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006464 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006465 }
6466
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006467 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006468 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006469 ConstantInt *C1, *C2;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006470 if (match(B, m_ConstantInt(C1), *Context) &&
6471 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006472 Constant *NC =
6473 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattnercb504b92008-11-16 05:38:51 +00006474 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson333c4002009-07-09 23:48:35 +00006475 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattnercb504b92008-11-16 05:38:51 +00006476 InsertNewInstBefore(Xor, I));
6477 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006478
6479 // A^B == A^D -> B == D
Owen Anderson333c4002009-07-09 23:48:35 +00006480 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6481 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6482 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6483 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006484 }
6485 }
6486
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006487 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006488 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006489 // A == (A^B) -> B == 0
6490 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson333c4002009-07-09 23:48:35 +00006491 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006492 Context->getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006493 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006494
6495 // (A-B) == A -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006496 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006497 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006498 Context->getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006499
6500 // A == (A-B) -> B == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006501 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson333c4002009-07-09 23:48:35 +00006502 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Andersond672ecb2009-07-03 00:17:18 +00006503 Context->getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006504
Chris Lattner9c2328e2006-11-14 06:06:06 +00006505 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6506 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00006507 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6508 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006509 Value *X = 0, *Y = 0, *Z = 0;
6510
6511 if (A == C) {
6512 X = B; Y = D; Z = A;
6513 } else if (A == D) {
6514 X = B; Y = C; Z = A;
6515 } else if (B == C) {
6516 X = A; Y = D; Z = B;
6517 } else if (B == D) {
6518 X = A; Y = C; Z = B;
6519 }
6520
6521 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006522 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6523 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006524 I.setOperand(0, Op1);
Owen Andersond672ecb2009-07-03 00:17:18 +00006525 I.setOperand(1, Context->getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006526 return &I;
6527 }
6528 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006529 }
Chris Lattner7e708292002-06-25 16:13:24 +00006530 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006531}
6532
Chris Lattner562ef782007-06-20 23:46:26 +00006533
6534/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6535/// and CmpRHS are both known to be integer constants.
6536Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6537 ConstantInt *DivRHS) {
6538 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6539 const APInt &CmpRHSV = CmpRHS->getValue();
6540
6541 // FIXME: If the operand types don't match the type of the divide
6542 // then don't attempt this transform. The code below doesn't have the
6543 // logic to deal with a signed divide and an unsigned compare (and
6544 // vice versa). This is because (x /s C1) <s C2 produces different
6545 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6546 // (x /u C1) <u C2. Simply casting the operands and result won't
6547 // work. :( The if statement below tests that condition and bails
6548 // if it finds it.
6549 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6550 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6551 return 0;
6552 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006553 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006554 if (DivIsSigned && DivRHS->isAllOnesValue())
6555 return 0; // The overflow computation also screws up here
6556 if (DivRHS->isOne())
6557 return 0; // Not worth bothering, and eliminates some funny cases
6558 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006559
6560 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6561 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6562 // C2 (CI). By solving for X we can turn this into a range check
6563 // instead of computing a divide.
Owen Andersond672ecb2009-07-03 00:17:18 +00006564 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006565
6566 // Determine if the product overflows by seeing if the product is
6567 // not equal to the divide. Make sure we do the same kind of divide
6568 // as in the LHS instruction that we're folding.
Owen Andersond672ecb2009-07-03 00:17:18 +00006569 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6570 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006571
6572 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006574
Chris Lattner1dbfd482007-06-21 18:11:19 +00006575 // Figure out the interval that is being checked. For example, a comparison
6576 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6577 // Compute this interval based on the constants involved and the signedness of
6578 // the compare/divide. This computes a half-open interval, keeping track of
6579 // whether either value in the interval overflows. After analysis each
6580 // overflow variable is set to 0 if it's corresponding bound variable is valid
6581 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6582 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006583 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006584
Chris Lattner562ef782007-06-20 23:46:26 +00006585 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006587 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006588 HiOverflow = LoOverflow = ProdOV;
6589 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006590 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006591 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006592 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006593 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00006594 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6595 Context)));
Chris Lattner562ef782007-06-20 23:46:26 +00006596 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006597 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006598 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6599 HiOverflow = LoOverflow = ProdOV;
6600 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006601 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006602 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006603 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006604 HiBound = AddOne(Prod, Context);
Chris Lattnera6321b42008-10-11 22:55:00 +00006605 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6606 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006607 ConstantInt* DivNeg =
6608 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6609 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006610 true) ? -1 : 0;
6611 }
Chris Lattner562ef782007-06-20 23:46:26 +00006612 }
Dan Gohman76491272008-02-13 22:09:18 +00006613 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006614 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006615 // e.g. X/-5 op 0 --> [-4, 5)
Owen Andersond672ecb2009-07-03 00:17:18 +00006616 LoBound = AddOne(DivRHS, Context);
6617 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006618 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6619 HiOverflow = 1; // [INTMIN+1, overflow)
6620 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6621 }
Dan Gohman76491272008-02-13 22:09:18 +00006622 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006623 // e.g. X/-5 op 3 --> [-19, -14)
Owen Andersond672ecb2009-07-03 00:17:18 +00006624 HiBound = AddOne(Prod, Context);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006625 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006626 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006627 LoOverflow = AddWithOverflow(LoBound, HiBound,
6628 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006629 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006630 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6631 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006632 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006633 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006634 }
6635
Chris Lattner1dbfd482007-06-21 18:11:19 +00006636 // Dividing by a negative swaps the condition. LT <-> GT
6637 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006638 }
6639
6640 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006641 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006642 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006643 case ICmpInst::ICMP_EQ:
6644 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006645 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner562ef782007-06-20 23:46:26 +00006646 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006647 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006648 ICmpInst::ICMP_UGE, X, LoBound);
6649 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006650 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006651 ICmpInst::ICMP_ULT, X, HiBound);
6652 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006653 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006654 case ICmpInst::ICMP_NE:
6655 if (LoOverflow && HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006656 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner562ef782007-06-20 23:46:26 +00006657 else if (HiOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006658 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006659 ICmpInst::ICMP_ULT, X, LoBound);
6660 else if (LoOverflow)
Owen Anderson333c4002009-07-09 23:48:35 +00006661 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006662 ICmpInst::ICMP_UGE, X, HiBound);
6663 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006664 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006665 case ICmpInst::ICMP_ULT:
6666 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006667 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006668 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006669 if (LoOverflow == -1) // Low bound is less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006670 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson333c4002009-07-09 23:48:35 +00006671 return new ICmpInst(*Context, Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006672 case ICmpInst::ICMP_UGT:
6673 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006674 if (HiOverflow == +1) // High bound greater than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006675 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006676 else if (HiOverflow == -1) // High bound less than input range.
Owen Andersond672ecb2009-07-03 00:17:18 +00006677 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006678 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson333c4002009-07-09 23:48:35 +00006679 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006680 else
Owen Anderson333c4002009-07-09 23:48:35 +00006681 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006682 }
6683}
6684
6685
Chris Lattner01deb9d2007-04-03 17:43:25 +00006686/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6687///
6688Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6689 Instruction *LHSI,
6690 ConstantInt *RHS) {
6691 const APInt &RHSV = RHS->getValue();
6692
6693 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006694 case Instruction::Trunc:
6695 if (ICI.isEquality() && LHSI->hasOneUse()) {
6696 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6697 // of the high bits truncated out of x are known.
6698 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6699 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6700 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6701 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6702 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6703
6704 // If all the high bits are known, we can do this xform.
6705 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6706 // Pull in the high bits from known-ones set.
6707 APInt NewRHS(RHS->getValue());
6708 NewRHS.zext(SrcBits);
6709 NewRHS |= KnownOne;
Owen Anderson333c4002009-07-09 23:48:35 +00006710 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006711 Context->getConstantInt(NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006712 }
6713 }
6714 break;
6715
Duncan Sands0091bf22007-04-04 06:42:45 +00006716 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006717 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6718 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6719 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006720 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6721 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006722 Value *CompareVal = LHSI->getOperand(0);
6723
6724 // If the sign bit of the XorCST is not set, there is no change to
6725 // the operation, just stop using the Xor.
6726 if (!XorCST->getValue().isNegative()) {
6727 ICI.setOperand(0, CompareVal);
6728 AddToWorkList(LHSI);
6729 return &ICI;
6730 }
6731
6732 // Was the old condition true if the operand is positive?
6733 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6734
6735 // If so, the new one isn't.
6736 isTrueIfPositive ^= true;
6737
6738 if (isTrueIfPositive)
Owen Anderson333c4002009-07-09 23:48:35 +00006739 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006740 SubOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006741 else
Owen Anderson333c4002009-07-09 23:48:35 +00006742 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Andersond672ecb2009-07-03 00:17:18 +00006743 AddOne(RHS, Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006744 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006745
6746 if (LHSI->hasOneUse()) {
6747 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6748 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6749 const APInt &SignBit = XorCST->getValue();
6750 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6751 ? ICI.getUnsignedPredicate()
6752 : ICI.getSignedPredicate();
Owen Anderson333c4002009-07-09 23:48:35 +00006753 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006754 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006755 }
6756
6757 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006758 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006759 const APInt &NotSignBit = XorCST->getValue();
6760 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6761 ? ICI.getUnsignedPredicate()
6762 : ICI.getSignedPredicate();
6763 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson333c4002009-07-09 23:48:35 +00006764 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006765 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006766 }
6767 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006768 }
6769 break;
6770 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6771 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6772 LHSI->getOperand(0)->hasOneUse()) {
6773 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6774
6775 // If the LHS is an AND of a truncating cast, we can widen the
6776 // and/compare to be the input width without changing the value
6777 // produced, eliminating a cast.
6778 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6779 // We can do this transformation if either the AND constant does not
6780 // have its sign bit set or if it is an equality comparison.
6781 // Extending a relational comparison when we're checking the sign
6782 // bit would not work.
6783 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006784 (ICI.isEquality() ||
6785 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006786 uint32_t BitWidth =
6787 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6788 APInt NewCST = AndCST->getValue();
6789 NewCST.zext(BitWidth);
6790 APInt NewCI = RHSV;
6791 NewCI.zext(BitWidth);
6792 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006793 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006794 Context->getConstantInt(NewCST),LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006795 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006796 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Andersond672ecb2009-07-03 00:17:18 +00006797 Context->getConstantInt(NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006798 }
6799 }
6800
6801 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6802 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6803 // happens a LOT in code produced by the C front-end, for bitfield
6804 // access.
6805 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6806 if (Shift && !Shift->isShift())
6807 Shift = 0;
6808
6809 ConstantInt *ShAmt;
6810 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6811 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6812 const Type *AndTy = AndCST->getType(); // Type of the and.
6813
6814 // We can fold this as long as we can't shift unknown bits
6815 // into the mask. This can only happen with signed shift
6816 // rights, as they sign-extend.
6817 if (ShAmt) {
6818 bool CanFold = Shift->isLogicalShift();
6819 if (!CanFold) {
6820 // To test for the bad case of the signed shr, see if any
6821 // of the bits shifted in could be tested after the mask.
6822 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6823 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6824
6825 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6826 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6827 AndCST->getValue()) == 0)
6828 CanFold = true;
6829 }
6830
6831 if (CanFold) {
6832 Constant *NewCst;
6833 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006834 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006835 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006836 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006837
6838 // Check to see if we are shifting out any of the bits being
6839 // compared.
Owen Andersond672ecb2009-07-03 00:17:18 +00006840 if (Context->getConstantExpr(Shift->getOpcode(),
6841 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006842 // If we shifted bits out, the fold is not going to work out.
6843 // As a special case, check to see if this means that the
6844 // result is always true or false now.
6845 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00006846 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006847 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00006848 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006849 } else {
6850 ICI.setOperand(1, NewCst);
6851 Constant *NewAndCST;
6852 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersond672ecb2009-07-03 00:17:18 +00006853 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006854 else
Owen Andersond672ecb2009-07-03 00:17:18 +00006855 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006856 LHSI->setOperand(1, NewAndCST);
6857 LHSI->setOperand(0, Shift->getOperand(0));
6858 AddToWorkList(Shift); // Shift is dead.
6859 AddUsesToWorkList(ICI);
6860 return &ICI;
6861 }
6862 }
6863 }
6864
6865 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6866 // preferable because it allows the C<<Y expression to be hoisted out
6867 // of a loop if Y is invariant and X is not.
6868 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006869 ICI.isEquality() && !Shift->isArithmeticShift() &&
6870 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006871 // Compute C << Y.
6872 Value *NS;
6873 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006874 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006875 Shift->getOperand(1), "tmp");
6876 } else {
6877 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006878 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006879 Shift->getOperand(1), "tmp");
6880 }
6881 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6882
6883 // Compute X & (C << Y).
6884 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006885 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006886 InsertNewInstBefore(NewAnd, ICI);
6887
6888 ICI.setOperand(0, NewAnd);
6889 return &ICI;
6890 }
6891 }
6892 break;
6893
Chris Lattnera0141b92007-07-15 20:42:37 +00006894 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6895 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6896 if (!ShAmt) break;
6897
6898 uint32_t TypeBits = RHSV.getBitWidth();
6899
6900 // Check that the shift amount is in range. If not, don't perform
6901 // undefined shifts. When the shift is visited it will be
6902 // simplified.
6903 if (ShAmt->uge(TypeBits))
6904 break;
6905
6906 if (ICI.isEquality()) {
6907 // If we are comparing against bits always shifted out, the
6908 // comparison cannot succeed.
6909 Constant *Comp =
Owen Andersond672ecb2009-07-03 00:17:18 +00006910 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6911 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006912 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6913 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006914 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006915 return ReplaceInstUsesWith(ICI, Cst);
6916 }
6917
6918 if (LHSI->hasOneUse()) {
6919 // Otherwise strength reduce the shift into an and.
6920 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6921 Constant *Mask =
Owen Andersond672ecb2009-07-03 00:17:18 +00006922 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6923 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006924
Chris Lattnera0141b92007-07-15 20:42:37 +00006925 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006926 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006927 Mask, LHSI->getName()+".mask");
6928 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00006929 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00006930 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006931 }
6932 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006933
6934 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6935 bool TrueIfSigned = false;
6936 if (LHSI->hasOneUse() &&
6937 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6938 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersond672ecb2009-07-03 00:17:18 +00006939 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006940 (TypeBits-ShAmt->getZExtValue()-1));
6941 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006942 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006943 Mask, LHSI->getName()+".mask");
6944 Value *And = InsertNewInstBefore(AndI, ICI);
6945
Owen Anderson333c4002009-07-09 23:48:35 +00006946 return new ICmpInst(*Context,
6947 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersond672ecb2009-07-03 00:17:18 +00006948 And, Context->getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006949 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006950 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006951 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006952
6953 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006954 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006955 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006956 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006957 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006958
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006959 // Check that the shift amount is in range. If not, don't perform
6960 // undefined shifts. When the shift is visited it will be
6961 // simplified.
6962 uint32_t TypeBits = RHSV.getBitWidth();
6963 if (ShAmt->uge(TypeBits))
6964 break;
6965
6966 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006967
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006968 // If we are comparing against bits always shifted out, the
6969 // comparison cannot succeed.
6970 APInt Comp = RHSV << ShAmtVal;
6971 if (LHSI->getOpcode() == Instruction::LShr)
6972 Comp = Comp.lshr(ShAmtVal);
6973 else
6974 Comp = Comp.ashr(ShAmtVal);
6975
6976 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6977 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Andersond672ecb2009-07-03 00:17:18 +00006978 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006979 return ReplaceInstUsesWith(ICI, Cst);
6980 }
6981
6982 // Otherwise, check to see if the bits shifted out are known to be zero.
6983 // If so, we can compare against the unshifted value:
6984 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006985 if (LHSI->hasOneUse() &&
6986 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006987 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson333c4002009-07-09 23:48:35 +00006988 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00006989 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006990 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006991
Evan Chengf30752c2008-04-23 00:38:06 +00006992 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006993 // Otherwise strength reduce the shift into an and.
6994 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersond672ecb2009-07-03 00:17:18 +00006995 Constant *Mask = Context->getConstantInt(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006996
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006997 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006998 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006999 Mask, LHSI->getName()+".mask");
7000 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007001 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Andersond672ecb2009-07-03 00:17:18 +00007002 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007003 }
7004 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007005 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007006
7007 case Instruction::SDiv:
7008 case Instruction::UDiv:
7009 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7010 // Fold this div into the comparison, producing a range check.
7011 // Determine, based on the divide type, what the range is being
7012 // checked. If there is an overflow on the low or high side, remember
7013 // it, otherwise compute the range [low, hi) bounding the new value.
7014 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007015 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7016 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7017 DivRHS))
7018 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007019 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007020
7021 case Instruction::Add:
7022 // Fold: icmp pred (add, X, C1), C2
7023
7024 if (!ICI.isEquality()) {
7025 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7026 if (!LHSC) break;
7027 const APInt &LHSV = LHSC->getValue();
7028
7029 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7030 .subtract(LHSV);
7031
7032 if (ICI.isSignedPredicate()) {
7033 if (CR.getLower().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007034 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007035 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007036 } else if (CR.getUpper().isSignBit()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007037 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007038 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007039 }
7040 } else {
7041 if (CR.getLower().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007042 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007043 Context->getConstantInt(CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007044 } else if (CR.getUpper().isMinValue()) {
Owen Anderson333c4002009-07-09 23:48:35 +00007045 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007046 Context->getConstantInt(CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007047 }
7048 }
7049 }
7050 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007051 }
7052
7053 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7054 if (ICI.isEquality()) {
7055 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7056
7057 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7058 // the second operand is a constant, simplify a bit.
7059 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7060 switch (BO->getOpcode()) {
7061 case Instruction::SRem:
7062 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7063 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7064 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7065 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7066 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007067 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 BO->getName());
7069 InsertNewInstBefore(NewRem, ICI);
Owen Anderson333c4002009-07-09 23:48:35 +00007070 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Andersond672ecb2009-07-03 00:17:18 +00007071 Context->getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007072 }
7073 }
7074 break;
7075 case Instruction::Add:
7076 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7077 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7078 if (BO->hasOneUse())
Owen Anderson333c4002009-07-09 23:48:35 +00007079 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007080 Context->getConstantExprSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007081 } else if (RHSV == 0) {
7082 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7083 // efficiently invertible, or if the add has just this one use.
7084 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7085
Owen Andersond672ecb2009-07-03 00:17:18 +00007086 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007087 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Andersond672ecb2009-07-03 00:17:18 +00007088 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson333c4002009-07-09 23:48:35 +00007089 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007090 else if (BO->hasOneUse()) {
Owen Anderson0a5372e2009-07-13 04:09:18 +00007091 Instruction *Neg = BinaryOperator::CreateNeg(*Context, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007092 InsertNewInstBefore(Neg, ICI);
7093 Neg->takeName(BO);
Owen Anderson333c4002009-07-09 23:48:35 +00007094 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007095 }
7096 }
7097 break;
7098 case Instruction::Xor:
7099 // For the xor case, we can xor two constants together, eliminating
7100 // the explicit xor.
7101 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson333c4002009-07-09 23:48:35 +00007102 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007103 Context->getConstantExprXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007104
7105 // FALLTHROUGH
7106 case Instruction::Sub:
7107 // Replace (([sub|xor] A, B) != 0) with (A != B)
7108 if (RHSV == 0)
Owen Anderson333c4002009-07-09 23:48:35 +00007109 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007110 BO->getOperand(1));
7111 break;
7112
7113 case Instruction::Or:
7114 // If bits are being or'd in that are not present in the constant we
7115 // are comparing against, then the comparison could never succeed!
7116 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007117 Constant *NotCI = Context->getConstantExprNot(RHS);
7118 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7119 return ReplaceInstUsesWith(ICI,
7120 Context->getConstantInt(Type::Int1Ty,
7121 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007122 }
7123 break;
7124
7125 case Instruction::And:
7126 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7127 // If bits are being compared against that are and'd out, then the
7128 // comparison can never succeed!
7129 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007130 return ReplaceInstUsesWith(ICI,
7131 Context->getConstantInt(Type::Int1Ty,
7132 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007133
7134 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7135 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson333c4002009-07-09 23:48:35 +00007136 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007137 ICmpInst::ICMP_NE, LHSI,
Owen Andersond672ecb2009-07-03 00:17:18 +00007138 Context->getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007139
7140 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007141 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007142 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007143 Constant *Zero = Context->getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007144 ICmpInst::Predicate pred = isICMP_NE ?
7145 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson333c4002009-07-09 23:48:35 +00007146 return new ICmpInst(*Context, pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007147 }
7148
7149 // ((X & ~7) == 0) --> X < 8
7150 if (RHSV == 0 && isHighOnes(BOC)) {
7151 Value *X = BO->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00007152 Constant *NegX = Context->getConstantExprNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007153 ICmpInst::Predicate pred = isICMP_NE ?
7154 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson333c4002009-07-09 23:48:35 +00007155 return new ICmpInst(*Context, pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156 }
7157 }
7158 default: break;
7159 }
7160 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7161 // Handle icmp {eq|ne} <intrinsic>, intcst.
7162 if (II->getIntrinsicID() == Intrinsic::bswap) {
7163 AddToWorkList(II);
7164 ICI.setOperand(0, II->getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007165 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007166 return &ICI;
7167 }
7168 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007169 }
7170 return 0;
7171}
7172
7173/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7174/// We only handle extending casts so far.
7175///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007176Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7177 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007178 Value *LHSCIOp = LHSCI->getOperand(0);
7179 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007180 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007181 Value *RHSCIOp;
7182
Chris Lattner8c756c12007-05-05 22:41:33 +00007183 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7184 // integer type is the same size as the pointer type.
7185 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7186 getTargetData().getPointerSizeInBits() ==
7187 cast<IntegerType>(DestTy)->getBitWidth()) {
7188 Value *RHSOp = 0;
7189 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007190 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007191 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7192 RHSOp = RHSC->getOperand(0);
7193 // If the pointer types don't match, insert a bitcast.
7194 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007195 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007196 }
7197
7198 if (RHSOp)
Owen Anderson333c4002009-07-09 23:48:35 +00007199 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007200 }
7201
7202 // The code below only handles extension cast instructions, so far.
7203 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007204 if (LHSCI->getOpcode() != Instruction::ZExt &&
7205 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007206 return 0;
7207
Reid Spencere4d87aa2006-12-23 06:05:41 +00007208 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7209 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007210
Reid Spencere4d87aa2006-12-23 06:05:41 +00007211 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007212 // Not an extension from the same type?
7213 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007214 if (RHSCIOp->getType() != LHSCIOp->getType())
7215 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007216
Nick Lewycky4189a532008-01-28 03:48:02 +00007217 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007218 // and the other is a zext), then we can't handle this.
7219 if (CI->getOpcode() != LHSCI->getOpcode())
7220 return 0;
7221
Nick Lewycky4189a532008-01-28 03:48:02 +00007222 // Deal with equality cases early.
7223 if (ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007224 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007225
7226 // A signed comparison of sign extended values simplifies into a
7227 // signed comparison.
7228 if (isSignedCmp && isSignedExt)
Owen Anderson333c4002009-07-09 23:48:35 +00007229 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007230
7231 // The other three cases all fold into an unsigned comparison.
Owen Anderson333c4002009-07-09 23:48:35 +00007232 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007233 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007234
Reid Spencere4d87aa2006-12-23 06:05:41 +00007235 // If we aren't dealing with a constant on the RHS, exit early
7236 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7237 if (!CI)
7238 return 0;
7239
7240 // Compute the constant that would happen if we truncated to SrcTy then
7241 // reextended to DestTy.
Owen Andersond672ecb2009-07-03 00:17:18 +00007242 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7243 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7244 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007245
7246 // If the re-extended constant didn't change...
7247 if (Res2 == CI) {
7248 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7249 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007250 // %A = sext i16 %X to i32
7251 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007252 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007253 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007254 // because %A may have negative value.
7255 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007256 // However, we allow this when the compare is EQ/NE, because they are
7257 // signless.
7258 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson333c4002009-07-09 23:48:35 +00007259 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007260 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261 }
7262
7263 // The re-extended constant changed so the constant cannot be represented
7264 // in the shorter type. Consequently, we cannot emit a simple comparison.
7265
7266 // First, handle some easy cases. We know the result cannot be equal at this
7267 // point so handle the ICI.isEquality() cases
7268 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Andersond672ecb2009-07-03 00:17:18 +00007269 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007270 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Andersond672ecb2009-07-03 00:17:18 +00007271 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007272
7273 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7274 // should have been folded away previously and not enter in here.
7275 Value *Result;
7276 if (isSignedCmp) {
7277 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007278 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Andersond672ecb2009-07-03 00:17:18 +00007279 Result = Context->getConstantIntFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007280 else
Owen Andersond672ecb2009-07-03 00:17:18 +00007281 Result = Context->getConstantIntTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007282 } else {
7283 // We're performing an unsigned comparison.
7284 if (isSignedExt) {
7285 // We're performing an unsigned comp with a sign extended value.
7286 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson73c6b712009-07-13 20:58:05 +00007287 Constant *NegOne = Context->getAllOnesValue(SrcTy);
Owen Anderson333c4002009-07-09 23:48:35 +00007288 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7289 LHSCIOp, NegOne, ICI.getName()), ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007290 } else {
7291 // Unsigned extend & unsigned compare -> always true.
Owen Andersond672ecb2009-07-03 00:17:18 +00007292 Result = Context->getConstantIntTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007293 }
7294 }
7295
7296 // Finally, return the value computed.
7297 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007298 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007299 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007300
7301 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7302 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7303 "ICmp should be folded!");
7304 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersond672ecb2009-07-03 00:17:18 +00007305 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Owen Anderson73c6b712009-07-13 20:58:05 +00007306 return BinaryOperator::CreateNot(*Context, Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007307}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007308
Reid Spencer832254e2007-02-02 02:16:23 +00007309Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7310 return commonShiftTransforms(I);
7311}
7312
7313Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7314 return commonShiftTransforms(I);
7315}
7316
7317Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007318 if (Instruction *R = commonShiftTransforms(I))
7319 return R;
7320
7321 Value *Op0 = I.getOperand(0);
7322
7323 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7324 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7325 if (CSI->isAllOnesValue())
7326 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007327
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007328 // See if we can turn a signed shr into an unsigned shr.
7329 if (MaskedValueIsZero(Op0,
7330 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7331 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7332
7333 // Arithmetic shifting an all-sign-bit value is a no-op.
7334 unsigned NumSignBits = ComputeNumSignBits(Op0);
7335 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7336 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007337
Chris Lattner348f6652007-12-06 01:59:46 +00007338 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007339}
7340
7341Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7342 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007344
7345 // shl X, 0 == X and shr X, 0 == X
7346 // shl 0, X == 0 and shr 0, X == 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007347 if (Op1 == Context->getNullValue(Op1->getType()) ||
7348 Op0 == Context->getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007349 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007350
Reid Spencere4d87aa2006-12-23 06:05:41 +00007351 if (isa<UndefValue>(Op0)) {
7352 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007353 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007354 else // undef << X -> 0, undef >>u X -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007355 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007356 }
7357 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007358 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7359 return ReplaceInstUsesWith(I, Op0);
7360 else // X << undef, X >>u undef -> 0
Owen Andersond672ecb2009-07-03 00:17:18 +00007361 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007362 }
7363
Dan Gohman9004c8a2009-05-21 02:28:33 +00007364 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007365 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007366 return &I;
7367
Chris Lattner2eefe512004-04-09 19:05:30 +00007368 // Try to fold constant and into select arguments.
7369 if (isa<Constant>(Op0))
7370 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007371 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007372 return R;
7373
Reid Spencerb83eb642006-10-20 07:07:24 +00007374 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007375 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7376 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007377 return 0;
7378}
7379
Reid Spencerb83eb642006-10-20 07:07:24 +00007380Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007381 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007382 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007383
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007384 // See if we can simplify any instructions used by the instruction whose sole
7385 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007386 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007387
Dan Gohmana119de82009-06-14 23:30:43 +00007388 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7389 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007390 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007391 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007392 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007393 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007394 else {
Owen Andersond672ecb2009-07-03 00:17:18 +00007395 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007396 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007397 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007398 }
7399
7400 // ((X*C1) << C2) == (X * (C1 << C2))
7401 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7402 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7403 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007404 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +00007405 Context->getConstantExprShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007406
7407 // Try to fold constant and into select arguments.
7408 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7409 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7410 return R;
7411 if (isa<PHINode>(Op0))
7412 if (Instruction *NV = FoldOpIntoPhi(I))
7413 return NV;
7414
Chris Lattner8999dd32007-12-22 09:07:47 +00007415 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7416 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7417 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7418 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7419 // place. Don't try to do this transformation in this case. Also, we
7420 // require that the input operand is a shift-by-constant so that we have
7421 // confidence that the shifts will get folded together. We could do this
7422 // xform in more cases, but it is unlikely to be profitable.
7423 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7424 isa<ConstantInt>(TrOp->getOperand(1))) {
7425 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersond672ecb2009-07-03 00:17:18 +00007426 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007427 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007428 I.getName());
7429 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7430
7431 // For logical shifts, the truncation has the effect of making the high
7432 // part of the register be zeros. Emulate this by inserting an AND to
7433 // clear the top bits as needed. This 'and' will usually be zapped by
7434 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007435 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7436 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007437 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7438
7439 // The mask we constructed says what the trunc would do if occurring
7440 // between the shifts. We want to know the effect *after* the second
7441 // shift. We know that it is a logical shift by a constant, so adjust the
7442 // mask as appropriate.
7443 if (I.getOpcode() == Instruction::Shl)
7444 MaskV <<= Op1->getZExtValue();
7445 else {
7446 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7447 MaskV = MaskV.lshr(Op1->getZExtValue());
7448 }
7449
Owen Andersond672ecb2009-07-03 00:17:18 +00007450 Instruction *And =
7451 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7452 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007453 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7454
7455 // Return the value truncated to the interesting size.
7456 return new TruncInst(And, I.getType());
7457 }
7458 }
7459
Chris Lattner4d5542c2006-01-06 07:12:35 +00007460 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007461 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7462 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7463 Value *V1, *V2;
7464 ConstantInt *CC;
7465 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007466 default: break;
7467 case Instruction::Add:
7468 case Instruction::And:
7469 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007470 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007471 // These operators commute.
7472 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007473 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007474 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7475 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007476 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007477 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007478 Op0BO->getName());
7479 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007480 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007481 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007482 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007483 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007484 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007485 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007486 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007487 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007488
Chris Lattner150f12a2005-09-18 06:30:59 +00007489 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007490 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007491 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007492 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007493 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007494 m_ConstantInt(CC)), *Context) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007495 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007496 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007497 Op0BO->getOperand(0), Op1,
7498 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007499 InsertNewInstBefore(YS, I); // (Y << C)
7500 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007501 BinaryOperator::CreateAnd(V1,
7502 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007503 V1->getName()+".mask");
7504 InsertNewInstBefore(XM, I); // X & (CC << C)
7505
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007506 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007507 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007508 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007509
Reid Spencera07cb7d2007-02-02 14:41:37 +00007510 // FALL THROUGH.
7511 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007512 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007513 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007514 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7515 m_Specific(Op1)), *Context)){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007516 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007517 Op0BO->getOperand(1), Op1,
7518 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007519 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007520 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007521 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007522 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007523 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007524 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersond672ecb2009-07-03 00:17:18 +00007525 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Zhou Sheng90b96812007-03-30 05:45:18 +00007526 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007527 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007528
Chris Lattner13d4ab42006-05-31 21:14:00 +00007529 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007530 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7531 match(Op0BO->getOperand(0),
7532 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007533 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007534 cast<BinaryOperator>(Op0BO->getOperand(0))
7535 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007536 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007537 Op0BO->getOperand(1), Op1,
7538 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007539 InsertNewInstBefore(YS, I); // (Y << C)
7540 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007541 BinaryOperator::CreateAnd(V1,
7542 Context->getConstantExprShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007543 V1->getName()+".mask");
7544 InsertNewInstBefore(XM, I); // X & (CC << C)
7545
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007546 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007547 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007548
Chris Lattner11021cb2005-09-18 05:12:10 +00007549 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007550 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007551 }
7552
7553
7554 // If the operand is an bitwise operator with a constant RHS, and the
7555 // shift is the only use, we can pull it out of the shift.
7556 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7557 bool isValid = true; // Valid only for And, Or, Xor
7558 bool highBitSet = false; // Transform if high bit of constant set?
7559
7560 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007561 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007562 case Instruction::Add:
7563 isValid = isLeftShift;
7564 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007565 case Instruction::Or:
7566 case Instruction::Xor:
7567 highBitSet = false;
7568 break;
7569 case Instruction::And:
7570 highBitSet = true;
7571 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007572 }
7573
7574 // If this is a signed shift right, and the high bit is modified
7575 // by the logical operation, do not perform the transformation.
7576 // The highBitSet boolean indicates the value of the high bit of
7577 // the constant which would cause it to be modified for this
7578 // operation.
7579 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007580 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007581 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007582
7583 if (isValid) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007584 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007585
7586 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007587 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007588 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007589 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007590
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007591 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007592 NewRHS);
7593 }
7594 }
7595 }
7596 }
7597
Chris Lattnerad0124c2006-01-06 07:52:12 +00007598 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007599 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7600 if (ShiftOp && !ShiftOp->isShift())
7601 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007602
Reid Spencerb83eb642006-10-20 07:07:24 +00007603 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007604 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007605 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7606 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007607 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7608 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7609 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007610
Zhou Sheng4351c642007-04-02 08:20:41 +00007611 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007612
7613 const IntegerType *Ty = cast<IntegerType>(I.getType());
7614
7615 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007616 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007617 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7618 // saturates.
7619 if (AmtSum >= TypeBits) {
7620 if (I.getOpcode() != Instruction::AShr)
Owen Andersond672ecb2009-07-03 00:17:18 +00007621 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007622 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7623 }
7624
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007625 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007626 Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007627 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7628 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007629 if (AmtSum >= TypeBits)
Owen Andersond672ecb2009-07-03 00:17:18 +00007630 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007631
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersond672ecb2009-07-03 00:17:18 +00007633 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007634 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7635 I.getOpcode() == Instruction::LShr) {
7636 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007637 if (AmtSum >= TypeBits)
7638 AmtSum = TypeBits-1;
7639
Chris Lattnerb87056f2007-02-05 00:57:54 +00007640 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007641 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007642 InsertNewInstBefore(Shift, I);
7643
Zhou Shenge9e03f62007-03-28 15:02:20 +00007644 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007645 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007646 }
7647
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648 // Okay, if we get here, one shift must be left, and the other shift must be
7649 // right. See if the amounts are equal.
7650 if (ShiftAmt1 == ShiftAmt2) {
7651 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7652 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007653 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007654 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007655 }
7656 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7657 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007658 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersond672ecb2009-07-03 00:17:18 +00007659 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007660 }
7661 // We can simplify ((X << C) >>s C) into a trunc + sext.
7662 // NOTE: we could do this for any C, but that would make 'unusual' integer
7663 // types. For now, just stick to ones well-supported by the code
7664 // generators.
7665 const Type *SExtType = 0;
7666 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007667 case 1 :
7668 case 8 :
7669 case 16 :
7670 case 32 :
7671 case 64 :
7672 case 128:
Owen Andersond672ecb2009-07-03 00:17:18 +00007673 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007674 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007675 default: break;
7676 }
7677 if (SExtType) {
7678 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7679 InsertNewInstBefore(NewTrunc, I);
7680 return new SExtInst(NewTrunc, Ty);
7681 }
7682 // Otherwise, we can't handle it yet.
7683 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007684 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007685
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007686 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007687 if (I.getOpcode() == Instruction::Shl) {
7688 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7689 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007690 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007691 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007692 InsertNewInstBefore(Shift, I);
7693
Reid Spencer55702aa2007-03-25 21:11:44 +00007694 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007695 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007696 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007697
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007698 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007699 if (I.getOpcode() == Instruction::LShr) {
7700 assert(ShiftOp->getOpcode() == Instruction::Shl);
7701 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007702 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007703 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007704
Reid Spencerd5e30f02007-03-26 17:18:58 +00007705 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007706 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007707 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007708
7709 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7710 } else {
7711 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007712 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007714 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007715 if (I.getOpcode() == Instruction::Shl) {
7716 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7717 ShiftOp->getOpcode() == Instruction::AShr);
7718 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007719 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersond672ecb2009-07-03 00:17:18 +00007720 Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007721 InsertNewInstBefore(Shift, I);
7722
Reid Spencer55702aa2007-03-25 21:11:44 +00007723 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007724 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007725 }
7726
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007727 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007728 if (I.getOpcode() == Instruction::LShr) {
7729 assert(ShiftOp->getOpcode() == Instruction::Shl);
7730 Instruction *Shift =
Owen Andersond672ecb2009-07-03 00:17:18 +00007731 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007732 InsertNewInstBefore(Shift, I);
7733
Reid Spencer68d27cf2007-03-26 23:45:51 +00007734 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersond672ecb2009-07-03 00:17:18 +00007735 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007736 }
7737
7738 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007739 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007740 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007741 return 0;
7742}
7743
Chris Lattnera1be5662002-05-02 17:06:02 +00007744
Chris Lattnercfd65102005-10-29 04:36:15 +00007745/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7746/// expression. If so, decompose it, returning some value X, such that Val is
7747/// X*Scale+Offset.
7748///
7749static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007750 int &Offset, LLVMContext *Context) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007751 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007752 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007753 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007754 Scale = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +00007755 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007756 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7757 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7758 if (I->getOpcode() == Instruction::Shl) {
7759 // This is a value scaled by '1 << the shift amt'.
7760 Scale = 1U << RHS->getZExtValue();
7761 Offset = 0;
7762 return I->getOperand(0);
7763 } else if (I->getOpcode() == Instruction::Mul) {
7764 // This value is scaled by 'RHS'.
7765 Scale = RHS->getZExtValue();
7766 Offset = 0;
7767 return I->getOperand(0);
7768 } else if (I->getOpcode() == Instruction::Add) {
7769 // We have X+C. Check to see if we really have (X*C2)+C1,
7770 // where C1 is divisible by C2.
7771 unsigned SubScale;
7772 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007773 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7774 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007775 Offset += RHS->getZExtValue();
7776 Scale = SubScale;
7777 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007778 }
7779 }
7780 }
7781
7782 // Otherwise, we can't look past this.
7783 Scale = 1;
7784 Offset = 0;
7785 return Val;
7786}
7787
7788
Chris Lattnerb3f83972005-10-24 06:03:58 +00007789/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7790/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007791Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007792 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007793 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007794
Chris Lattnerb53c2382005-10-24 06:22:12 +00007795 // Remove any uses of AI that are dead.
7796 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007797
Chris Lattnerb53c2382005-10-24 06:22:12 +00007798 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7799 Instruction *User = cast<Instruction>(*UI++);
7800 if (isInstructionTriviallyDead(User)) {
7801 while (UI != E && *UI == User)
7802 ++UI; // If this instruction uses AI more than once, don't break UI.
7803
Chris Lattnerb53c2382005-10-24 06:22:12 +00007804 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007805 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007806 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007807 }
7808 }
7809
Chris Lattnerb3f83972005-10-24 06:03:58 +00007810 // Get the type really allocated and the type casted to.
7811 const Type *AllocElTy = AI.getAllocatedType();
7812 const Type *CastElTy = PTy->getElementType();
7813 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007814
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007815 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7816 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007817 if (CastElTyAlign < AllocElTyAlign) return 0;
7818
Chris Lattner39387a52005-10-24 06:35:18 +00007819 // If the allocation has multiple uses, only promote it if we are strictly
7820 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007821 // same, we open the door to infinite loops of various kinds. (A reference
7822 // from a dbg.declare doesn't count as a use for this purpose.)
7823 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7824 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007825
Duncan Sands777d2302009-05-09 07:06:46 +00007826 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7827 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007828 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007829
Chris Lattner455fcc82005-10-29 03:19:53 +00007830 // See if we can satisfy the modulus by pulling a scale out of the array
7831 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007832 unsigned ArraySizeScale;
7833 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007834 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007835 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7836 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007837
Chris Lattner455fcc82005-10-29 03:19:53 +00007838 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7839 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007840 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7841 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007842
Chris Lattner455fcc82005-10-29 03:19:53 +00007843 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7844 Value *Amt = 0;
7845 if (Scale == 1) {
7846 Amt = NumElements;
7847 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007848 // If the allocation size is constant, form a constant mul expression
Owen Andersond672ecb2009-07-03 00:17:18 +00007849 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007850 if (isa<ConstantInt>(NumElements))
Owen Andersond672ecb2009-07-03 00:17:18 +00007851 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007852 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007853 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007854 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007855 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007856 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007857 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007858 }
7859
Jeff Cohen86796be2007-04-04 16:58:57 +00007860 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007861 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007862 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007863 Amt = InsertNewInstBefore(Tmp, AI);
7864 }
7865
Chris Lattnerb3f83972005-10-24 06:03:58 +00007866 AllocationInst *New;
7867 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007868 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007869 else
Owen Anderson50dead02009-07-15 23:53:25 +00007870 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007871 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007872 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007873
Dale Johannesena0a66372009-03-05 00:39:02 +00007874 // If the allocation has one real use plus a dbg.declare, just remove the
7875 // declare.
7876 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7877 EraseInstFromFunction(*DI);
7878 }
7879 // If the allocation has multiple real uses, insert a cast and change all
7880 // things that used it to use the new cast. This will also hack on CI, but it
7881 // will die soon.
7882 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007883 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007884 // New is the allocation instruction, pointer typed. AI is the original
7885 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7886 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007887 InsertNewInstBefore(NewCast, AI);
7888 AI.replaceAllUsesWith(NewCast);
7889 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007890 return ReplaceInstUsesWith(CI, New);
7891}
7892
Chris Lattner70074e02006-05-13 02:06:03 +00007893/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007894/// and return it as type Ty without inserting any new casts and without
7895/// changing the computed value. This is used by code that tries to decide
7896/// whether promoting or shrinking integer operations to wider or smaller types
7897/// will allow us to eliminate a truncate or extend.
7898///
7899/// This is a truncation operation if Ty is smaller than V->getType(), or an
7900/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007901///
7902/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7903/// should return true if trunc(V) can be computed by computing V in the smaller
7904/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7905/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7906/// efficiently truncated.
7907///
7908/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7909/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7910/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007911bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007912 unsigned CastOpc,
7913 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007914 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007915 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007916 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007917
7918 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007919 if (!I) return false;
7920
Dan Gohman6de29f82009-06-15 22:12:54 +00007921 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007922
Chris Lattner951626b2007-08-02 06:11:14 +00007923 // If this is an extension or truncate, we can often eliminate it.
7924 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7925 // If this is a cast from the destination type, we can trivially eliminate
7926 // it, and this will remove a cast overall.
7927 if (I->getOperand(0)->getType() == Ty) {
7928 // If the first operand is itself a cast, and is eliminable, do not count
7929 // this as an eliminable cast. We would prefer to eliminate those two
7930 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007931 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007932 ++NumCastsRemoved;
7933 return true;
7934 }
7935 }
7936
7937 // We can't extend or shrink something that has multiple uses: doing so would
7938 // require duplicating the instruction in general, which isn't profitable.
7939 if (!I->hasOneUse()) return false;
7940
Evan Chengf35fd542009-01-15 17:01:23 +00007941 unsigned Opc = I->getOpcode();
7942 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007943 case Instruction::Add:
7944 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007945 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007946 case Instruction::And:
7947 case Instruction::Or:
7948 case Instruction::Xor:
7949 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007950 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007951 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007952 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007953 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007954
Eli Friedman070a9812009-07-13 22:46:01 +00007955 case Instruction::UDiv:
7956 case Instruction::URem: {
7957 // UDiv and URem can be truncated if all the truncated bits are zero.
7958 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7959 uint32_t BitWidth = Ty->getScalarSizeInBits();
7960 if (BitWidth < OrigBitWidth) {
7961 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7962 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7963 MaskedValueIsZero(I->getOperand(1), Mask)) {
7964 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7965 NumCastsRemoved) &&
7966 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7967 NumCastsRemoved);
7968 }
7969 }
7970 break;
7971 }
Chris Lattner46b96052006-11-29 07:18:39 +00007972 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007973 // If we are truncating the result of this SHL, and if it's a shift of a
7974 // constant amount, we can always perform a SHL in a smaller type.
7975 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007976 uint32_t BitWidth = Ty->getScalarSizeInBits();
7977 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007978 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007979 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007980 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007981 }
7982 break;
7983 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007984 // If this is a truncate of a logical shr, we can truncate it to a smaller
7985 // lshr iff we know that the bits we would otherwise be shifting in are
7986 // already zeros.
7987 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007988 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7989 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007990 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007991 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007992 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7993 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007994 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007995 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007996 }
7997 }
Chris Lattner46b96052006-11-29 07:18:39 +00007998 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007999 case Instruction::ZExt:
8000 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008001 case Instruction::Trunc:
8002 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008003 // can safely replace it. Note that replacing it does not reduce the number
8004 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008005 if (Opc == CastOpc)
8006 return true;
8007
8008 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008009 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008010 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008011 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008012 case Instruction::Select: {
8013 SelectInst *SI = cast<SelectInst>(I);
8014 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008015 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008016 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008017 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008018 }
Chris Lattner8114b712008-06-18 04:00:49 +00008019 case Instruction::PHI: {
8020 // We can change a phi if we can change all operands.
8021 PHINode *PN = cast<PHINode>(I);
8022 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8023 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008024 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008025 return false;
8026 return true;
8027 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008028 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008029 // TODO: Can handle more cases here.
8030 break;
8031 }
8032
8033 return false;
8034}
8035
8036/// EvaluateInDifferentType - Given an expression that
8037/// CanEvaluateInDifferentType returns true for, actually insert the code to
8038/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008039Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008040 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008041 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +00008042 return Context->getConstantExprIntegerCast(C, Ty,
8043 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008044
8045 // Otherwise, it must be an instruction.
8046 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008047 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008048 unsigned Opc = I->getOpcode();
8049 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008050 case Instruction::Add:
8051 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008052 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008053 case Instruction::And:
8054 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008055 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008056 case Instruction::AShr:
8057 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008058 case Instruction::Shl:
8059 case Instruction::UDiv:
8060 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008061 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008062 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008063 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008064 break;
8065 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008066 case Instruction::Trunc:
8067 case Instruction::ZExt:
8068 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008069 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008070 // just return the source. There's no need to insert it because it is not
8071 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008072 if (I->getOperand(0)->getType() == Ty)
8073 return I->getOperand(0);
8074
Chris Lattner8114b712008-06-18 04:00:49 +00008075 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008076 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00008077 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008078 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008079 case Instruction::Select: {
8080 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8081 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8082 Res = SelectInst::Create(I->getOperand(0), True, False);
8083 break;
8084 }
Chris Lattner8114b712008-06-18 04:00:49 +00008085 case Instruction::PHI: {
8086 PHINode *OPN = cast<PHINode>(I);
8087 PHINode *NPN = PHINode::Create(Ty);
8088 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8089 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8090 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8091 }
8092 Res = NPN;
8093 break;
8094 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008095 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008096 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008097 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008098 break;
8099 }
8100
Chris Lattner8114b712008-06-18 04:00:49 +00008101 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008102 return InsertNewInstBefore(Res, *I);
8103}
8104
Reid Spencer3da59db2006-11-27 01:05:10 +00008105/// @brief Implement the transforms common to all CastInst visitors.
8106Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008107 Value *Src = CI.getOperand(0);
8108
Dan Gohman23d9d272007-05-11 21:10:54 +00008109 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008110 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008111 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008112 if (Instruction::CastOps opc =
8113 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8114 // The first cast (CSrc) is eliminable so we need to fix up or replace
8115 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008116 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008117 }
8118 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008119
Reid Spencer3da59db2006-11-27 01:05:10 +00008120 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008121 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8122 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8123 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008124
8125 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008126 if (isa<PHINode>(Src))
8127 if (Instruction *NV = FoldOpIntoPhi(CI))
8128 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008129
Reid Spencer3da59db2006-11-27 01:05:10 +00008130 return 0;
8131}
8132
Chris Lattner46cd5a12009-01-09 05:44:56 +00008133/// FindElementAtOffset - Given a type and a constant offset, determine whether
8134/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008135/// the specified offset. If so, fill them into NewIndices and return the
8136/// resultant element type, otherwise return null.
8137static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8138 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008139 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008140 LLVMContext *Context) {
Chris Lattner3914f722009-01-24 01:00:13 +00008141 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008142
8143 // Start with the index over the outer type. Note that the type size
8144 // might be zero (even if the offset isn't zero) if the indexed type
8145 // is something like [0 x {int, int}]
8146 const Type *IntPtrTy = TD->getIntPtrType();
8147 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008148 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008149 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008150 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008151
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008152 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008153 if (Offset < 0) {
8154 --FirstIdx;
8155 Offset += TySize;
8156 assert(Offset >= 0);
8157 }
8158 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8159 }
8160
Owen Andersond672ecb2009-07-03 00:17:18 +00008161 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008162
8163 // Index into the types. If we fail, set OrigBase to null.
8164 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008165 // Indexing into tail padding between struct/array elements.
8166 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008167 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008168
Chris Lattner46cd5a12009-01-09 05:44:56 +00008169 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8170 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008171 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8172 "Offset must stay within the indexed type");
8173
Chris Lattner46cd5a12009-01-09 05:44:56 +00008174 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Andersond672ecb2009-07-03 00:17:18 +00008175 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008176
8177 Offset -= SL->getElementOffset(Elt);
8178 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008179 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008180 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008181 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersond672ecb2009-07-03 00:17:18 +00008182 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008183 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008184 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008185 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008186 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008187 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008188 }
8189 }
8190
Chris Lattner3914f722009-01-24 01:00:13 +00008191 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008192}
8193
Chris Lattnerd3e28342007-04-27 17:44:50 +00008194/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8195Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8196 Value *Src = CI.getOperand(0);
8197
Chris Lattnerd3e28342007-04-27 17:44:50 +00008198 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008199 // If casting the result of a getelementptr instruction with no offset, turn
8200 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008201 if (GEP->hasAllZeroIndices()) {
8202 // Changing the cast operand is usually not a good idea but it is safe
8203 // here because the pointer operand is being replaced with another
8204 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008205 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008206 CI.setOperand(0, GEP->getOperand(0));
8207 return &CI;
8208 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008209
8210 // If the GEP has a single use, and the base pointer is a bitcast, and the
8211 // GEP computes a constant offset, see if we can convert these three
8212 // instructions into fewer. This typically happens with unions and other
8213 // non-type-safe code.
8214 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8215 if (GEP->hasAllConstantIndices()) {
8216 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008217 ConstantInt *OffsetV =
8218 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008219 int64_t Offset = OffsetV->getSExtValue();
8220
8221 // Get the base pointer input of the bitcast, and the type it points to.
8222 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8223 const Type *GEPIdxTy =
8224 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008225 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008226 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008227 // If we were able to index down into an element, create the GEP
8228 // and bitcast the result. This eliminates one bitcast, potentially
8229 // two.
8230 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8231 NewIndices.begin(),
8232 NewIndices.end(), "");
8233 InsertNewInstBefore(NGEP, CI);
8234 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008235
Chris Lattner46cd5a12009-01-09 05:44:56 +00008236 if (isa<BitCastInst>(CI))
8237 return new BitCastInst(NGEP, CI.getType());
8238 assert(isa<PtrToIntInst>(CI));
8239 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008240 }
8241 }
8242 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008243 }
8244
8245 return commonCastTransforms(CI);
8246}
8247
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008248/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8249/// type like i42. We don't want to introduce operations on random non-legal
8250/// integer types where they don't already exist in the code. In the future,
8251/// we should consider making this based off target-data, so that 32-bit targets
8252/// won't get i64 operations etc.
8253static bool isSafeIntegerType(const Type *Ty) {
8254 switch (Ty->getPrimitiveSizeInBits()) {
8255 case 8:
8256 case 16:
8257 case 32:
8258 case 64:
8259 return true;
8260 default:
8261 return false;
8262 }
8263}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008264
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008265/// commonIntCastTransforms - This function implements the common transforms
8266/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008267Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8268 if (Instruction *Result = commonCastTransforms(CI))
8269 return Result;
8270
8271 Value *Src = CI.getOperand(0);
8272 const Type *SrcTy = Src->getType();
8273 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008274 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8275 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008276
Reid Spencer3da59db2006-11-27 01:05:10 +00008277 // See if we can simplify any instructions used by the LHS whose sole
8278 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008279 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008280 return &CI;
8281
8282 // If the source isn't an instruction or has more than one use then we
8283 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008284 Instruction *SrcI = dyn_cast<Instruction>(Src);
8285 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008286 return 0;
8287
Chris Lattnerc739cd62007-03-03 05:27:34 +00008288 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008289 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008290 // Only do this if the dest type is a simple type, don't convert the
8291 // expression tree to something weird like i93 unless the source is also
8292 // strange.
8293 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008294 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8295 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008296 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008297 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008298 // eliminates the cast, so it is always a win. If this is a zero-extension,
8299 // we need to do an AND to maintain the clear top-part of the computation,
8300 // so we require that the input have eliminated at least one cast. If this
8301 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008302 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008303 bool DoXForm = false;
8304 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008305 switch (CI.getOpcode()) {
8306 default:
8307 // All the others use floating point so we shouldn't actually
8308 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008309 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008310 case Instruction::Trunc:
8311 DoXForm = true;
8312 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008313 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008314 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008315 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008316 // If it's unnecessary to issue an AND to clear the high bits, it's
8317 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008318 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008319 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8320 if (MaskedValueIsZero(TryRes, Mask))
8321 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008322
8323 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008324 if (TryI->use_empty())
8325 EraseInstFromFunction(*TryI);
8326 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008327 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008328 }
Evan Chengf35fd542009-01-15 17:01:23 +00008329 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008330 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008331 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008332 // If we do not have to emit the truncate + sext pair, then it's always
8333 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008334 //
8335 // It's not safe to eliminate the trunc + sext pair if one of the
8336 // eliminated cast is a truncate. e.g.
8337 // t2 = trunc i32 t1 to i16
8338 // t3 = sext i16 t2 to i32
8339 // !=
8340 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008341 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008342 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8343 if (NumSignBits > (DestBitSize - SrcBitSize))
8344 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008345
8346 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008347 if (TryI->use_empty())
8348 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008349 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008350 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008351 }
Evan Chengf35fd542009-01-15 17:01:23 +00008352 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008353
8354 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008355 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8356 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008357 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8358 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008359 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008360 // Just replace this cast with the result.
8361 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008362
Reid Spencer3da59db2006-11-27 01:05:10 +00008363 assert(Res->getType() == DestTy);
8364 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008365 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008366 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008367 // Just replace this cast with the result.
8368 return ReplaceInstUsesWith(CI, Res);
8369 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008370 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008371
8372 // If the high bits are already zero, just replace this cast with the
8373 // result.
8374 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8375 if (MaskedValueIsZero(Res, Mask))
8376 return ReplaceInstUsesWith(CI, Res);
8377
8378 // We need to emit an AND to clear the high bits.
Owen Andersond672ecb2009-07-03 00:17:18 +00008379 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008380 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008381 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008383 case Instruction::SExt: {
8384 // If the high bits are already filled with sign bit, just replace this
8385 // cast with the result.
8386 unsigned NumSignBits = ComputeNumSignBits(Res);
8387 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008388 return ReplaceInstUsesWith(CI, Res);
8389
Reid Spencer3da59db2006-11-27 01:05:10 +00008390 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008391 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008392 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8393 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008394 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008395 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008396 }
8397 }
8398
8399 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8400 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8401
8402 switch (SrcI->getOpcode()) {
8403 case Instruction::Add:
8404 case Instruction::Mul:
8405 case Instruction::And:
8406 case Instruction::Or:
8407 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008408 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008409 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8410 // Don't insert two casts unless at least one can be eliminated.
8411 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008412 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008413 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8414 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008415 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008416 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008417 }
8418 }
8419
8420 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8421 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8422 SrcI->getOpcode() == Instruction::Xor &&
Owen Andersond672ecb2009-07-03 00:17:18 +00008423 Op1 == Context->getConstantIntTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008424 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008425 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008426 return BinaryOperator::CreateXor(New,
8427 Context->getConstantInt(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008428 }
8429 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008430
Eli Friedman65445c52009-07-13 21:45:57 +00008431 case Instruction::Shl: {
8432 // Canonicalize trunc inside shl, if we can.
8433 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8434 if (CI && DestBitSize < SrcBitSize &&
8435 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8436 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8437 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008438 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008439 }
8440 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008441 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008442 }
8443 return 0;
8444}
8445
Chris Lattner8a9f5712007-04-11 06:57:46 +00008446Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008447 if (Instruction *Result = commonIntCastTransforms(CI))
8448 return Result;
8449
8450 Value *Src = CI.getOperand(0);
8451 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008452 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8453 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008454
8455 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008456 if (DestBitWidth == 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008457 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008458 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008459 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson333c4002009-07-09 23:48:35 +00008460 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008461 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008462
Chris Lattner4f9797d2009-03-24 18:15:30 +00008463 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8464 ConstantInt *ShAmtV = 0;
8465 Value *ShiftOp = 0;
8466 if (Src->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008467 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008468 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8469
8470 // Get a mask for the bits shifting in.
8471 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8472 if (MaskedValueIsZero(ShiftOp, Mask)) {
8473 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersond672ecb2009-07-03 00:17:18 +00008474 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008475
8476 // Okay, we can shrink this. Truncate the input, then return a new
8477 // shift.
8478 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008479 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008480 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008481 }
8482 }
8483
8484 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008485}
8486
Evan Chengb98a10e2008-03-24 00:21:34 +00008487/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8488/// in order to eliminate the icmp.
8489Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8490 bool DoXform) {
8491 // If we are just checking for a icmp eq of a single bit and zext'ing it
8492 // to an integer, then shift the bit to the appropriate place and then
8493 // cast to integer to avoid the comparison.
8494 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8495 const APInt &Op1CV = Op1C->getValue();
8496
8497 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8498 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8499 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8500 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8501 if (!DoXform) return ICI;
8502
8503 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00008504 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008505 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008506 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008507 In->getName()+".lobit"),
8508 CI);
8509 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008510 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008511 false/*ZExt*/, "tmp", &CI);
8512
8513 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008514 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008515 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008516 In->getName()+".not"),
8517 CI);
8518 }
8519
8520 return ReplaceInstUsesWith(CI, In);
8521 }
8522
8523
8524
8525 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8526 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8527 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8528 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8529 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8530 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8531 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8532 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8533 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8534 // This only works for EQ and NE
8535 ICI->isEquality()) {
8536 // If Op1C some other power of two, convert:
8537 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8538 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8539 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8540 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8541
8542 APInt KnownZeroMask(~KnownZero);
8543 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8544 if (!DoXform) return ICI;
8545
8546 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8547 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8548 // (X&4) == 2 --> false
8549 // (X&4) != 2 --> true
Owen Andersond672ecb2009-07-03 00:17:18 +00008550 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8551 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008552 return ReplaceInstUsesWith(CI, Res);
8553 }
8554
8555 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8556 Value *In = ICI->getOperand(0);
8557 if (ShiftAmt) {
8558 // Perform a logical shr by shiftamt.
8559 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008560 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersond672ecb2009-07-03 00:17:18 +00008561 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008562 In->getName()+".lobit"), CI);
8563 }
8564
8565 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersond672ecb2009-07-03 00:17:18 +00008566 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008567 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008568 InsertNewInstBefore(cast<Instruction>(In), CI);
8569 }
8570
8571 if (CI.getType() == In->getType())
8572 return ReplaceInstUsesWith(CI, In);
8573 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008574 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008575 }
8576 }
8577 }
8578
8579 return 0;
8580}
8581
Chris Lattner8a9f5712007-04-11 06:57:46 +00008582Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008583 // If one of the common conversion will work ..
8584 if (Instruction *Result = commonIntCastTransforms(CI))
8585 return Result;
8586
8587 Value *Src = CI.getOperand(0);
8588
Chris Lattnera84f47c2009-02-17 20:47:23 +00008589 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8590 // types and if the sizes are just right we can convert this into a logical
8591 // 'and' which will be much cheaper than the pair of casts.
8592 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8593 // Get the sizes of the types involved. We know that the intermediate type
8594 // will be smaller than A or C, but don't know the relation between A and C.
8595 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008596 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8597 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8598 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008599 // If we're actually extending zero bits, then if
8600 // SrcSize < DstSize: zext(a & mask)
8601 // SrcSize == DstSize: a & mask
8602 // SrcSize > DstSize: trunc(a) & mask
8603 if (SrcSize < DstSize) {
8604 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008605 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008606 Instruction *And =
8607 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8608 InsertNewInstBefore(And, CI);
8609 return new ZExtInst(And, CI.getType());
8610 } else if (SrcSize == DstSize) {
8611 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008612 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008613 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008614 } else if (SrcSize > DstSize) {
8615 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8616 InsertNewInstBefore(Trunc, CI);
8617 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008618 return BinaryOperator::CreateAnd(Trunc,
8619 Context->getConstantInt(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008620 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008621 }
8622 }
8623
Evan Chengb98a10e2008-03-24 00:21:34 +00008624 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8625 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008626
Evan Chengb98a10e2008-03-24 00:21:34 +00008627 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8628 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8629 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8630 // of the (zext icmp) will be transformed.
8631 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8632 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8633 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8634 (transformZExtICmp(LHS, CI, false) ||
8635 transformZExtICmp(RHS, CI, false))) {
8636 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8637 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008638 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008639 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008640 }
8641
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008642 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008643 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8644 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8645 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8646 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008647 if (TI0->getType() == CI.getType())
8648 return
8649 BinaryOperator::CreateAnd(TI0,
Owen Andersond672ecb2009-07-03 00:17:18 +00008650 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008651 }
8652
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008653 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8654 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8655 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8656 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8657 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8658 And->getOperand(1) == C)
8659 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8660 Value *TI0 = TI->getOperand(0);
8661 if (TI0->getType() == CI.getType()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00008662 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008663 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8664 InsertNewInstBefore(NewAnd, *And);
8665 return BinaryOperator::CreateXor(NewAnd, ZC);
8666 }
8667 }
8668
Reid Spencer3da59db2006-11-27 01:05:10 +00008669 return 0;
8670}
8671
Chris Lattner8a9f5712007-04-11 06:57:46 +00008672Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008673 if (Instruction *I = commonIntCastTransforms(CI))
8674 return I;
8675
Chris Lattner8a9f5712007-04-11 06:57:46 +00008676 Value *Src = CI.getOperand(0);
8677
Dan Gohman1975d032008-10-30 20:40:10 +00008678 // Canonicalize sign-extend from i1 to a select.
8679 if (Src->getType() == Type::Int1Ty)
8680 return SelectInst::Create(Src,
Owen Anderson73c6b712009-07-13 20:58:05 +00008681 Context->getAllOnesValue(CI.getType()),
Owen Andersond672ecb2009-07-03 00:17:18 +00008682 Context->getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008683
8684 // See if the value being truncated is already sign extended. If so, just
8685 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008686 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008687 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008688 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8689 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8690 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008691 unsigned NumSignBits = ComputeNumSignBits(Op);
8692
8693 if (OpBits == DestBits) {
8694 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8695 // bits, it is already ready.
8696 if (NumSignBits > DestBits-MidBits)
8697 return ReplaceInstUsesWith(CI, Op);
8698 } else if (OpBits < DestBits) {
8699 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8700 // bits, just sext from i32.
8701 if (NumSignBits > OpBits-MidBits)
8702 return new SExtInst(Op, CI.getType(), "tmp");
8703 } else {
8704 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8705 // bits, just truncate to i32.
8706 if (NumSignBits > OpBits-MidBits)
8707 return new TruncInst(Op, CI.getType(), "tmp");
8708 }
8709 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008710
8711 // If the input is a shl/ashr pair of a same constant, then this is a sign
8712 // extension from a smaller value. If we could trust arbitrary bitwidth
8713 // integers, we could turn this into a truncate to the smaller bit and then
8714 // use a sext for the whole extension. Since we don't, look deeper and check
8715 // for a truncate. If the source and dest are the same type, eliminate the
8716 // trunc and extend and just do shifts. For example, turn:
8717 // %a = trunc i32 %i to i8
8718 // %b = shl i8 %a, 6
8719 // %c = ashr i8 %b, 6
8720 // %d = sext i8 %c to i32
8721 // into:
8722 // %a = shl i32 %i, 30
8723 // %d = ashr i32 %a, 30
8724 Value *A = 0;
8725 ConstantInt *BA = 0, *CA = 0;
8726 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008727 m_ConstantInt(CA)), *Context) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008728 BA == CA && isa<TruncInst>(A)) {
8729 Value *I = cast<TruncInst>(A)->getOperand(0);
8730 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008731 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8732 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008733 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersond672ecb2009-07-03 00:17:18 +00008734 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008735 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8736 CI.getName()), CI);
8737 return BinaryOperator::CreateAShr(I, ShAmtV);
8738 }
8739 }
8740
Chris Lattnerba417832007-04-11 06:12:58 +00008741 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008742}
8743
Chris Lattnerb7530652008-01-27 05:29:54 +00008744/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8745/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008746static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008747 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008748 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008749 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008750 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8751 if (!losesInfo)
Owen Andersond672ecb2009-07-03 00:17:18 +00008752 return Context->getConstantFP(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008753 return 0;
8754}
8755
8756/// LookThroughFPExtensions - If this is an fp extension instruction, look
8757/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008758static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008759 if (Instruction *I = dyn_cast<Instruction>(V))
8760 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008761 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008762
8763 // If this value is a constant, return the constant in the smallest FP type
8764 // that can accurately represent it. This allows us to turn
8765 // (float)((double)X+2.0) into x+2.0f.
8766 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8767 if (CFP->getType() == Type::PPC_FP128Ty)
8768 return V; // No constant folding of this.
8769 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008770 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008771 return V;
8772 if (CFP->getType() == Type::DoubleTy)
8773 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008774 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008775 return V;
8776 // Don't try to shrink to various long double types.
8777 }
8778
8779 return V;
8780}
8781
8782Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8783 if (Instruction *I = commonCastTransforms(CI))
8784 return I;
8785
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008786 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008787 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008788 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008789 // many builtins (sqrt, etc).
8790 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8791 if (OpI && OpI->hasOneUse()) {
8792 switch (OpI->getOpcode()) {
8793 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008794 case Instruction::FAdd:
8795 case Instruction::FSub:
8796 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008797 case Instruction::FDiv:
8798 case Instruction::FRem:
8799 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008800 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8801 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008802 if (LHSTrunc->getType() != SrcTy &&
8803 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008804 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008805 // If the source types were both smaller than the destination type of
8806 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008807 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8808 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008809 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8810 CI.getType(), CI);
8811 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8812 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008813 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008814 }
8815 }
8816 break;
8817 }
8818 }
8819 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008820}
8821
8822Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8823 return commonCastTransforms(CI);
8824}
8825
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008826Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008827 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8828 if (OpI == 0)
8829 return commonCastTransforms(FI);
8830
8831 // fptoui(uitofp(X)) --> X
8832 // fptoui(sitofp(X)) --> X
8833 // This is safe if the intermediate type has enough bits in its mantissa to
8834 // accurately represent all values of X. For example, do not do this with
8835 // i64->float->i64. This is also safe for sitofp case, because any negative
8836 // 'X' value would cause an undefined result for the fptoui.
8837 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8838 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008839 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008840 OpI->getType()->getFPMantissaWidth())
8841 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008842
8843 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008844}
8845
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008846Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008847 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8848 if (OpI == 0)
8849 return commonCastTransforms(FI);
8850
8851 // fptosi(sitofp(X)) --> X
8852 // fptosi(uitofp(X)) --> X
8853 // This is safe if the intermediate type has enough bits in its mantissa to
8854 // accurately represent all values of X. For example, do not do this with
8855 // i64->float->i64. This is also safe for sitofp case, because any negative
8856 // 'X' value would cause an undefined result for the fptoui.
8857 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8858 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008859 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008860 OpI->getType()->getFPMantissaWidth())
8861 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008862
8863 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008864}
8865
8866Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8867 return commonCastTransforms(CI);
8868}
8869
8870Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8871 return commonCastTransforms(CI);
8872}
8873
Chris Lattnera0e69692009-03-24 18:35:40 +00008874Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8875 // If the destination integer type is smaller than the intptr_t type for
8876 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8877 // trunc to be exposed to other transforms. Don't do this for extending
8878 // ptrtoint's, because we don't know if the target sign or zero extends its
8879 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008880 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008881 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8882 TD->getIntPtrType(),
8883 "tmp"), CI);
8884 return new TruncInst(P, CI.getType());
8885 }
8886
Chris Lattnerd3e28342007-04-27 17:44:50 +00008887 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008888}
8889
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008890Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008891 // If the source integer type is larger than the intptr_t type for
8892 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8893 // allows the trunc to be exposed to other transforms. Don't do this for
8894 // extending inttoptr's, because we don't know if the target sign or zero
8895 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008896 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008897 TD->getPointerSizeInBits()) {
8898 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8899 TD->getIntPtrType(),
8900 "tmp"), CI);
8901 return new IntToPtrInst(P, CI.getType());
8902 }
8903
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008904 if (Instruction *I = commonCastTransforms(CI))
8905 return I;
8906
8907 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8908 if (!DestPointee->isSized()) return 0;
8909
8910 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8911 ConstantInt *Cst;
8912 Value *X;
8913 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008914 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008915 // If the source and destination operands have the same type, see if this
8916 // is a single-index GEP.
8917 if (X->getType() == CI.getType()) {
8918 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008919 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008920
8921 // Convert the constant to intptr type.
8922 APInt Offset = Cst->getValue();
8923 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8924
8925 // If Offset is evenly divisible by Size, we can do this xform.
8926 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8927 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Dan Gohman3a7a68c2009-07-17 22:25:10 +00008928 GetElementPtrInst *GEP =
8929 GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8930 // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8931 // potentially overflow, in the absense of further analysis.
8932 cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8933 return GEP;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008934 }
8935 }
8936 // TODO: Could handle other cases, e.g. where add is indexing into field of
8937 // struct etc.
8938 } else if (CI.getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008939 match(CI.getOperand(0), m_Add(m_Value(X),
8940 m_ConstantInt(Cst)), *Context)) {
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008941 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8942 // "inttoptr+GEP" instead of "add+intptr".
8943
8944 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008945 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008946
8947 // Convert the constant to intptr type.
8948 APInt Offset = Cst->getValue();
8949 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8950
8951 // If Offset is evenly divisible by Size, we can do this xform.
8952 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8953 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8954
8955 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8956 "tmp"), CI);
Dan Gohman3a7a68c2009-07-17 22:25:10 +00008957 GetElementPtrInst *GEP =
8958 GetElementPtrInst::Create(P, Context->getConstantInt(Offset), "tmp");
8959 // A gep synthesized from inttoptr+add+ptrtoint must be assumed to
8960 // potentially overflow, in the absense of further analysis.
8961 cast<GEPOperator>(GEP)->setHasNoPointerOverflow(false);
8962 return GEP;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008963 }
8964 }
8965 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008966}
8967
Chris Lattnerd3e28342007-04-27 17:44:50 +00008968Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008969 // If the operands are integer typed then apply the integer transforms,
8970 // otherwise just apply the common ones.
8971 Value *Src = CI.getOperand(0);
8972 const Type *SrcTy = Src->getType();
8973 const Type *DestTy = CI.getType();
8974
Eli Friedman7e25d452009-07-13 20:53:00 +00008975 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008976 if (Instruction *I = commonPointerCastTransforms(CI))
8977 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008978 } else {
8979 if (Instruction *Result = commonCastTransforms(CI))
8980 return Result;
8981 }
8982
8983
8984 // Get rid of casts from one type to the same type. These are useless and can
8985 // be replaced by the operand.
8986 if (DestTy == Src->getType())
8987 return ReplaceInstUsesWith(CI, Src);
8988
Reid Spencer3da59db2006-11-27 01:05:10 +00008989 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008990 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8991 const Type *DstElTy = DstPTy->getElementType();
8992 const Type *SrcElTy = SrcPTy->getElementType();
8993
Nate Begeman83ad90a2008-03-31 00:22:16 +00008994 // If the address spaces don't match, don't eliminate the bitcast, which is
8995 // required for changing types.
8996 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8997 return 0;
8998
Chris Lattnerd3e28342007-04-27 17:44:50 +00008999 // If we are casting a malloc or alloca to a pointer to a type of the same
9000 // size, rewrite the allocation instruction to allocate the "right" type.
9001 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9002 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9003 return V;
9004
Chris Lattnerd717c182007-05-05 22:32:24 +00009005 // If the source and destination are pointers, and this cast is equivalent
9006 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009007 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Andersond672ecb2009-07-03 00:17:18 +00009008 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd3e28342007-04-27 17:44:50 +00009009 unsigned NumZeros = 0;
9010 while (SrcElTy != DstElTy &&
9011 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9012 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9013 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9014 ++NumZeros;
9015 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009016
Chris Lattnerd3e28342007-04-27 17:44:50 +00009017 // If we found a path from the src to dest, create the getelementptr now.
9018 if (SrcElTy == DstElTy) {
9019 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00009020 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9021 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009022 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009023 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009024
Reid Spencer3da59db2006-11-27 01:05:10 +00009025 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9026 if (SVI->hasOneUse()) {
9027 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9028 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009029 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009030 cast<VectorType>(DestTy)->getNumElements() ==
9031 SVI->getType()->getNumElements() &&
9032 SVI->getType()->getNumElements() ==
9033 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009034 CastInst *Tmp;
9035 // If either of the operands is a cast from CI.getType(), then
9036 // evaluating the shuffle in the casted destination's type will allow
9037 // us to eliminate at least one cast.
9038 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9039 Tmp->getOperand(0)->getType() == DestTy) ||
9040 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9041 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009042 Value *LHS = InsertCastBefore(Instruction::BitCast,
9043 SVI->getOperand(0), DestTy, CI);
9044 Value *RHS = InsertCastBefore(Instruction::BitCast,
9045 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009046 // Return a new shuffle vector. Use the same element ID's, as we
9047 // know the vector types match #elts.
9048 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009049 }
9050 }
9051 }
9052 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009053 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009054}
9055
Chris Lattnere576b912004-04-09 23:46:01 +00009056/// GetSelectFoldableOperands - We want to turn code that looks like this:
9057/// %C = or %A, %B
9058/// %D = select %cond, %C, %A
9059/// into:
9060/// %C = select %cond, %B, 0
9061/// %D = or %A, %C
9062///
9063/// Assuming that the specified instruction is an operand to the select, return
9064/// a bitmask indicating which operands of this instruction are foldable if they
9065/// equal the other incoming value of the select.
9066///
9067static unsigned GetSelectFoldableOperands(Instruction *I) {
9068 switch (I->getOpcode()) {
9069 case Instruction::Add:
9070 case Instruction::Mul:
9071 case Instruction::And:
9072 case Instruction::Or:
9073 case Instruction::Xor:
9074 return 3; // Can fold through either operand.
9075 case Instruction::Sub: // Can only fold on the amount subtracted.
9076 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009077 case Instruction::LShr:
9078 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009079 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009080 default:
9081 return 0; // Cannot fold
9082 }
9083}
9084
9085/// GetSelectFoldableConstant - For the same transformation as the previous
9086/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009087static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009088 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009089 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009090 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009091 case Instruction::Add:
9092 case Instruction::Sub:
9093 case Instruction::Or:
9094 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009095 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009096 case Instruction::LShr:
9097 case Instruction::AShr:
Owen Andersond672ecb2009-07-03 00:17:18 +00009098 return Context->getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009099 case Instruction::And:
Owen Andersond672ecb2009-07-03 00:17:18 +00009100 return Context->getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009101 case Instruction::Mul:
Owen Andersond672ecb2009-07-03 00:17:18 +00009102 return Context->getConstantInt(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009103 }
9104}
9105
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009106/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9107/// have the same opcode and only one use each. Try to simplify this.
9108Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9109 Instruction *FI) {
9110 if (TI->getNumOperands() == 1) {
9111 // If this is a non-volatile load or a cast from the same type,
9112 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009113 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009114 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9115 return 0;
9116 } else {
9117 return 0; // unknown unary op.
9118 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009119
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009120 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009121 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9122 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009123 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009124 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009125 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009126 }
9127
Reid Spencer832254e2007-02-02 02:16:23 +00009128 // Only handle binary operators here.
9129 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009130 return 0;
9131
9132 // Figure out if the operations have any operands in common.
9133 Value *MatchOp, *OtherOpT, *OtherOpF;
9134 bool MatchIsOpZero;
9135 if (TI->getOperand(0) == FI->getOperand(0)) {
9136 MatchOp = TI->getOperand(0);
9137 OtherOpT = TI->getOperand(1);
9138 OtherOpF = FI->getOperand(1);
9139 MatchIsOpZero = true;
9140 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9141 MatchOp = TI->getOperand(1);
9142 OtherOpT = TI->getOperand(0);
9143 OtherOpF = FI->getOperand(0);
9144 MatchIsOpZero = false;
9145 } else if (!TI->isCommutative()) {
9146 return 0;
9147 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9148 MatchOp = TI->getOperand(0);
9149 OtherOpT = TI->getOperand(1);
9150 OtherOpF = FI->getOperand(0);
9151 MatchIsOpZero = true;
9152 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9153 MatchOp = TI->getOperand(1);
9154 OtherOpT = TI->getOperand(0);
9155 OtherOpF = FI->getOperand(1);
9156 MatchIsOpZero = true;
9157 } else {
9158 return 0;
9159 }
9160
9161 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009162 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9163 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009164 InsertNewInstBefore(NewSI, SI);
9165
9166 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9167 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009168 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009169 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009170 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009171 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009172 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009173 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009174}
9175
Evan Chengde621922009-03-31 20:42:45 +00009176static bool isSelect01(Constant *C1, Constant *C2) {
9177 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9178 if (!C1I)
9179 return false;
9180 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9181 if (!C2I)
9182 return false;
9183 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9184}
9185
9186/// FoldSelectIntoOp - Try fold the select into one of the operands to
9187/// facilitate further optimization.
9188Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9189 Value *FalseVal) {
9190 // See the comment above GetSelectFoldableOperands for a description of the
9191 // transformation we are doing here.
9192 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9193 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9194 !isa<Constant>(FalseVal)) {
9195 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9196 unsigned OpToFold = 0;
9197 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9198 OpToFold = 1;
9199 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9200 OpToFold = 2;
9201 }
9202
9203 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009204 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009205 Value *OOp = TVI->getOperand(2-OpToFold);
9206 // Avoid creating select between 2 constants unless it's selecting
9207 // between 0 and 1.
9208 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9209 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9210 InsertNewInstBefore(NewSel, SI);
9211 NewSel->takeName(TVI);
9212 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9213 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009214 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009215 }
9216 }
9217 }
9218 }
9219 }
9220
9221 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9222 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9223 !isa<Constant>(TrueVal)) {
9224 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9225 unsigned OpToFold = 0;
9226 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9227 OpToFold = 1;
9228 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9229 OpToFold = 2;
9230 }
9231
9232 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009233 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009234 Value *OOp = FVI->getOperand(2-OpToFold);
9235 // Avoid creating select between 2 constants unless it's selecting
9236 // between 0 and 1.
9237 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9238 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9239 InsertNewInstBefore(NewSel, SI);
9240 NewSel->takeName(FVI);
9241 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9242 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009243 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009244 }
9245 }
9246 }
9247 }
9248 }
9249
9250 return 0;
9251}
9252
Dan Gohman81b28ce2008-09-16 18:46:06 +00009253/// visitSelectInstWithICmp - Visit a SelectInst that has an
9254/// ICmpInst as its first operand.
9255///
9256Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9257 ICmpInst *ICI) {
9258 bool Changed = false;
9259 ICmpInst::Predicate Pred = ICI->getPredicate();
9260 Value *CmpLHS = ICI->getOperand(0);
9261 Value *CmpRHS = ICI->getOperand(1);
9262 Value *TrueVal = SI.getTrueValue();
9263 Value *FalseVal = SI.getFalseValue();
9264
9265 // Check cases where the comparison is with a constant that
9266 // can be adjusted to fit the min/max idiom. We may edit ICI in
9267 // place here, so make sure the select is the only user.
9268 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009269 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009270 switch (Pred) {
9271 default: break;
9272 case ICmpInst::ICMP_ULT:
9273 case ICmpInst::ICMP_SLT: {
9274 // X < MIN ? T : F --> F
9275 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9276 return ReplaceInstUsesWith(SI, FalseVal);
9277 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009278 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009279 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9280 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9281 Pred = ICmpInst::getSwappedPredicate(Pred);
9282 CmpRHS = AdjustedRHS;
9283 std::swap(FalseVal, TrueVal);
9284 ICI->setPredicate(Pred);
9285 ICI->setOperand(1, CmpRHS);
9286 SI.setOperand(1, TrueVal);
9287 SI.setOperand(2, FalseVal);
9288 Changed = true;
9289 }
9290 break;
9291 }
9292 case ICmpInst::ICMP_UGT:
9293 case ICmpInst::ICMP_SGT: {
9294 // X > MAX ? T : F --> F
9295 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9296 return ReplaceInstUsesWith(SI, FalseVal);
9297 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Andersond672ecb2009-07-03 00:17:18 +00009298 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009299 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9300 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9301 Pred = ICmpInst::getSwappedPredicate(Pred);
9302 CmpRHS = AdjustedRHS;
9303 std::swap(FalseVal, TrueVal);
9304 ICI->setPredicate(Pred);
9305 ICI->setOperand(1, CmpRHS);
9306 SI.setOperand(1, TrueVal);
9307 SI.setOperand(2, FalseVal);
9308 Changed = true;
9309 }
9310 break;
9311 }
9312 }
9313
Dan Gohman1975d032008-10-30 20:40:10 +00009314 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9315 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009316 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009317 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9318 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009319 Pred = ICI->getPredicate();
Owen Andersonc7d2ce72009-07-10 17:35:01 +00009320 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9321 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattnercb504b92008-11-16 05:38:51 +00009322 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9323
Dan Gohman1975d032008-10-30 20:40:10 +00009324 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9325 // If we are just checking for a icmp eq of a single bit and zext'ing it
9326 // to an integer, then shift the bit to the appropriate place and then
9327 // cast to integer to avoid the comparison.
9328 const APInt &Op1CV = CI->getValue();
9329
9330 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9331 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9332 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009333 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009334 Value *In = ICI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +00009335 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009336 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009337 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9338 In->getName()+".lobit"),
9339 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009340 if (In->getType() != SI.getType())
9341 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009342 true/*SExt*/, "tmp", ICI);
9343
9344 if (Pred == ICmpInst::ICMP_SGT)
Owen Anderson73c6b712009-07-13 20:58:05 +00009345 In = InsertNewInstBefore(BinaryOperator::CreateNot(*Context, In,
Dan Gohman1975d032008-10-30 20:40:10 +00009346 In->getName()+".not"), *ICI);
9347
9348 return ReplaceInstUsesWith(SI, In);
9349 }
9350 }
9351 }
9352
Dan Gohman81b28ce2008-09-16 18:46:06 +00009353 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9354 // Transform (X == Y) ? X : Y -> Y
9355 if (Pred == ICmpInst::ICMP_EQ)
9356 return ReplaceInstUsesWith(SI, FalseVal);
9357 // Transform (X != Y) ? X : Y -> X
9358 if (Pred == ICmpInst::ICMP_NE)
9359 return ReplaceInstUsesWith(SI, TrueVal);
9360 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9361
9362 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9363 // Transform (X == Y) ? Y : X -> X
9364 if (Pred == ICmpInst::ICMP_EQ)
9365 return ReplaceInstUsesWith(SI, FalseVal);
9366 // Transform (X != Y) ? Y : X -> Y
9367 if (Pred == ICmpInst::ICMP_NE)
9368 return ReplaceInstUsesWith(SI, TrueVal);
9369 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9370 }
9371
9372 /// NOTE: if we wanted to, this is where to detect integer ABS
9373
9374 return Changed ? &SI : 0;
9375}
9376
Chris Lattner3d69f462004-03-12 05:52:32 +00009377Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009378 Value *CondVal = SI.getCondition();
9379 Value *TrueVal = SI.getTrueValue();
9380 Value *FalseVal = SI.getFalseValue();
9381
9382 // select true, X, Y -> X
9383 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009384 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009385 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009386
9387 // select C, X, X -> X
9388 if (TrueVal == FalseVal)
9389 return ReplaceInstUsesWith(SI, TrueVal);
9390
Chris Lattnere87597f2004-10-16 18:11:37 +00009391 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9392 return ReplaceInstUsesWith(SI, FalseVal);
9393 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9394 return ReplaceInstUsesWith(SI, TrueVal);
9395 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9396 if (isa<Constant>(TrueVal))
9397 return ReplaceInstUsesWith(SI, TrueVal);
9398 else
9399 return ReplaceInstUsesWith(SI, FalseVal);
9400 }
9401
Reid Spencer4fe16d62007-01-11 18:21:29 +00009402 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009403 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009404 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009405 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009406 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009407 } else {
9408 // Change: A = select B, false, C --> A = and !B, C
9409 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009410 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009411 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009412 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009413 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009414 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009415 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009416 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009417 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009418 } else {
9419 // Change: A = select B, C, true --> A = or !B, C
9420 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009421 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009422 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009423 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009424 }
9425 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009426
9427 // select a, b, a -> a&b
9428 // select a, a, b -> a|b
9429 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009430 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009431 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009432 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009433 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009434
Chris Lattner2eefe512004-04-09 19:05:30 +00009435 // Selecting between two integer constants?
9436 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9437 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009438 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009439 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009440 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009441 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009442 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009443 Value *NotCond =
Owen Anderson73c6b712009-07-13 20:58:05 +00009444 InsertNewInstBefore(BinaryOperator::CreateNot(*Context, CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009445 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009446 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009447 }
Chris Lattner457dd822004-06-09 07:59:58 +00009448
Reid Spencere4d87aa2006-12-23 06:05:41 +00009449 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009450 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009451 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009452 // non-constant value, eliminate this whole mess. This corresponds to
9453 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009454 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009455 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009456 cast<Constant>(IC->getOperand(1))->isNullValue())
9457 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9458 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009459 isa<ConstantInt>(ICA->getOperand(1)) &&
9460 (ICA->getOperand(1) == TrueValC ||
9461 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009462 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9463 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009464 // know whether we have a icmp_ne or icmp_eq and whether the
9465 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009466 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009467 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009468 Value *V = ICA;
9469 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009470 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009471 Instruction::Xor, V, ICA->getOperand(1)), SI);
9472 return ReplaceInstUsesWith(SI, V);
9473 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009474 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009475 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009476
9477 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009478 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9479 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009480 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009481 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9482 // This is not safe in general for floating point:
9483 // consider X== -0, Y== +0.
9484 // It becomes safe if either operand is a nonzero constant.
9485 ConstantFP *CFPt, *CFPf;
9486 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9487 !CFPt->getValueAPF().isZero()) ||
9488 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9489 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009490 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009491 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009492 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009493 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009494 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009495 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009496
Reid Spencere4d87aa2006-12-23 06:05:41 +00009497 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009498 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009499 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9500 // This is not safe in general for floating point:
9501 // consider X== -0, Y== +0.
9502 // It becomes safe if either operand is a nonzero constant.
9503 ConstantFP *CFPt, *CFPf;
9504 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9505 !CFPt->getValueAPF().isZero()) ||
9506 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9507 !CFPf->getValueAPF().isZero()))
9508 return ReplaceInstUsesWith(SI, FalseVal);
9509 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009510 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009511 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9512 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009513 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009514 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009515 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009516 }
9517
9518 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009519 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9520 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9521 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009522
Chris Lattner87875da2005-01-13 22:52:24 +00009523 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9524 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9525 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009526 Instruction *AddOp = 0, *SubOp = 0;
9527
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009528 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9529 if (TI->getOpcode() == FI->getOpcode())
9530 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9531 return IV;
9532
9533 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9534 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009535 if ((TI->getOpcode() == Instruction::Sub &&
9536 FI->getOpcode() == Instruction::Add) ||
9537 (TI->getOpcode() == Instruction::FSub &&
9538 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009539 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009540 } else if ((FI->getOpcode() == Instruction::Sub &&
9541 TI->getOpcode() == Instruction::Add) ||
9542 (FI->getOpcode() == Instruction::FSub &&
9543 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009544 AddOp = TI; SubOp = FI;
9545 }
9546
9547 if (AddOp) {
9548 Value *OtherAddOp = 0;
9549 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9550 OtherAddOp = AddOp->getOperand(1);
9551 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9552 OtherAddOp = AddOp->getOperand(0);
9553 }
9554
9555 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009556 // So at this point we know we have (Y -> OtherAddOp):
9557 // select C, (add X, Y), (sub X, Z)
9558 Value *NegVal; // Compute -Z
9559 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009560 NegVal = Context->getConstantExprNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009561 } else {
9562 NegVal = InsertNewInstBefore(
Owen Anderson0a5372e2009-07-13 04:09:18 +00009563 BinaryOperator::CreateNeg(*Context, SubOp->getOperand(1),
9564 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009565 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009566
9567 Value *NewTrueOp = OtherAddOp;
9568 Value *NewFalseOp = NegVal;
9569 if (AddOp != TI)
9570 std::swap(NewTrueOp, NewFalseOp);
9571 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009572 SelectInst::Create(CondVal, NewTrueOp,
9573 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009574
9575 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009576 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009577 }
9578 }
9579 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009580
Chris Lattnere576b912004-04-09 23:46:01 +00009581 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009582 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009583 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9584 if (FoldI)
9585 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009586 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009587
9588 if (BinaryOperator::isNot(CondVal)) {
9589 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9590 SI.setOperand(1, FalseVal);
9591 SI.setOperand(2, TrueVal);
9592 return &SI;
9593 }
9594
Chris Lattner3d69f462004-03-12 05:52:32 +00009595 return 0;
9596}
9597
Dan Gohmaneee962e2008-04-10 18:43:06 +00009598/// EnforceKnownAlignment - If the specified pointer points to an object that
9599/// we control, modify the object's alignment to PrefAlign. This isn't
9600/// often possible though. If alignment is important, a more reliable approach
9601/// is to simply align all global variables and allocation instructions to
9602/// their preferred alignment from the beginning.
9603///
9604static unsigned EnforceKnownAlignment(Value *V,
9605 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009606
Dan Gohmaneee962e2008-04-10 18:43:06 +00009607 User *U = dyn_cast<User>(V);
9608 if (!U) return Align;
9609
Dan Gohmanca178902009-07-17 20:47:02 +00009610 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009611 default: break;
9612 case Instruction::BitCast:
9613 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9614 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009615 // If all indexes are zero, it is just the alignment of the base pointer.
9616 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009617 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009618 if (!isa<Constant>(*i) ||
9619 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009620 AllZeroOperands = false;
9621 break;
9622 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009623
9624 if (AllZeroOperands) {
9625 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009626 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009627 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009628 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009629 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009630 }
9631
9632 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9633 // If there is a large requested alignment and we can, bump up the alignment
9634 // of the global.
9635 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009636 if (GV->getAlignment() >= PrefAlign)
9637 Align = GV->getAlignment();
9638 else {
9639 GV->setAlignment(PrefAlign);
9640 Align = PrefAlign;
9641 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009642 }
9643 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9644 // If there is a requested alignment and if this is an alloca, round up. We
9645 // don't do this for malloc, because some systems can't respect the request.
9646 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009647 if (AI->getAlignment() >= PrefAlign)
9648 Align = AI->getAlignment();
9649 else {
9650 AI->setAlignment(PrefAlign);
9651 Align = PrefAlign;
9652 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009653 }
9654 }
9655
9656 return Align;
9657}
9658
9659/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9660/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9661/// and it is more than the alignment of the ultimate object, see if we can
9662/// increase the alignment of the ultimate object, making this check succeed.
9663unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9664 unsigned PrefAlign) {
9665 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9666 sizeof(PrefAlign) * CHAR_BIT;
9667 APInt Mask = APInt::getAllOnesValue(BitWidth);
9668 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9669 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9670 unsigned TrailZ = KnownZero.countTrailingOnes();
9671 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9672
9673 if (PrefAlign > Align)
9674 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9675
9676 // We don't need to make any adjustment.
9677 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009678}
9679
Chris Lattnerf497b022008-01-13 23:50:23 +00009680Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009681 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009682 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009683 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009684 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009685
9686 if (CopyAlign < MinAlign) {
Owen Andersona547b472009-07-09 18:36:20 +00009687 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9688 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009689 return MI;
9690 }
9691
9692 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9693 // load/store.
9694 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9695 if (MemOpLength == 0) return 0;
9696
Chris Lattner37ac6082008-01-14 00:28:35 +00009697 // Source and destination pointer types are always "i8*" for intrinsic. See
9698 // if the size is something we can handle with a single primitive load/store.
9699 // A single load+store correctly handles overlapping memory in the memmove
9700 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009701 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009702 if (Size == 0) return MI; // Delete this mem transfer.
9703
9704 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009705 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009706
Chris Lattner37ac6082008-01-14 00:28:35 +00009707 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009708 Type *NewPtrTy =
9709 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009710
9711 // Memcpy forces the use of i8* for the source and destination. That means
9712 // that if you're using memcpy to move one double around, you'll get a cast
9713 // from double* to i8*. We'd much rather use a double load+store rather than
9714 // an i64 load+store, here because this improves the odds that the source or
9715 // dest address will be promotable. See if we can find a better type than the
9716 // integer datatype.
9717 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9718 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9719 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9720 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9721 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009722 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009723 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9724 if (STy->getNumElements() == 1)
9725 SrcETy = STy->getElementType(0);
9726 else
9727 break;
9728 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9729 if (ATy->getNumElements() == 1)
9730 SrcETy = ATy->getElementType();
9731 else
9732 break;
9733 } else
9734 break;
9735 }
9736
Dan Gohman8f8e2692008-05-23 01:52:21 +00009737 if (SrcETy->isSingleValueType())
Owen Andersond672ecb2009-07-03 00:17:18 +00009738 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009739 }
9740 }
9741
9742
Chris Lattnerf497b022008-01-13 23:50:23 +00009743 // If the memcpy/memmove provides better alignment info than we can
9744 // infer, use it.
9745 SrcAlign = std::max(SrcAlign, CopyAlign);
9746 DstAlign = std::max(DstAlign, CopyAlign);
9747
9748 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9749 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009750 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9751 InsertNewInstBefore(L, *MI);
9752 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9753
9754 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009755 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009756 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009757}
Chris Lattner3d69f462004-03-12 05:52:32 +00009758
Chris Lattner69ea9d22008-04-30 06:39:11 +00009759Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9760 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009761 if (MI->getAlignment() < Alignment) {
Owen Andersona547b472009-07-09 18:36:20 +00009762 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9763 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009764 return MI;
9765 }
9766
9767 // Extract the length and alignment and fill if they are constant.
9768 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9769 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9770 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9771 return 0;
9772 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009773 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009774
9775 // If the length is zero, this is a no-op
9776 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9777
9778 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9779 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009780 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009781
9782 Value *Dest = MI->getDest();
Owen Andersond672ecb2009-07-03 00:17:18 +00009783 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009784
9785 // Alignment 0 is identity for alignment 1 for memset, but not store.
9786 if (Alignment == 0) Alignment = 1;
9787
9788 // Extract the fill value and store.
9789 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersond672ecb2009-07-03 00:17:18 +00009790 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9791 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009792
9793 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersond672ecb2009-07-03 00:17:18 +00009794 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009795 return MI;
9796 }
9797
9798 return 0;
9799}
9800
9801
Chris Lattner8b0ea312006-01-13 20:11:04 +00009802/// visitCallInst - CallInst simplification. This mostly only handles folding
9803/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9804/// the heavy lifting.
9805///
Chris Lattner9fe38862003-06-19 17:00:31 +00009806Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009807 // If the caller function is nounwind, mark the call as nounwind, even if the
9808 // callee isn't.
9809 if (CI.getParent()->getParent()->doesNotThrow() &&
9810 !CI.doesNotThrow()) {
9811 CI.setDoesNotThrow();
9812 return &CI;
9813 }
9814
9815
9816
Chris Lattner8b0ea312006-01-13 20:11:04 +00009817 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9818 if (!II) return visitCallSite(&CI);
9819
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009820 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9821 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009822 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009823 bool Changed = false;
9824
9825 // memmove/cpy/set of zero bytes is a noop.
9826 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9827 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9828
Chris Lattner35b9e482004-10-12 04:52:52 +00009829 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009830 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009831 // Replace the instruction with just byte operations. We would
9832 // transform other cases to loads/stores, but we don't know if
9833 // alignment is sufficient.
9834 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009835 }
9836
Chris Lattner35b9e482004-10-12 04:52:52 +00009837 // If we have a memmove and the source operation is a constant global,
9838 // then the source and dest pointers can't alias, so we can change this
9839 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009840 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009841 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9842 if (GVSrc->isConstant()) {
9843 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009844 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9845 const Type *Tys[1];
9846 Tys[0] = CI.getOperand(3)->getType();
9847 CI.setOperand(0,
9848 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009849 Changed = true;
9850 }
Chris Lattnera935db82008-05-28 05:30:41 +00009851
9852 // memmove(x,x,size) -> noop.
9853 if (MMI->getSource() == MMI->getDest())
9854 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009855 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009856
Chris Lattner95a959d2006-03-06 20:18:44 +00009857 // If we can determine a pointer alignment that is bigger than currently
9858 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009859 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009860 if (Instruction *I = SimplifyMemTransfer(MI))
9861 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009862 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9863 if (Instruction *I = SimplifyMemSet(MSI))
9864 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009865 }
9866
Chris Lattner8b0ea312006-01-13 20:11:04 +00009867 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009868 }
9869
9870 switch (II->getIntrinsicID()) {
9871 default: break;
9872 case Intrinsic::bswap:
9873 // bswap(bswap(x)) -> x
9874 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9875 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9876 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9877 break;
9878 case Intrinsic::ppc_altivec_lvx:
9879 case Intrinsic::ppc_altivec_lvxl:
9880 case Intrinsic::x86_sse_loadu_ps:
9881 case Intrinsic::x86_sse2_loadu_pd:
9882 case Intrinsic::x86_sse2_loadu_dq:
9883 // Turn PPC lvx -> load if the pointer is known aligned.
9884 // Turn X86 loadups -> load if the pointer is known aligned.
9885 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9886 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +00009887 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009888 CI);
9889 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009890 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009891 break;
9892 case Intrinsic::ppc_altivec_stvx:
9893 case Intrinsic::ppc_altivec_stvxl:
9894 // Turn stvx -> store if the pointer is known aligned.
9895 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9896 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009897 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009898 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9899 return new StoreInst(II->getOperand(1), Ptr);
9900 }
9901 break;
9902 case Intrinsic::x86_sse_storeu_ps:
9903 case Intrinsic::x86_sse2_storeu_pd:
9904 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009905 // Turn X86 storeu -> store if the pointer is known aligned.
9906 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9907 const Type *OpPtrTy =
Owen Andersond672ecb2009-07-03 00:17:18 +00009908 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009909 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9910 return new StoreInst(II->getOperand(2), Ptr);
9911 }
9912 break;
9913
9914 case Intrinsic::x86_sse_cvttss2si: {
9915 // These intrinsics only demands the 0th element of its input vector. If
9916 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009917 unsigned VWidth =
9918 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9919 APInt DemandedElts(VWidth, 1);
9920 APInt UndefElts(VWidth, 0);
9921 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009922 UndefElts)) {
9923 II->setOperand(1, V);
9924 return II;
9925 }
9926 break;
9927 }
9928
9929 case Intrinsic::ppc_altivec_vperm:
9930 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9931 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9932 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009933
Chris Lattner0521e3c2008-06-18 04:33:20 +00009934 // Check that all of the elements are integer constants or undefs.
9935 bool AllEltsOk = true;
9936 for (unsigned i = 0; i != 16; ++i) {
9937 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9938 !isa<UndefValue>(Mask->getOperand(i))) {
9939 AllEltsOk = false;
9940 break;
9941 }
9942 }
9943
9944 if (AllEltsOk) {
9945 // Cast the input vectors to byte vectors.
9946 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9947 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00009948 Value *Result = Context->getUndef(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009949
Chris Lattner0521e3c2008-06-18 04:33:20 +00009950 // Only extract each element once.
9951 Value *ExtractedElts[32];
9952 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9953
Chris Lattnere2ed0572006-04-06 19:19:17 +00009954 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009955 if (isa<UndefValue>(Mask->getOperand(i)))
9956 continue;
9957 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9958 Idx &= 31; // Match the hardware behavior.
9959
9960 if (ExtractedElts[Idx] == 0) {
9961 Instruction *Elt =
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009962 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
9963 Context->getConstantInt(Type::Int32Ty, Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009964 InsertNewInstBefore(Elt, CI);
9965 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009966 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009967
Chris Lattner0521e3c2008-06-18 04:33:20 +00009968 // Insert this value into the result vector.
9969 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009970 Context->getConstantInt(Type::Int32Ty, i, false),
9971 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009972 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009973 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009974 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009975 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009976 }
9977 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009978
Chris Lattner0521e3c2008-06-18 04:33:20 +00009979 case Intrinsic::stackrestore: {
9980 // If the save is right next to the restore, remove the restore. This can
9981 // happen when variable allocas are DCE'd.
9982 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9983 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9984 BasicBlock::iterator BI = SS;
9985 if (&*++BI == II)
9986 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009987 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009988 }
9989
9990 // Scan down this block to see if there is another stack restore in the
9991 // same block without an intervening call/alloca.
9992 BasicBlock::iterator BI = II;
9993 TerminatorInst *TI = II->getParent()->getTerminator();
9994 bool CannotRemove = false;
9995 for (++BI; &*BI != TI; ++BI) {
9996 if (isa<AllocaInst>(BI)) {
9997 CannotRemove = true;
9998 break;
9999 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010000 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10001 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10002 // If there is a stackrestore below this one, remove this one.
10003 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10004 return EraseInstFromFunction(CI);
10005 // Otherwise, ignore the intrinsic.
10006 } else {
10007 // If we found a non-intrinsic call, we can't remove the stack
10008 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010009 CannotRemove = true;
10010 break;
10011 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010012 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010013 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010014
10015 // If the stack restore is in a return/unwind block and if there are no
10016 // allocas or calls between the restore and the return, nuke the restore.
10017 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10018 return EraseInstFromFunction(CI);
10019 break;
10020 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010021 }
10022
Chris Lattner8b0ea312006-01-13 20:11:04 +000010023 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010024}
10025
10026// InvokeInst simplification
10027//
10028Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010029 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010030}
10031
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010032/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10033/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010034static bool isSafeToEliminateVarargsCast(const CallSite CS,
10035 const CastInst * const CI,
10036 const TargetData * const TD,
10037 const int ix) {
10038 if (!CI->isLosslessCast())
10039 return false;
10040
10041 // The size of ByVal arguments is derived from the type, so we
10042 // can't change to a type with a different size. If the size were
10043 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010044 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010045 return true;
10046
10047 const Type* SrcTy =
10048 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10049 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10050 if (!SrcTy->isSized() || !DstTy->isSized())
10051 return false;
Duncan Sands777d2302009-05-09 07:06:46 +000010052 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010053 return false;
10054 return true;
10055}
10056
Chris Lattnera44d8a22003-10-07 22:32:43 +000010057// visitCallSite - Improvements for call and invoke instructions.
10058//
10059Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010060 bool Changed = false;
10061
10062 // If the callee is a constexpr cast of a function, attempt to move the cast
10063 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010064 if (transformConstExprCastCall(CS)) return 0;
10065
Chris Lattner6c266db2003-10-07 22:54:13 +000010066 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010067
Chris Lattner08b22ec2005-05-13 07:09:09 +000010068 if (Function *CalleeF = dyn_cast<Function>(Callee))
10069 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10070 Instruction *OldCall = CS.getInstruction();
10071 // If the call and callee calling conventions don't match, this call must
10072 // be unreachable, as the call is undefined.
Owen Andersond672ecb2009-07-03 00:17:18 +000010073 new StoreInst(Context->getConstantIntTrue(),
10074 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10075 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +000010076 if (!OldCall->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000010077 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010078 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10079 return EraseInstFromFunction(*OldCall);
10080 return 0;
10081 }
10082
Chris Lattner17be6352004-10-18 02:59:09 +000010083 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10084 // This instruction is not reachable, just remove it. We insert a store to
10085 // undef so that we know that this code is not reachable, despite the fact
10086 // that we can't modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000010087 new StoreInst(Context->getConstantIntTrue(),
10088 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010089 CS.getInstruction());
10090
10091 if (!CS.getInstruction()->use_empty())
10092 CS.getInstruction()->
Owen Andersond672ecb2009-07-03 00:17:18 +000010093 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010094
10095 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10096 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010097 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Andersond672ecb2009-07-03 00:17:18 +000010098 Context->getConstantIntTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010099 }
Chris Lattner17be6352004-10-18 02:59:09 +000010100 return EraseInstFromFunction(*CS.getInstruction());
10101 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010102
Duncan Sandscdb6d922007-09-17 10:26:40 +000010103 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10104 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10105 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10106 return transformCallThroughTrampoline(CS);
10107
Chris Lattner6c266db2003-10-07 22:54:13 +000010108 const PointerType *PTy = cast<PointerType>(Callee->getType());
10109 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10110 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010111 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010112 // See if we can optimize any arguments passed through the varargs area of
10113 // the call.
10114 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010115 E = CS.arg_end(); I != E; ++I, ++ix) {
10116 CastInst *CI = dyn_cast<CastInst>(*I);
10117 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10118 *I = CI->getOperand(0);
10119 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010120 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010121 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010122 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010123
Duncan Sandsf0c33542007-12-19 21:13:37 +000010124 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010125 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010126 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010127 Changed = true;
10128 }
10129
Chris Lattner6c266db2003-10-07 22:54:13 +000010130 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010131}
10132
Chris Lattner9fe38862003-06-19 17:00:31 +000010133// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10134// attempt to move the cast to the arguments of the call/invoke.
10135//
10136bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10137 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10138 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010139 if (CE->getOpcode() != Instruction::BitCast ||
10140 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010141 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010142 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010143 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010144 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010145
10146 // Okay, this is a cast from a function to a different type. Unless doing so
10147 // would cause a type conversion of one of our arguments, change this call to
10148 // be a direct call with arguments casted to the appropriate types.
10149 //
10150 const FunctionType *FT = Callee->getFunctionType();
10151 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010152 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010153
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010154 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010155 return false; // TODO: Handle multiple return values.
10156
Chris Lattnerf78616b2004-01-14 06:06:08 +000010157 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010158 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010159 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010160 // Conversion is ok if changing from one pointer type to another or from
10161 // a pointer to an integer of the same size.
10162 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010163 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010164 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010165
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010166 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010167 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010168 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010169 return false; // Cannot transform this return value.
10170
Chris Lattner58d74912008-03-12 17:45:29 +000010171 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010172 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010173 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010174 return false; // Attribute not compatible with transformed value.
10175 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010176
Chris Lattnerf78616b2004-01-14 06:06:08 +000010177 // If the callsite is an invoke instruction, and the return value is used by
10178 // a PHI node in a successor, we cannot change the return type of the call
10179 // because there is no place to put the cast instruction (without breaking
10180 // the critical edge). Bail out in this case.
10181 if (!Caller->use_empty())
10182 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10183 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10184 UI != E; ++UI)
10185 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10186 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010187 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010188 return false;
10189 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010190
10191 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10192 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010193
Chris Lattner9fe38862003-06-19 17:00:31 +000010194 CallSite::arg_iterator AI = CS.arg_begin();
10195 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10196 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010197 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010198
10199 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010200 return false; // Cannot transform this parameter value.
10201
Devang Patel19c87462008-09-26 22:53:05 +000010202 if (CallerPAL.getParamAttributes(i + 1)
10203 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010204 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010205
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010206 // Converting from one pointer type to another or between a pointer and an
10207 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010208 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010209 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10210 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010211 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010212 }
10213
10214 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010215 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010216 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010217
Chris Lattner58d74912008-03-12 17:45:29 +000010218 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10219 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010220 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010221 // won't be dropping them. Check that these extra arguments have attributes
10222 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010223 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10224 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010225 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010226 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010227 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010228 return false;
10229 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010230
Chris Lattner9fe38862003-06-19 17:00:31 +000010231 // Okay, we decided that this is a safe thing to do: go ahead and start
10232 // inserting cast instructions as necessary...
10233 std::vector<Value*> Args;
10234 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010235 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010236 attrVec.reserve(NumCommonArgs);
10237
10238 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010239 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010240
10241 // If the return value is not being used, the type may not be compatible
10242 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010243 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010244
10245 // Add the new return attributes.
10246 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010247 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010248
10249 AI = CS.arg_begin();
10250 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10251 const Type *ParamTy = FT->getParamType(i);
10252 if ((*AI)->getType() == ParamTy) {
10253 Args.push_back(*AI);
10254 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010255 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010256 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010257 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010258 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010259 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010260
10261 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010262 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010263 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010264 }
10265
10266 // If the function takes more arguments than the call was taking, add them
10267 // now...
10268 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000010269 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010270
10271 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010272 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010273 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010274 cerr << "WARNING: While resolving call to function '"
10275 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010276 } else {
10277 // Add all of the arguments in their promoted form to the arg list...
10278 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10279 const Type *PTy = getPromotedType((*AI)->getType());
10280 if (PTy != (*AI)->getType()) {
10281 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010282 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10283 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010284 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010285 InsertNewInstBefore(Cast, *Caller);
10286 Args.push_back(Cast);
10287 } else {
10288 Args.push_back(*AI);
10289 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010290
Duncan Sandse1e520f2008-01-13 08:02:44 +000010291 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010292 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010293 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010294 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010295 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010296 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010297
Devang Patel19c87462008-09-26 22:53:05 +000010298 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10299 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10300
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010301 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010302 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010303
Devang Patel05988662008-09-25 21:00:45 +000010304 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010305
Chris Lattner9fe38862003-06-19 17:00:31 +000010306 Instruction *NC;
10307 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010308 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010309 Args.begin(), Args.end(),
10310 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010311 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010312 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010313 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010314 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10315 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010316 CallInst *CI = cast<CallInst>(Caller);
10317 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010318 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010319 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010320 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010321 }
10322
Chris Lattner6934a042007-02-11 01:23:03 +000010323 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010324 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010325 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010326 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010327 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010328 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010329 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010330
10331 // If this is an invoke instruction, we should insert it after the first
10332 // non-phi, instruction in the normal successor block.
10333 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010334 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010335 InsertNewInstBefore(NC, *I);
10336 } else {
10337 // Otherwise, it's a call, just insert cast right after the call instr
10338 InsertNewInstBefore(NC, *Caller);
10339 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010340 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010341 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000010342 NV = Context->getUndef(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010343 }
10344 }
10345
10346 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10347 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010348 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010349 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010350 return true;
10351}
10352
Duncan Sandscdb6d922007-09-17 10:26:40 +000010353// transformCallThroughTrampoline - Turn a call to a function created by the
10354// init_trampoline intrinsic into a direct call to the underlying function.
10355//
10356Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10357 Value *Callee = CS.getCalledValue();
10358 const PointerType *PTy = cast<PointerType>(Callee->getType());
10359 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010360 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010361
10362 // If the call already has the 'nest' attribute somewhere then give up -
10363 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010364 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010365 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010366
10367 IntrinsicInst *Tramp =
10368 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10369
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010370 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010371 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10372 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10373
Devang Patel05988662008-09-25 21:00:45 +000010374 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010375 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 unsigned NestIdx = 1;
10377 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010378 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010379
10380 // Look for a parameter marked with the 'nest' attribute.
10381 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10382 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010383 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010384 // Record the parameter type and any other attributes.
10385 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010386 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387 break;
10388 }
10389
10390 if (NestTy) {
10391 Instruction *Caller = CS.getInstruction();
10392 std::vector<Value*> NewArgs;
10393 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10394
Devang Patel05988662008-09-25 21:00:45 +000010395 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010396 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010397
Duncan Sandscdb6d922007-09-17 10:26:40 +000010398 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010399 // mean appending it. Likewise for attributes.
10400
Devang Patel19c87462008-09-26 22:53:05 +000010401 // Add any result attributes.
10402 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010403 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010404
Duncan Sandscdb6d922007-09-17 10:26:40 +000010405 {
10406 unsigned Idx = 1;
10407 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10408 do {
10409 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010410 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010411 Value *NestVal = Tramp->getOperand(3);
10412 if (NestVal->getType() != NestTy)
10413 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10414 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010415 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010416 }
10417
10418 if (I == E)
10419 break;
10420
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010421 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010422 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010423 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010424 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010425 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010426
10427 ++Idx, ++I;
10428 } while (1);
10429 }
10430
Devang Patel19c87462008-09-26 22:53:05 +000010431 // Add any function attributes.
10432 if (Attributes Attr = Attrs.getFnAttributes())
10433 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10434
Duncan Sandscdb6d922007-09-17 10:26:40 +000010435 // The trampoline may have been bitcast to a bogus type (FTy).
10436 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010437 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438
Duncan Sandscdb6d922007-09-17 10:26:40 +000010439 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440 NewTypes.reserve(FTy->getNumParams()+1);
10441
Duncan Sandscdb6d922007-09-17 10:26:40 +000010442 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010443 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010444 {
10445 unsigned Idx = 1;
10446 FunctionType::param_iterator I = FTy->param_begin(),
10447 E = FTy->param_end();
10448
10449 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010450 if (Idx == NestIdx)
10451 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010452 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010453
10454 if (I == E)
10455 break;
10456
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010457 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010458 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010459
10460 ++Idx, ++I;
10461 } while (1);
10462 }
10463
10464 // Replace the trampoline call with a direct call. Let the generic
10465 // code sort out any function type mismatches.
10466 FunctionType *NewFTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000010467 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10468 FTy->isVarArg());
10469 Constant *NewCallee =
10470 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10471 NestF : Context->getConstantExprBitCast(NestF,
10472 Context->getPointerTypeUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010473 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010474
10475 Instruction *NewCaller;
10476 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010477 NewCaller = InvokeInst::Create(NewCallee,
10478 II->getNormalDest(), II->getUnwindDest(),
10479 NewArgs.begin(), NewArgs.end(),
10480 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010481 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010482 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010483 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010484 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10485 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010486 if (cast<CallInst>(Caller)->isTailCall())
10487 cast<CallInst>(NewCaller)->setTailCall();
10488 cast<CallInst>(NewCaller)->
10489 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010490 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010491 }
10492 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10493 Caller->replaceAllUsesWith(NewCaller);
10494 Caller->eraseFromParent();
10495 RemoveFromWorkList(Caller);
10496 return 0;
10497 }
10498 }
10499
10500 // Replace the trampoline call with a direct call. Since there is no 'nest'
10501 // parameter, there is no need to adjust the argument list. Let the generic
10502 // code sort out any function type mismatches.
10503 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010504 NestF->getType() == PTy ? NestF :
10505 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010506 CS.setCalledFunction(NewCallee);
10507 return CS.getInstruction();
10508}
10509
Chris Lattner7da52b22006-11-01 04:51:18 +000010510/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10511/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10512/// and a single binop.
10513Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10514 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010515 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010516 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010517 Value *LHSVal = FirstInst->getOperand(0);
10518 Value *RHSVal = FirstInst->getOperand(1);
10519
10520 const Type *LHSType = LHSVal->getType();
10521 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010522
10523 // Scan to see if all operands are the same opcode, all have one use, and all
10524 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010525 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010526 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010527 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010528 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010529 // types or GEP's with different index types.
10530 I->getOperand(0)->getType() != LHSType ||
10531 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010532 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010533
10534 // If they are CmpInst instructions, check their predicates
10535 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10536 if (cast<CmpInst>(I)->getPredicate() !=
10537 cast<CmpInst>(FirstInst)->getPredicate())
10538 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010539
10540 // Keep track of which operand needs a phi node.
10541 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10542 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010543 }
10544
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010545 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010546
Chris Lattner7da52b22006-11-01 04:51:18 +000010547 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010548 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010549 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010550 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010551 NewLHS = PHINode::Create(LHSType,
10552 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010553 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10554 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010555 InsertNewInstBefore(NewLHS, PN);
10556 LHSVal = NewLHS;
10557 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010558
10559 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010560 NewRHS = PHINode::Create(RHSType,
10561 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010562 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10563 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010564 InsertNewInstBefore(NewRHS, PN);
10565 RHSVal = NewRHS;
10566 }
10567
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010568 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010569 if (NewLHS || NewRHS) {
10570 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10571 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10572 if (NewLHS) {
10573 Value *NewInLHS = InInst->getOperand(0);
10574 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10575 }
10576 if (NewRHS) {
10577 Value *NewInRHS = InInst->getOperand(1);
10578 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10579 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010580 }
10581 }
10582
Chris Lattner7da52b22006-11-01 04:51:18 +000010583 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010584 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010585 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson333c4002009-07-09 23:48:35 +000010586 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10587 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010588}
10589
Chris Lattner05f18922008-12-01 02:34:36 +000010590Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10591 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10592
10593 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10594 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010595 // This is true if all GEP bases are allocas and if all indices into them are
10596 // constants.
10597 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010598
10599 // Scan to see if all operands are the same opcode, all have one use, and all
10600 // kill their operands (i.e. the operands have one use).
10601 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10602 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10603 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10604 GEP->getNumOperands() != FirstInst->getNumOperands())
10605 return 0;
10606
Chris Lattner36d3e322009-02-21 00:46:50 +000010607 // Keep track of whether or not all GEPs are of alloca pointers.
10608 if (AllBasePointersAreAllocas &&
10609 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10610 !GEP->hasAllConstantIndices()))
10611 AllBasePointersAreAllocas = false;
10612
Chris Lattner05f18922008-12-01 02:34:36 +000010613 // Compare the operand lists.
10614 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10615 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10616 continue;
10617
10618 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10619 // if one of the PHIs has a constant for the index. The index may be
10620 // substantially cheaper to compute for the constants, so making it a
10621 // variable index could pessimize the path. This also handles the case
10622 // for struct indices, which must always be constant.
10623 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10624 isa<ConstantInt>(GEP->getOperand(op)))
10625 return 0;
10626
10627 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10628 return 0;
10629 FixedOperands[op] = 0; // Needs a PHI.
10630 }
10631 }
10632
Chris Lattner36d3e322009-02-21 00:46:50 +000010633 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010634 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010635 // offset calculation, but all the predecessors will have to materialize the
10636 // stack address into a register anyway. We'd actually rather *clone* the
10637 // load up into the predecessors so that we have a load of a gep of an alloca,
10638 // which can usually all be folded into the load.
10639 if (AllBasePointersAreAllocas)
10640 return 0;
10641
Chris Lattner05f18922008-12-01 02:34:36 +000010642 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10643 // that is variable.
10644 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10645
10646 bool HasAnyPHIs = false;
10647 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10648 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10649 Value *FirstOp = FirstInst->getOperand(i);
10650 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10651 FirstOp->getName()+".pn");
10652 InsertNewInstBefore(NewPN, PN);
10653
10654 NewPN->reserveOperandSpace(e);
10655 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10656 OperandPhis[i] = NewPN;
10657 FixedOperands[i] = NewPN;
10658 HasAnyPHIs = true;
10659 }
10660
10661
10662 // Add all operands to the new PHIs.
10663 if (HasAnyPHIs) {
10664 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10665 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10666 BasicBlock *InBB = PN.getIncomingBlock(i);
10667
10668 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10669 if (PHINode *OpPhi = OperandPhis[op])
10670 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10671 }
10672 }
10673
10674 Value *Base = FixedOperands[0];
10675 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10676 FixedOperands.end());
10677}
10678
10679
Chris Lattner21550882009-02-23 05:56:17 +000010680/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10681/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010682/// obvious the value of the load is not changed from the point of the load to
10683/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010684///
10685/// Finally, it is safe, but not profitable, to sink a load targetting a
10686/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10687/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010688static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010689 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10690
10691 for (++BBI; BBI != E; ++BBI)
10692 if (BBI->mayWriteToMemory())
10693 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010694
10695 // Check for non-address taken alloca. If not address-taken already, it isn't
10696 // profitable to do this xform.
10697 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10698 bool isAddressTaken = false;
10699 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10700 UI != E; ++UI) {
10701 if (isa<LoadInst>(UI)) continue;
10702 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10703 // If storing TO the alloca, then the address isn't taken.
10704 if (SI->getOperand(1) == AI) continue;
10705 }
10706 isAddressTaken = true;
10707 break;
10708 }
10709
Chris Lattner36d3e322009-02-21 00:46:50 +000010710 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010711 return false;
10712 }
10713
Chris Lattner36d3e322009-02-21 00:46:50 +000010714 // If this load is a load from a GEP with a constant offset from an alloca,
10715 // then we don't want to sink it. In its present form, it will be
10716 // load [constant stack offset]. Sinking it will cause us to have to
10717 // materialize the stack addresses in each predecessor in a register only to
10718 // do a shared load from register in the successor.
10719 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10720 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10721 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10722 return false;
10723
Chris Lattner76c73142006-11-01 07:13:54 +000010724 return true;
10725}
10726
Chris Lattner9fe38862003-06-19 17:00:31 +000010727
Chris Lattnerbac32862004-11-14 19:13:23 +000010728// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10729// operator and they all are only used by the PHI, PHI together their
10730// inputs, and do the operation once, to the result of the PHI.
10731Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10732 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10733
10734 // Scan the instruction, looking for input operations that can be folded away.
10735 // If all input operands to the phi are the same instruction (e.g. a cast from
10736 // the same type or "+42") we can pull the operation through the PHI, reducing
10737 // code size and simplifying code.
10738 Constant *ConstantOp = 0;
10739 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010740 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010741 if (isa<CastInst>(FirstInst)) {
10742 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010743 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010744 // Can fold binop, compare or shift here if the RHS is a constant,
10745 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010746 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010747 if (ConstantOp == 0)
10748 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010749 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10750 isVolatile = LI->isVolatile();
10751 // We can't sink the load if the loaded value could be modified between the
10752 // load and the PHI.
10753 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010754 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010755 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010756
10757 // If the PHI is of volatile loads and the load block has multiple
10758 // successors, sinking it would remove a load of the volatile value from
10759 // the path through the other successor.
10760 if (isVolatile &&
10761 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10762 return 0;
10763
Chris Lattner9c080502006-11-01 07:43:41 +000010764 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010765 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010766 } else {
10767 return 0; // Cannot fold this operation.
10768 }
10769
10770 // Check to see if all arguments are the same operation.
10771 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10772 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10773 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010774 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010775 return 0;
10776 if (CastSrcTy) {
10777 if (I->getOperand(0)->getType() != CastSrcTy)
10778 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010779 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010780 // We can't sink the load if the loaded value could be modified between
10781 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010782 if (LI->isVolatile() != isVolatile ||
10783 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010784 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010785 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010786
Chris Lattner71042962008-07-08 17:18:32 +000010787 // If the PHI is of volatile loads and the load block has multiple
10788 // successors, sinking it would remove a load of the volatile value from
10789 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010790 if (isVolatile &&
10791 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10792 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010793
Chris Lattnerbac32862004-11-14 19:13:23 +000010794 } else if (I->getOperand(1) != ConstantOp) {
10795 return 0;
10796 }
10797 }
10798
10799 // Okay, they are all the same operation. Create a new PHI node of the
10800 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010801 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10802 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010803 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010804
10805 Value *InVal = FirstInst->getOperand(0);
10806 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010807
10808 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010809 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10810 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10811 if (NewInVal != InVal)
10812 InVal = 0;
10813 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10814 }
10815
10816 Value *PhiVal;
10817 if (InVal) {
10818 // The new PHI unions all of the same values together. This is really
10819 // common, so we handle it intelligently here for compile-time speed.
10820 PhiVal = InVal;
10821 delete NewPN;
10822 } else {
10823 InsertNewInstBefore(NewPN, PN);
10824 PhiVal = NewPN;
10825 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010826
Chris Lattnerbac32862004-11-14 19:13:23 +000010827 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010828 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010829 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010830 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010831 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010832 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson333c4002009-07-09 23:48:35 +000010833 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010834 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010835 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10836
10837 // If this was a volatile load that we are merging, make sure to loop through
10838 // and mark all the input loads as non-volatile. If we don't do this, we will
10839 // insert a new volatile load and the old ones will not be deletable.
10840 if (isVolatile)
10841 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10842 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10843
10844 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010845}
Chris Lattnera1be5662002-05-02 17:06:02 +000010846
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010847/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10848/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010849static bool DeadPHICycle(PHINode *PN,
10850 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010851 if (PN->use_empty()) return true;
10852 if (!PN->hasOneUse()) return false;
10853
10854 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010855 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010856 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010857
10858 // Don't scan crazily complex things.
10859 if (PotentiallyDeadPHIs.size() == 16)
10860 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010861
10862 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10863 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010864
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010865 return false;
10866}
10867
Chris Lattnercf5008a2007-11-06 21:52:06 +000010868/// PHIsEqualValue - Return true if this phi node is always equal to
10869/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10870/// z = some value; x = phi (y, z); y = phi (x, z)
10871static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10872 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10873 // See if we already saw this PHI node.
10874 if (!ValueEqualPHIs.insert(PN))
10875 return true;
10876
10877 // Don't scan crazily complex things.
10878 if (ValueEqualPHIs.size() == 16)
10879 return false;
10880
10881 // Scan the operands to see if they are either phi nodes or are equal to
10882 // the value.
10883 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10884 Value *Op = PN->getIncomingValue(i);
10885 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10886 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10887 return false;
10888 } else if (Op != NonPhiInVal)
10889 return false;
10890 }
10891
10892 return true;
10893}
10894
10895
Chris Lattner473945d2002-05-06 18:06:38 +000010896// PHINode simplification
10897//
Chris Lattner7e708292002-06-25 16:13:24 +000010898Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010899 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010900 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010901
Owen Anderson7e057142006-07-10 22:03:18 +000010902 if (Value *V = PN.hasConstantValue())
10903 return ReplaceInstUsesWith(PN, V);
10904
Owen Anderson7e057142006-07-10 22:03:18 +000010905 // If all PHI operands are the same operation, pull them through the PHI,
10906 // reducing code size.
10907 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010908 isa<Instruction>(PN.getIncomingValue(1)) &&
10909 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10910 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10911 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10912 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010913 PN.getIncomingValue(0)->hasOneUse())
10914 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10915 return Result;
10916
10917 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10918 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10919 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010920 if (PN.hasOneUse()) {
10921 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10922 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010923 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010924 PotentiallyDeadPHIs.insert(&PN);
10925 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Andersond672ecb2009-07-03 00:17:18 +000010926 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010927 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010928
10929 // If this phi has a single use, and if that use just computes a value for
10930 // the next iteration of a loop, delete the phi. This occurs with unused
10931 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10932 // common case here is good because the only other things that catch this
10933 // are induction variable analysis (sometimes) and ADCE, which is only run
10934 // late.
10935 if (PHIUser->hasOneUse() &&
10936 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10937 PHIUser->use_back() == &PN) {
Owen Andersond672ecb2009-07-03 00:17:18 +000010938 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010939 }
10940 }
Owen Anderson7e057142006-07-10 22:03:18 +000010941
Chris Lattnercf5008a2007-11-06 21:52:06 +000010942 // We sometimes end up with phi cycles that non-obviously end up being the
10943 // same value, for example:
10944 // z = some value; x = phi (y, z); y = phi (x, z)
10945 // where the phi nodes don't necessarily need to be in the same block. Do a
10946 // quick check to see if the PHI node only contains a single non-phi value, if
10947 // so, scan to see if the phi cycle is actually equal to that value.
10948 {
10949 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10950 // Scan for the first non-phi operand.
10951 while (InValNo != NumOperandVals &&
10952 isa<PHINode>(PN.getIncomingValue(InValNo)))
10953 ++InValNo;
10954
10955 if (InValNo != NumOperandVals) {
10956 Value *NonPhiInVal = PN.getOperand(InValNo);
10957
10958 // Scan the rest of the operands to see if there are any conflicts, if so
10959 // there is no need to recursively scan other phis.
10960 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10961 Value *OpVal = PN.getIncomingValue(InValNo);
10962 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10963 break;
10964 }
10965
10966 // If we scanned over all operands, then we have one unique value plus
10967 // phi values. Scan PHI nodes to see if they all merge in each other or
10968 // the value.
10969 if (InValNo == NumOperandVals) {
10970 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10971 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10972 return ReplaceInstUsesWith(PN, NonPhiInVal);
10973 }
10974 }
10975 }
Chris Lattner60921c92003-12-19 05:58:40 +000010976 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010977}
10978
Reid Spencer17212df2006-12-12 09:18:51 +000010979static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10980 Instruction *InsertPoint,
10981 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010982 unsigned PtrSize = DTy->getScalarSizeInBits();
10983 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010984 // We must cast correctly to the pointer type. Ensure that we
10985 // sign extend the integer value if it is smaller as this is
10986 // used for address computation.
10987 Instruction::CastOps opcode =
10988 (VTySize < PtrSize ? Instruction::SExt :
10989 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10990 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010991}
10992
Chris Lattnera1be5662002-05-02 17:06:02 +000010993
Chris Lattner7e708292002-06-25 16:13:24 +000010994Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010995 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010996 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010997 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010998 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010999 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011000
Chris Lattnere87597f2004-10-16 18:11:37 +000011001 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000011002 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011003
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011004 bool HasZeroPointerIndex = false;
11005 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11006 HasZeroPointerIndex = C->isNullValue();
11007
11008 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011009 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011010
Chris Lattner28977af2004-04-05 01:30:19 +000011011 // Eliminate unneeded casts for indices.
11012 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011013
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011014 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011015 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11016 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000011017 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000011018 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011019 if (CI->getOpcode() == Instruction::ZExt ||
11020 CI->getOpcode() == Instruction::SExt) {
11021 const Type *SrcTy = CI->getOperand(0)->getType();
11022 // We can eliminate a cast from i32 to i64 iff the target
11023 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000011024 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000011025 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000011026 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000011027 }
11028 }
11029 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011030 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000011031 // to what we need. If narrower, sign-extend it to what we need.
11032 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011033 // insert it. This explicit cast can make subsequent optimizations more
11034 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000011035 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011036 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000011037 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011038 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000011039 MadeChange = true;
11040 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000011041 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11042 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000011043 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011044 MadeChange = true;
11045 }
Dan Gohman4f833d42008-09-11 23:06:38 +000011046 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11047 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011048 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman4f833d42008-09-11 23:06:38 +000011049 MadeChange = true;
11050 } else {
11051 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11052 GEP);
11053 *i = Op;
11054 MadeChange = true;
11055 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011056 }
Chris Lattner28977af2004-04-05 01:30:19 +000011057 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011058 }
Chris Lattner28977af2004-04-05 01:30:19 +000011059 if (MadeChange) return &GEP;
11060
Chris Lattner90ac28c2002-08-02 19:29:35 +000011061 // Combine Indices - If the source pointer to this getelementptr instruction
11062 // is a getelementptr instruction, combine the indices of the two
11063 // getelementptr instructions into a single instruction.
11064 //
Chris Lattner72588fc2007-02-15 22:48:32 +000011065 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000011066 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000011067 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000011068
11069 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000011070 // Note that if our source is a gep chain itself that we wait for that
11071 // chain to be resolved before we perform this transformation. This
11072 // avoids us creating a TON of code in some cases.
11073 //
11074 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11075 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11076 return 0; // Wait until our source is folded to completion.
11077
Chris Lattner72588fc2007-02-15 22:48:32 +000011078 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011079
11080 // Find out whether the last index in the source GEP is a sequential idx.
11081 bool EndsWithSequential = false;
11082 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11083 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011084 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011085
Chris Lattner90ac28c2002-08-02 19:29:35 +000011086 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011087 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011088 // Replace: gep (gep %P, long B), long A, ...
11089 // With: T = long A+B; gep %P, T, ...
11090 //
Chris Lattner620ce142004-05-07 22:09:22 +000011091 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011092 if (SO1 == Context->getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011093 Sum = GO1;
Owen Andersond672ecb2009-07-03 00:17:18 +000011094 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011095 Sum = SO1;
11096 } else {
11097 // If they aren't the same type, convert both to an integer of the
11098 // target's pointer size.
11099 if (SO1->getType() != GO1->getType()) {
11100 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011101 SO1 =
11102 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011103 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011104 GO1 =
11105 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011106 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011107 unsigned PS = TD->getPointerSizeInBits();
11108 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011109 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011110 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011111
Duncan Sands514ab342007-11-01 20:53:16 +000011112 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011113 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011114 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011115 } else {
11116 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011117 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11118 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011119 }
11120 }
11121 }
Chris Lattner620ce142004-05-07 22:09:22 +000011122 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Andersond672ecb2009-07-03 00:17:18 +000011123 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11124 cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000011125 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011126 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011127 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011128 }
Chris Lattner28977af2004-04-05 01:30:19 +000011129 }
Chris Lattner620ce142004-05-07 22:09:22 +000011130
11131 // Recycle the GEP we already have if possible.
11132 if (SrcGEPOperands.size() == 2) {
11133 GEP.setOperand(0, SrcGEPOperands[0]);
11134 GEP.setOperand(1, Sum);
11135 return &GEP;
11136 } else {
11137 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11138 SrcGEPOperands.end()-1);
11139 Indices.push_back(Sum);
11140 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11141 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011142 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011143 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011144 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011145 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011146 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11147 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011148 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11149 }
11150
11151 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011152 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11153 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011154
Chris Lattner620ce142004-05-07 22:09:22 +000011155 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011156 // GEP of global variable. If all of the indices for this GEP are
11157 // constants, we can promote this to a constexpr instead of an instruction.
11158
11159 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011160 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011161 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11162 for (; I != E && isa<Constant>(*I); ++I)
11163 Indices.push_back(cast<Constant>(*I));
11164
11165 if (I == E) { // If they are all constants...
Owen Andersond672ecb2009-07-03 00:17:18 +000011166 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Chris Lattner55eb1c42007-01-31 04:40:53 +000011167 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011168
11169 // Replace all uses of the GEP with the new constexpr...
11170 return ReplaceInstUsesWith(GEP, CE);
11171 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011172 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011173 if (!isa<PointerType>(X->getType())) {
11174 // Not interesting. Source pointer must be a cast from pointer.
11175 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011176 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11177 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011178 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011179 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11180 // into : GEP i8* X, ...
11181 //
Chris Lattnereed48272005-09-13 00:40:14 +000011182 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011183 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11184 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011185 if (const ArrayType *CATy =
11186 dyn_cast<ArrayType>(CPTy->getElementType())) {
11187 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11188 if (CATy->getElementType() == XTy->getElementType()) {
11189 // -> GEP i8* X, ...
11190 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11191 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11192 GEP.getName());
11193 } else if (const ArrayType *XATy =
11194 dyn_cast<ArrayType>(XTy->getElementType())) {
11195 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011196 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011197 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011198 // At this point, we know that the cast source type is a pointer
11199 // to an array of the same type as the destination pointer
11200 // array. Because the array type is never stepped over (there
11201 // is a leading zero) we can fold the cast into this GEP.
11202 GEP.setOperand(0, X);
11203 return &GEP;
11204 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011205 }
11206 }
Chris Lattnereed48272005-09-13 00:40:14 +000011207 } else if (GEP.getNumOperands() == 2) {
11208 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011209 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11210 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011211 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11212 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11213 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011214 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11215 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011216 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011217 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011218 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011219 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011220 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011221 // V and GEP are both pointer types --> BitCast
11222 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011223 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011224
11225 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011226 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011227 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011228 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011229
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011230 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011231 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011232 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011233
11234 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11235 // allow either a mul, shift, or constant here.
11236 Value *NewIdx = 0;
11237 ConstantInt *Scale = 0;
11238 if (ArrayEltSize == 1) {
11239 NewIdx = GEP.getOperand(1);
Owen Andersond672ecb2009-07-03 00:17:18 +000011240 Scale =
11241 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011242 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011243 NewIdx = Context->getConstantInt(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011244 Scale = CI;
11245 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11246 if (Inst->getOpcode() == Instruction::Shl &&
11247 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011248 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11249 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersond672ecb2009-07-03 00:17:18 +000011250 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011251 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011252 NewIdx = Inst->getOperand(0);
11253 } else if (Inst->getOpcode() == Instruction::Mul &&
11254 isa<ConstantInt>(Inst->getOperand(1))) {
11255 Scale = cast<ConstantInt>(Inst->getOperand(1));
11256 NewIdx = Inst->getOperand(0);
11257 }
11258 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011259
Chris Lattner7835cdd2005-09-13 18:36:04 +000011260 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011261 // out, perform the transformation. Note, we don't know whether Scale is
11262 // signed or not. We'll use unsigned version of division/modulo
11263 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011264 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011265 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011266 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011267 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011268 if (Scale->getZExtValue() != 1) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011269 Constant *C =
11270 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011271 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011272 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011273 NewIdx = InsertNewInstBefore(Sc, GEP);
11274 }
11275
11276 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011277 Value *Idx[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011278 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011279 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011280 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011281 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011282 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11283 // The NewGEP must be pointer typed, so must the old one -> BitCast
11284 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011285 }
11286 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011287 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011288 }
Chris Lattner58407792009-01-09 04:53:57 +000011289
Chris Lattner46cd5a12009-01-09 05:44:56 +000011290 /// See if we can simplify:
11291 /// X = bitcast A to B*
11292 /// Y = gep X, <...constant indices...>
11293 /// into a gep of the original struct. This is important for SROA and alias
11294 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011295 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011296 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11297 // Determine how much the GEP moves the pointer. We are guaranteed to get
11298 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011299 ConstantInt *OffsetV =
11300 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011301 int64_t Offset = OffsetV->getSExtValue();
11302
11303 // If this GEP instruction doesn't move the pointer, just replace the GEP
11304 // with a bitcast of the real input to the dest type.
11305 if (Offset == 0) {
11306 // If the bitcast is of an allocation, and the allocation will be
11307 // converted to match the type of the cast, don't touch this.
11308 if (isa<AllocationInst>(BCI->getOperand(0))) {
11309 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11310 if (Instruction *I = visitBitCast(*BCI)) {
11311 if (I != BCI) {
11312 I->takeName(BCI);
11313 BCI->getParent()->getInstList().insert(BCI, I);
11314 ReplaceInstUsesWith(*BCI, I);
11315 }
11316 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011317 }
Chris Lattner58407792009-01-09 04:53:57 +000011318 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011319 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011320 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011321
11322 // Otherwise, if the offset is non-zero, we need to find out if there is a
11323 // field at Offset in 'A's type. If so, we can pull the cast through the
11324 // GEP.
11325 SmallVector<Value*, 8> NewIndices;
11326 const Type *InTy =
11327 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011328 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011329 Instruction *NGEP =
11330 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11331 NewIndices.end());
11332 if (NGEP->getType() == GEP.getType()) return NGEP;
11333 InsertNewInstBefore(NGEP, GEP);
11334 NGEP->takeName(&GEP);
11335 return new BitCastInst(NGEP, GEP.getType());
11336 }
Chris Lattner58407792009-01-09 04:53:57 +000011337 }
11338 }
11339
Chris Lattner8a2a3112001-12-14 16:52:21 +000011340 return 0;
11341}
11342
Chris Lattner0864acf2002-11-04 16:18:53 +000011343Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11344 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011345 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011346 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11347 const Type *NewTy =
Owen Andersond672ecb2009-07-03 00:17:18 +000011348 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011349 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011350
11351 // Create and insert the replacement instruction...
11352 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011353 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011354 else {
11355 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011356 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011357 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011358
11359 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011360
Chris Lattner0864acf2002-11-04 16:18:53 +000011361 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011362 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011363 //
11364 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011365 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011366
11367 // Now that I is pointing to the first non-allocation-inst in the block,
11368 // insert our getelementptr instruction...
11369 //
Owen Andersond672ecb2009-07-03 00:17:18 +000011370 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011371 Value *Idx[2];
11372 Idx[0] = NullIdx;
11373 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011374 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11375 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011376
11377 // Now make everything use the getelementptr instead of the original
11378 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011379 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011380 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011381 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011382 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011383 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011384
Dan Gohman6893cd72009-01-13 20:18:38 +000011385 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11386 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011387 // Note that we only do this for alloca's, because malloc should allocate
11388 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011389 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersond672ecb2009-07-03 00:17:18 +000011390 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011391
11392 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11393 if (AI.getAlignment() == 0)
11394 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11395 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011396
Chris Lattner0864acf2002-11-04 16:18:53 +000011397 return 0;
11398}
11399
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011400Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11401 Value *Op = FI.getOperand(0);
11402
Chris Lattner17be6352004-10-18 02:59:09 +000011403 // free undef -> unreachable.
11404 if (isa<UndefValue>(Op)) {
11405 // Insert a new store to null because we cannot modify the CFG here.
Owen Andersond672ecb2009-07-03 00:17:18 +000011406 new StoreInst(Context->getConstantIntTrue(),
11407 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011408 return EraseInstFromFunction(FI);
11409 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011410
Chris Lattner6160e852004-02-28 04:57:37 +000011411 // If we have 'free null' delete the instruction. This can happen in stl code
11412 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011413 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011414 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011415
11416 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11417 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11418 FI.setOperand(0, CI->getOperand(0));
11419 return &FI;
11420 }
11421
11422 // Change free (gep X, 0,0,0,0) into free(X)
11423 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11424 if (GEPI->hasAllZeroIndices()) {
11425 AddToWorkList(GEPI);
11426 FI.setOperand(0, GEPI->getOperand(0));
11427 return &FI;
11428 }
11429 }
11430
11431 // Change free(malloc) into nothing, if the malloc has a single use.
11432 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11433 if (MI->hasOneUse()) {
11434 EraseInstFromFunction(FI);
11435 return EraseInstFromFunction(*MI);
11436 }
Chris Lattner6160e852004-02-28 04:57:37 +000011437
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011438 return 0;
11439}
11440
11441
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011442/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011443static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011444 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011445 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011446 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011447 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011448
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011449 if (TD) {
11450 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11451 // Instead of loading constant c string, use corresponding integer value
11452 // directly if string length is small enough.
11453 std::string Str;
11454 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11455 unsigned len = Str.length();
11456 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11457 unsigned numBits = Ty->getPrimitiveSizeInBits();
11458 // Replace LI with immediate integer store.
11459 if ((numBits >> 3) == len + 1) {
11460 APInt StrVal(numBits, 0);
11461 APInt SingleChar(numBits, 0);
11462 if (TD->isLittleEndian()) {
11463 for (signed i = len-1; i >= 0; i--) {
11464 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11465 StrVal = (StrVal << 8) | SingleChar;
11466 }
11467 } else {
11468 for (unsigned i = 0; i < len; i++) {
11469 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11470 StrVal = (StrVal << 8) | SingleChar;
11471 }
11472 // Append NULL at the end.
11473 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011474 StrVal = (StrVal << 8) | SingleChar;
11475 }
Owen Andersond672ecb2009-07-03 00:17:18 +000011476 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011477 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011478 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011479 }
11480 }
11481 }
11482
Mon P Wang6753f952009-02-07 22:19:29 +000011483 const PointerType *DestTy = cast<PointerType>(CI->getType());
11484 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011485 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011486
11487 // If the address spaces don't match, don't eliminate the cast.
11488 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11489 return 0;
11490
Chris Lattnerb89e0712004-07-13 01:49:43 +000011491 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011492
Reid Spencer42230162007-01-22 05:51:25 +000011493 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011494 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011495 // If the source is an array, the code below will not succeed. Check to
11496 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11497 // constants.
11498 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11499 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11500 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011501 Value *Idxs[2];
Owen Andersond672ecb2009-07-03 00:17:18 +000011502 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11503 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011504 SrcTy = cast<PointerType>(CastOp->getType());
11505 SrcPTy = SrcTy->getElementType();
11506 }
11507
Reid Spencer42230162007-01-22 05:51:25 +000011508 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011509 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011510 // Do not allow turning this into a load of an integer, which is then
11511 // casted to a pointer, this pessimizes pointer analysis a lot.
11512 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011513 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11514 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011515
Chris Lattnerf9527852005-01-31 04:50:46 +000011516 // Okay, we are casting from one integer or pointer type to another of
11517 // the same size. Instead of casting the pointer before the load, cast
11518 // the result of the loaded value.
11519 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11520 CI->getName(),
11521 LI.isVolatile()),LI);
11522 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011523 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011524 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011525 }
11526 }
11527 return 0;
11528}
11529
Chris Lattner833b8a42003-06-26 05:06:25 +000011530Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11531 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011532
Dan Gohman9941f742007-07-20 16:34:21 +000011533 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011534 unsigned KnownAlign =
11535 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011536 if (KnownAlign >
11537 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11538 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011539 LI.setAlignment(KnownAlign);
11540
Chris Lattner37366c12005-05-01 04:24:53 +000011541 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011542 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011543 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011544 return Res;
11545
11546 // None of the following transforms are legal for volatile loads.
11547 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011548
Dan Gohman2276a7b2008-10-15 23:19:35 +000011549 // Do really simple store-to-load forwarding and load CSE, to catch cases
11550 // where there are several consequtive memory accesses to the same location,
11551 // separated by a few arithmetic operations.
11552 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011553 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11554 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011555
Christopher Lambb15147e2007-12-29 07:56:53 +000011556 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11557 const Value *GEPI0 = GEPI->getOperand(0);
11558 // TODO: Consider a target hook for valid address spaces for this xform.
11559 if (isa<ConstantPointerNull>(GEPI0) &&
11560 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011561 // Insert a new store to null instruction before the load to indicate
11562 // that this code is not reachable. We do this instead of inserting
11563 // an unreachable instruction directly because we cannot modify the
11564 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011565 new StoreInst(Context->getUndef(LI.getType()),
11566 Context->getNullValue(Op->getType()), &LI);
11567 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011568 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011569 }
Chris Lattner37366c12005-05-01 04:24:53 +000011570
Chris Lattnere87597f2004-10-16 18:11:37 +000011571 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011572 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011573 // TODO: Consider a target hook for valid address spaces for this xform.
11574 if (isa<UndefValue>(C) || (C->isNullValue() &&
11575 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011576 // Insert a new store to null instruction before the load to indicate that
11577 // this code is not reachable. We do this instead of inserting an
11578 // unreachable instruction directly because we cannot modify the CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011579 new StoreInst(Context->getUndef(LI.getType()),
11580 Context->getNullValue(Op->getType()), &LI);
11581 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011582 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011583
Chris Lattnere87597f2004-10-16 18:11:37 +000011584 // Instcombine load (constant global) into the value loaded.
11585 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011586 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011587 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011588
Chris Lattnere87597f2004-10-16 18:11:37 +000011589 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011590 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011591 if (CE->getOpcode() == Instruction::GetElementPtr) {
11592 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011593 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011594 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011595 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11596 Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011597 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011598 if (CE->getOperand(0)->isNullValue()) {
11599 // Insert a new store to null instruction before the load to indicate
11600 // that this code is not reachable. We do this instead of inserting
11601 // an unreachable instruction directly because we cannot modify the
11602 // CFG.
Owen Andersond672ecb2009-07-03 00:17:18 +000011603 new StoreInst(Context->getUndef(LI.getType()),
11604 Context->getNullValue(Op->getType()), &LI);
11605 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011606 }
11607
Reid Spencer3da59db2006-11-27 01:05:10 +000011608 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011609 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011610 return Res;
11611 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011612 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011613 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011614
11615 // If this load comes from anywhere in a constant global, and if the global
11616 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011617 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011618 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011619 if (GV->getInitializer()->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +000011620 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011621 else if (isa<UndefValue>(GV->getInitializer()))
Owen Andersond672ecb2009-07-03 00:17:18 +000011622 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011623 }
11624 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011625
Chris Lattner37366c12005-05-01 04:24:53 +000011626 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011627 // Change select and PHI nodes to select values instead of addresses: this
11628 // helps alias analysis out a lot, allows many others simplifications, and
11629 // exposes redundancy in the code.
11630 //
11631 // Note that we cannot do the transformation unless we know that the
11632 // introduced loads cannot trap! Something like this is valid as long as
11633 // the condition is always false: load (select bool %C, int* null, int* %G),
11634 // but it would not be valid if we transformed it to load from null
11635 // unconditionally.
11636 //
11637 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11638 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011639 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11640 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011641 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011642 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011643 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011644 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011645 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011646 }
11647
Chris Lattner684fe212004-09-23 15:46:00 +000011648 // load (select (cond, null, P)) -> load P
11649 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11650 if (C->isNullValue()) {
11651 LI.setOperand(0, SI->getOperand(2));
11652 return &LI;
11653 }
11654
11655 // load (select (cond, P, null)) -> load P
11656 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11657 if (C->isNullValue()) {
11658 LI.setOperand(0, SI->getOperand(1));
11659 return &LI;
11660 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011661 }
11662 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011663 return 0;
11664}
11665
Reid Spencer55af2b52007-01-19 21:20:31 +000011666/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011667/// when possible. This makes it generally easy to do alias analysis and/or
11668/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011669static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11670 User *CI = cast<User>(SI.getOperand(1));
11671 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011672 LLVMContext *Context = IC.getContext();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011673
11674 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011675 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11676 if (SrcTy == 0) return 0;
11677
11678 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011679
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011680 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11681 return 0;
11682
Chris Lattner3914f722009-01-24 01:00:13 +000011683 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11684 /// to its first element. This allows us to handle things like:
11685 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11686 /// on 32-bit hosts.
11687 SmallVector<Value*, 4> NewGEPIndices;
11688
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011689 // If the source is an array, the code below will not succeed. Check to
11690 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11691 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011692 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11693 // Index through pointer.
Owen Andersond672ecb2009-07-03 00:17:18 +000011694 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner3914f722009-01-24 01:00:13 +000011695 NewGEPIndices.push_back(Zero);
11696
11697 while (1) {
11698 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011699 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011700 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011701 NewGEPIndices.push_back(Zero);
11702 SrcPTy = STy->getElementType(0);
11703 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11704 NewGEPIndices.push_back(Zero);
11705 SrcPTy = ATy->getElementType();
11706 } else {
11707 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011708 }
Chris Lattner3914f722009-01-24 01:00:13 +000011709 }
11710
Owen Andersond672ecb2009-07-03 00:17:18 +000011711 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011712 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011713
11714 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11715 return 0;
11716
Chris Lattner71759c42009-01-16 20:12:52 +000011717 // If the pointers point into different address spaces or if they point to
11718 // values with different sizes, we can't do the transformation.
11719 if (SrcTy->getAddressSpace() !=
11720 cast<PointerType>(CI->getType())->getAddressSpace() ||
11721 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011722 IC.getTargetData().getTypeSizeInBits(DestPTy))
11723 return 0;
11724
11725 // Okay, we are casting from one integer or pointer type to another of
11726 // the same size. Instead of casting the pointer before
11727 // the store, cast the value to be stored.
11728 Value *NewCast;
11729 Value *SIOp0 = SI.getOperand(0);
11730 Instruction::CastOps opcode = Instruction::BitCast;
11731 const Type* CastSrcTy = SIOp0->getType();
11732 const Type* CastDstTy = SrcPTy;
11733 if (isa<PointerType>(CastDstTy)) {
11734 if (CastSrcTy->isInteger())
11735 opcode = Instruction::IntToPtr;
11736 } else if (isa<IntegerType>(CastDstTy)) {
11737 if (isa<PointerType>(SIOp0->getType()))
11738 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011739 }
Chris Lattner3914f722009-01-24 01:00:13 +000011740
11741 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11742 // emit a GEP to index into its first field.
11743 if (!NewGEPIndices.empty()) {
11744 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000011745 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011746 NewGEPIndices.size());
11747 else
11748 CastOp = IC.InsertNewInstBefore(
11749 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11750 NewGEPIndices.end()), SI);
11751 }
11752
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011753 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersond672ecb2009-07-03 00:17:18 +000011754 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011755 else
11756 NewCast = IC.InsertNewInstBefore(
11757 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11758 SI);
11759 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011760}
11761
Chris Lattner4aebaee2008-11-27 08:56:30 +000011762/// equivalentAddressValues - Test if A and B will obviously have the same
11763/// value. This includes recognizing that %t0 and %t1 will have the same
11764/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011765/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011766/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011767/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011768/// %t2 = load i32* %t1
11769///
11770static bool equivalentAddressValues(Value *A, Value *B) {
11771 // Test if the values are trivially equivalent.
11772 if (A == B) return true;
11773
11774 // Test if the values come form identical arithmetic instructions.
11775 if (isa<BinaryOperator>(A) ||
11776 isa<CastInst>(A) ||
11777 isa<PHINode>(A) ||
11778 isa<GetElementPtrInst>(A))
11779 if (Instruction *BI = dyn_cast<Instruction>(B))
11780 if (cast<Instruction>(A)->isIdenticalTo(BI))
11781 return true;
11782
11783 // Otherwise they may not be equivalent.
11784 return false;
11785}
11786
Dale Johannesen4945c652009-03-03 21:26:39 +000011787// If this instruction has two uses, one of which is a llvm.dbg.declare,
11788// return the llvm.dbg.declare.
11789DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11790 if (!V->hasNUses(2))
11791 return 0;
11792 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11793 UI != E; ++UI) {
11794 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11795 return DI;
11796 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11797 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11798 return DI;
11799 }
11800 }
11801 return 0;
11802}
11803
Chris Lattner2f503e62005-01-31 05:36:43 +000011804Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11805 Value *Val = SI.getOperand(0);
11806 Value *Ptr = SI.getOperand(1);
11807
11808 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011809 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011810 ++NumCombined;
11811 return 0;
11812 }
Chris Lattner836692d2007-01-15 06:51:56 +000011813
11814 // If the RHS is an alloca with a single use, zapify the store, making the
11815 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011816 // If the RHS is an alloca with a two uses, the other one being a
11817 // llvm.dbg.declare, zapify the store and the declare, making the
11818 // alloca dead. We must do this to prevent declare's from affecting
11819 // codegen.
11820 if (!SI.isVolatile()) {
11821 if (Ptr->hasOneUse()) {
11822 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011823 EraseInstFromFunction(SI);
11824 ++NumCombined;
11825 return 0;
11826 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011827 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11828 if (isa<AllocaInst>(GEP->getOperand(0))) {
11829 if (GEP->getOperand(0)->hasOneUse()) {
11830 EraseInstFromFunction(SI);
11831 ++NumCombined;
11832 return 0;
11833 }
11834 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11835 EraseInstFromFunction(*DI);
11836 EraseInstFromFunction(SI);
11837 ++NumCombined;
11838 return 0;
11839 }
11840 }
11841 }
11842 }
11843 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11844 EraseInstFromFunction(*DI);
11845 EraseInstFromFunction(SI);
11846 ++NumCombined;
11847 return 0;
11848 }
Chris Lattner836692d2007-01-15 06:51:56 +000011849 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011850
Dan Gohman9941f742007-07-20 16:34:21 +000011851 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011852 unsigned KnownAlign =
11853 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011854 if (KnownAlign >
11855 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11856 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011857 SI.setAlignment(KnownAlign);
11858
Dale Johannesenacb51a32009-03-03 01:43:03 +000011859 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011860 // stores to the same location, separated by a few arithmetic operations. This
11861 // situation often occurs with bitfield accesses.
11862 BasicBlock::iterator BBI = &SI;
11863 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11864 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011865 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011866 // Don't count debug info directives, lest they affect codegen,
11867 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11868 // It is necessary for correctness to skip those that feed into a
11869 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011870 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011871 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011872 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011873 continue;
11874 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011875
11876 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11877 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011878 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11879 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011880 ++NumDeadStore;
11881 ++BBI;
11882 EraseInstFromFunction(*PrevSI);
11883 continue;
11884 }
11885 break;
11886 }
11887
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011888 // If this is a load, we have to stop. However, if the loaded value is from
11889 // the pointer we're loading and is producing the pointer we're storing,
11890 // then *this* store is dead (X = load P; store X -> P).
11891 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011892 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11893 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011894 EraseInstFromFunction(SI);
11895 ++NumCombined;
11896 return 0;
11897 }
11898 // Otherwise, this is a load from some other location. Stores before it
11899 // may not be dead.
11900 break;
11901 }
11902
Chris Lattner9ca96412006-02-08 03:25:32 +000011903 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011904 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011905 break;
11906 }
11907
11908
11909 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011910
11911 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011912 if (isa<ConstantPointerNull>(Ptr) &&
11913 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011914 if (!isa<UndefValue>(Val)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000011915 SI.setOperand(0, Context->getUndef(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011916 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011917 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011918 ++NumCombined;
11919 }
11920 return 0; // Do not modify these!
11921 }
11922
11923 // store undef, Ptr -> noop
11924 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011925 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011926 ++NumCombined;
11927 return 0;
11928 }
11929
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011930 // If the pointer destination is a cast, see if we can fold the cast into the
11931 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011932 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011933 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11934 return Res;
11935 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011936 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011937 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11938 return Res;
11939
Chris Lattner408902b2005-09-12 23:23:25 +000011940
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011941 // If this store is the last instruction in the basic block (possibly
11942 // excepting debug info instructions and the pointer bitcasts that feed
11943 // into them), and if the block ends with an unconditional branch, try
11944 // to move it to the successor block.
11945 BBI = &SI;
11946 do {
11947 ++BBI;
11948 } while (isa<DbgInfoIntrinsic>(BBI) ||
11949 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011950 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011951 if (BI->isUnconditional())
11952 if (SimplifyStoreAtEndOfBlock(SI))
11953 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011954
Chris Lattner2f503e62005-01-31 05:36:43 +000011955 return 0;
11956}
11957
Chris Lattner3284d1f2007-04-15 00:07:55 +000011958/// SimplifyStoreAtEndOfBlock - Turn things like:
11959/// if () { *P = v1; } else { *P = v2 }
11960/// into a phi node with a store in the successor.
11961///
Chris Lattner31755a02007-04-15 01:02:18 +000011962/// Simplify things like:
11963/// *P = v1; if () { *P = v2; }
11964/// into a phi node with a store in the successor.
11965///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011966bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11967 BasicBlock *StoreBB = SI.getParent();
11968
11969 // Check to see if the successor block has exactly two incoming edges. If
11970 // so, see if the other predecessor contains a store to the same location.
11971 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011972 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011973
11974 // Determine whether Dest has exactly two predecessors and, if so, compute
11975 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011976 pred_iterator PI = pred_begin(DestBB);
11977 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011978 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011979 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011980 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011981 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011982 return false;
11983
11984 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011985 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011986 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011987 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011988 }
Chris Lattner31755a02007-04-15 01:02:18 +000011989 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011990 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011991
11992 // Bail out if all the relevant blocks aren't distinct (this can happen,
11993 // for example, if SI is in an infinite loop)
11994 if (StoreBB == DestBB || OtherBB == DestBB)
11995 return false;
11996
Chris Lattner31755a02007-04-15 01:02:18 +000011997 // Verify that the other block ends in a branch and is not otherwise empty.
11998 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011999 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012000 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012001 return false;
12002
Chris Lattner31755a02007-04-15 01:02:18 +000012003 // If the other block ends in an unconditional branch, check for the 'if then
12004 // else' case. there is an instruction before the branch.
12005 StoreInst *OtherStore = 0;
12006 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012007 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012008 // Skip over debugging info.
12009 while (isa<DbgInfoIntrinsic>(BBI) ||
12010 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12011 if (BBI==OtherBB->begin())
12012 return false;
12013 --BBI;
12014 }
12015 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012016 OtherStore = dyn_cast<StoreInst>(BBI);
12017 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12018 return false;
12019 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012020 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012021 // destinations is StoreBB, then we have the if/then case.
12022 if (OtherBr->getSuccessor(0) != StoreBB &&
12023 OtherBr->getSuccessor(1) != StoreBB)
12024 return false;
12025
12026 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012027 // if/then triangle. See if there is a store to the same ptr as SI that
12028 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012029 for (;; --BBI) {
12030 // Check to see if we find the matching store.
12031 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12032 if (OtherStore->getOperand(1) != SI.getOperand(1))
12033 return false;
12034 break;
12035 }
Eli Friedman6903a242008-06-13 22:02:12 +000012036 // If we find something that may be using or overwriting the stored
12037 // value, or if we run out of instructions, we can't do the xform.
12038 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012039 BBI == OtherBB->begin())
12040 return false;
12041 }
12042
12043 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012044 // make sure nothing reads or overwrites the stored value in
12045 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012046 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12047 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012048 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012049 return false;
12050 }
12051 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012052
Chris Lattner31755a02007-04-15 01:02:18 +000012053 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012054 Value *MergedVal = OtherStore->getOperand(0);
12055 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012056 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012057 PN->reserveOperandSpace(2);
12058 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012059 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12060 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012061 }
12062
12063 // Advance to a place where it is safe to insert the new store and
12064 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012065 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012066 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12067 OtherStore->isVolatile()), *BBI);
12068
12069 // Nuke the old stores.
12070 EraseInstFromFunction(SI);
12071 EraseInstFromFunction(*OtherStore);
12072 ++NumCombined;
12073 return true;
12074}
12075
Chris Lattner2f503e62005-01-31 05:36:43 +000012076
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012077Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12078 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012079 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012080 BasicBlock *TrueDest;
12081 BasicBlock *FalseDest;
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012082 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012083 !isa<Constant>(X)) {
12084 // Swap Destinations and condition...
12085 BI.setCondition(X);
12086 BI.setSuccessor(0, FalseDest);
12087 BI.setSuccessor(1, TrueDest);
12088 return &BI;
12089 }
12090
Reid Spencere4d87aa2006-12-23 06:05:41 +000012091 // Cannonicalize fcmp_one -> fcmp_oeq
12092 FCmpInst::Predicate FPred; Value *Y;
12093 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012094 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012095 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12096 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12097 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012098 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012099 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012100 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012101 // Swap Destinations and condition...
12102 BI.setCondition(NewSCC);
12103 BI.setSuccessor(0, FalseDest);
12104 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012105 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012106 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012107 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012108 return &BI;
12109 }
12110
12111 // Cannonicalize icmp_ne -> icmp_eq
12112 ICmpInst::Predicate IPred;
12113 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersonc7d2ce72009-07-10 17:35:01 +000012114 TrueDest, FalseDest), *Context))
Reid Spencere4d87aa2006-12-23 06:05:41 +000012115 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12116 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12117 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12118 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012119 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson333c4002009-07-09 23:48:35 +000012120 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Chris Lattner6934a042007-02-11 01:23:03 +000012121 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012122 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012123 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012124 BI.setSuccessor(0, FalseDest);
12125 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012126 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012127 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012128 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012129 return &BI;
12130 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012131
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012132 return 0;
12133}
Chris Lattner0864acf2002-11-04 16:18:53 +000012134
Chris Lattner46238a62004-07-03 00:26:11 +000012135Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12136 Value *Cond = SI.getCondition();
12137 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12138 if (I->getOpcode() == Instruction::Add)
12139 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12140 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12141 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012142 SI.setOperand(i,
12143 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012144 AddRHS));
12145 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012146 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012147 return &SI;
12148 }
12149 }
12150 return 0;
12151}
12152
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012153Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012154 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012155
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012156 if (!EV.hasIndices())
12157 return ReplaceInstUsesWith(EV, Agg);
12158
12159 if (Constant *C = dyn_cast<Constant>(Agg)) {
12160 if (isa<UndefValue>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012161 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012162
12163 if (isa<ConstantAggregateZero>(C))
Owen Andersond672ecb2009-07-03 00:17:18 +000012164 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012165
12166 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12167 // Extract the element indexed by the first index out of the constant
12168 Value *V = C->getOperand(*EV.idx_begin());
12169 if (EV.getNumIndices() > 1)
12170 // Extract the remaining indices out of the constant indexed by the
12171 // first index
12172 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12173 else
12174 return ReplaceInstUsesWith(EV, V);
12175 }
12176 return 0; // Can't handle other constants
12177 }
12178 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12179 // We're extracting from an insertvalue instruction, compare the indices
12180 const unsigned *exti, *exte, *insi, *inse;
12181 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12182 exte = EV.idx_end(), inse = IV->idx_end();
12183 exti != exte && insi != inse;
12184 ++exti, ++insi) {
12185 if (*insi != *exti)
12186 // The insert and extract both reference distinctly different elements.
12187 // This means the extract is not influenced by the insert, and we can
12188 // replace the aggregate operand of the extract with the aggregate
12189 // operand of the insert. i.e., replace
12190 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12191 // %E = extractvalue { i32, { i32 } } %I, 0
12192 // with
12193 // %E = extractvalue { i32, { i32 } } %A, 0
12194 return ExtractValueInst::Create(IV->getAggregateOperand(),
12195 EV.idx_begin(), EV.idx_end());
12196 }
12197 if (exti == exte && insi == inse)
12198 // Both iterators are at the end: Index lists are identical. Replace
12199 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12200 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12201 // with "i32 42"
12202 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12203 if (exti == exte) {
12204 // The extract list is a prefix of the insert list. i.e. replace
12205 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12206 // %E = extractvalue { i32, { i32 } } %I, 1
12207 // with
12208 // %X = extractvalue { i32, { i32 } } %A, 1
12209 // %E = insertvalue { i32 } %X, i32 42, 0
12210 // by switching the order of the insert and extract (though the
12211 // insertvalue should be left in, since it may have other uses).
12212 Value *NewEV = InsertNewInstBefore(
12213 ExtractValueInst::Create(IV->getAggregateOperand(),
12214 EV.idx_begin(), EV.idx_end()),
12215 EV);
12216 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12217 insi, inse);
12218 }
12219 if (insi == inse)
12220 // The insert list is a prefix of the extract list
12221 // We can simply remove the common indices from the extract and make it
12222 // operate on the inserted value instead of the insertvalue result.
12223 // i.e., replace
12224 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12225 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12226 // with
12227 // %E extractvalue { i32 } { i32 42 }, 0
12228 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12229 exti, exte);
12230 }
12231 // Can't simplify extracts from other values. Note that nested extracts are
12232 // already simplified implicitely by the above (extract ( extract (insert) )
12233 // will be translated into extract ( insert ( extract ) ) first and then just
12234 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012235 return 0;
12236}
12237
Chris Lattner220b0cf2006-03-05 00:22:33 +000012238/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12239/// is to leave as a vector operation.
12240static bool CheapToScalarize(Value *V, bool isConstant) {
12241 if (isa<ConstantAggregateZero>(V))
12242 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012243 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012244 if (isConstant) return true;
12245 // If all elts are the same, we can extract.
12246 Constant *Op0 = C->getOperand(0);
12247 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12248 if (C->getOperand(i) != Op0)
12249 return false;
12250 return true;
12251 }
12252 Instruction *I = dyn_cast<Instruction>(V);
12253 if (!I) return false;
12254
12255 // Insert element gets simplified to the inserted element or is deleted if
12256 // this is constant idx extract element and its a constant idx insertelt.
12257 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12258 isa<ConstantInt>(I->getOperand(2)))
12259 return true;
12260 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12261 return true;
12262 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12263 if (BO->hasOneUse() &&
12264 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12265 CheapToScalarize(BO->getOperand(1), isConstant)))
12266 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012267 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12268 if (CI->hasOneUse() &&
12269 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12270 CheapToScalarize(CI->getOperand(1), isConstant)))
12271 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012272
12273 return false;
12274}
12275
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012276/// Read and decode a shufflevector mask.
12277///
12278/// It turns undef elements into values that are larger than the number of
12279/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012280static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12281 unsigned NElts = SVI->getType()->getNumElements();
12282 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12283 return std::vector<unsigned>(NElts, 0);
12284 if (isa<UndefValue>(SVI->getOperand(2)))
12285 return std::vector<unsigned>(NElts, 2*NElts);
12286
12287 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012288 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012289 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12290 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012291 Result.push_back(NElts*2); // undef -> 8
12292 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012293 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012294 return Result;
12295}
12296
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012297/// FindScalarElement - Given a vector and an element number, see if the scalar
12298/// value is already around as a register, for example if it were inserted then
12299/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012300static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012301 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012302 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12303 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012304 unsigned Width = PTy->getNumElements();
12305 if (EltNo >= Width) // Out of range access.
Owen Andersond672ecb2009-07-03 00:17:18 +000012306 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012307
12308 if (isa<UndefValue>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012309 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012310 else if (isa<ConstantAggregateZero>(V))
Owen Andersond672ecb2009-07-03 00:17:18 +000012311 return Context->getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012312 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012313 return CP->getOperand(EltNo);
12314 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12315 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012316 if (!isa<ConstantInt>(III->getOperand(2)))
12317 return 0;
12318 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012319
12320 // If this is an insert to the element we are looking for, return the
12321 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012322 if (EltNo == IIElt)
12323 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012324
12325 // Otherwise, the insertelement doesn't modify the value, recurse on its
12326 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012327 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012328 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012329 unsigned LHSWidth =
12330 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012331 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012332 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012333 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012334 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012335 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012336 else
Owen Andersond672ecb2009-07-03 00:17:18 +000012337 return Context->getUndef(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012338 }
12339
12340 // Otherwise, we don't know.
12341 return 0;
12342}
12343
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012344Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012345 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012346 if (isa<UndefValue>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012347 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012348
Dan Gohman07a96762007-07-16 14:29:03 +000012349 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012350 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012351 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012352
Reid Spencer9d6565a2007-02-15 02:26:10 +000012353 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012354 // If vector val is constant with all elements the same, replace EI with
12355 // that element. When the elements are not identical, we cannot replace yet
12356 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012357 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012358 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012359 if (C->getOperand(i) != op0) {
12360 op0 = 0;
12361 break;
12362 }
12363 if (op0)
12364 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012365 }
Eli Friedmanfc21f8f2009-07-18 09:07:47 +000012366
12367 unsigned VectorWidth =
12368 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12369
12370 // Canonicalize extractelement from a vector of width 1 to a bitcast
12371 if (VectorWidth == 1)
12372 return new BitCastInst(EI.getOperand(0), EI.getType());
12373
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012374 // If extracting a specified index from the vector, see if we can recursively
12375 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012376 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012377 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner85464092007-04-09 01:37:55 +000012378
12379 // If this is extracting an invalid index, turn this into undef, to avoid
12380 // crashing the code below.
12381 if (IndexVal >= VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012382 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012383
Chris Lattner867b99f2006-10-05 06:55:50 +000012384 // This instruction only demands the single element from the input vector.
12385 // If the input vector has a single use, simplify it based on this use
12386 // property.
Eli Friedmanfc21f8f2009-07-18 09:07:47 +000012387 if (EI.getOperand(0)->hasOneUse()) {
Evan Cheng388df622009-02-03 10:05:09 +000012388 APInt UndefElts(VectorWidth, 0);
12389 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012390 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012391 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012392 EI.setOperand(0, V);
12393 return &EI;
12394 }
12395 }
12396
Owen Andersond672ecb2009-07-03 00:17:18 +000012397 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012398 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012399
12400 // If the this extractelement is directly using a bitcast from a vector of
12401 // the same number of elements, see if we can find the source element from
12402 // it. In this case, we will end up needing to bitcast the scalars.
12403 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12404 if (const VectorType *VT =
12405 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12406 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012407 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12408 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012409 return new BitCastInst(Elt, EI.getType());
12410 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012411 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012412
Chris Lattner73fa49d2006-05-25 22:53:38 +000012413 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012414 if (I->hasOneUse()) {
12415 // Push extractelement into predecessor operation if legal and
12416 // profitable to do so
12417 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012418 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12419 if (CheapToScalarize(BO, isConstantElt)) {
12420 ExtractElementInst *newEI0 =
12421 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12422 EI.getName()+".lhs");
12423 ExtractElementInst *newEI1 =
12424 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12425 EI.getName()+".rhs");
12426 InsertNewInstBefore(newEI0, EI);
12427 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012428 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012429 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012430 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012431 unsigned AS =
12432 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012433 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Andersond672ecb2009-07-03 00:17:18 +000012434 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012435 GetElementPtrInst *GEP =
12436 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012437 InsertNewInstBefore(GEP, EI);
12438 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012439 }
12440 }
12441 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12442 // Extracting the inserted element?
12443 if (IE->getOperand(2) == EI.getOperand(1))
12444 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12445 // If the inserted and extracted elements are constants, they must not
12446 // be the same value, extract from the pre-inserted value instead.
12447 if (isa<Constant>(IE->getOperand(2)) &&
12448 isa<Constant>(EI.getOperand(1))) {
12449 AddUsesToWorkList(EI);
12450 EI.setOperand(0, IE->getOperand(0));
12451 return &EI;
12452 }
12453 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12454 // If this is extracting an element from a shufflevector, figure out where
12455 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012456 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12457 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012458 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012459 unsigned LHSWidth =
12460 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12461
12462 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012463 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012464 else if (SrcIdx < LHSWidth*2) {
12465 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012466 Src = SVI->getOperand(1);
12467 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012468 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012469 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000012470 return new ExtractElementInst(Src,
12471 Context->getConstantInt(Type::Int32Ty, SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012472 }
12473 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012474 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012475 return 0;
12476}
12477
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012478/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12479/// elements from either LHS or RHS, return the shuffle mask and true.
12480/// Otherwise, return false.
12481static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012482 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012483 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012484 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12485 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012486 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012487
12488 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012489 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012490 return true;
12491 } else if (V == LHS) {
12492 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012493 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012494 return true;
12495 } else if (V == RHS) {
12496 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012497 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012498 return true;
12499 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12500 // If this is an insert of an extract from some other vector, include it.
12501 Value *VecOp = IEI->getOperand(0);
12502 Value *ScalarOp = IEI->getOperand(1);
12503 Value *IdxOp = IEI->getOperand(2);
12504
Chris Lattnerd929f062006-04-27 21:14:21 +000012505 if (!isa<ConstantInt>(IdxOp))
12506 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012507 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012508
12509 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12510 // Okay, we can handle this if the vector we are insertinting into is
12511 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012512 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012513 // If so, update the mask to reflect the inserted undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012514 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012515 return true;
12516 }
12517 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12518 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012519 EI->getOperand(0)->getType() == V->getType()) {
12520 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012521 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012522
12523 // This must be extracting from either LHS or RHS.
12524 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12525 // Okay, we can handle this if the vector we are insertinting into is
12526 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012527 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012528 // If so, update the mask to reflect the inserted value.
12529 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012530 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012531 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012532 } else {
12533 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012534 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012535 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012536
12537 }
12538 return true;
12539 }
12540 }
12541 }
12542 }
12543 }
12544 // TODO: Handle shufflevector here!
12545
12546 return false;
12547}
12548
12549/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12550/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12551/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012552static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012553 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012554 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012555 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012556 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012557 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012558
12559 if (isa<UndefValue>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012560 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012561 return V;
12562 } else if (isa<ConstantAggregateZero>(V)) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012563 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012564 return V;
12565 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12566 // If this is an insert of an extract from some other vector, include it.
12567 Value *VecOp = IEI->getOperand(0);
12568 Value *ScalarOp = IEI->getOperand(1);
12569 Value *IdxOp = IEI->getOperand(2);
12570
12571 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12572 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12573 EI->getOperand(0)->getType() == V->getType()) {
12574 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012575 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12576 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012577
12578 // Either the extracted from or inserted into vector must be RHSVec,
12579 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012580 if (EI->getOperand(0) == RHS || RHS == 0) {
12581 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012582 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012583 Mask[InsertedIdx % NumElts] =
Owen Andersond672ecb2009-07-03 00:17:18 +000012584 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012585 return V;
12586 }
12587
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012588 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012589 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12590 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012591 // Everything but the extracted element is replaced with the RHS.
12592 for (unsigned i = 0; i != NumElts; ++i) {
12593 if (i != InsertedIdx)
Owen Andersond672ecb2009-07-03 00:17:18 +000012594 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012595 }
12596 return V;
12597 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012598
12599 // If this insertelement is a chain that comes from exactly these two
12600 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012601 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12602 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012603 return EI->getOperand(0);
12604
Chris Lattnerefb47352006-04-15 01:39:45 +000012605 }
12606 }
12607 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012608 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012609
12610 // Otherwise, can't do anything fancy. Return an identity vector.
12611 for (unsigned i = 0; i != NumElts; ++i)
Owen Andersond672ecb2009-07-03 00:17:18 +000012612 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012613 return V;
12614}
12615
12616Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12617 Value *VecOp = IE.getOperand(0);
12618 Value *ScalarOp = IE.getOperand(1);
12619 Value *IdxOp = IE.getOperand(2);
12620
Chris Lattner599ded12007-04-09 01:11:16 +000012621 // Inserting an undef or into an undefined place, remove this.
12622 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12623 ReplaceInstUsesWith(IE, VecOp);
Eli Friedmanfc21f8f2009-07-18 09:07:47 +000012624
12625 unsigned NumVectorElts = IE.getType()->getNumElements();
12626
12627 // Canonicalize insertelement into vector of width 1 to a bitcast
12628 if (NumVectorElts == 1)
12629 return new BitCastInst(IE.getOperand(1), IE.getType());
12630
Chris Lattnerefb47352006-04-15 01:39:45 +000012631 // If the inserted element was extracted from some other vector, and if the
12632 // indexes are constant, try to turn this into a shufflevector operation.
12633 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12634 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12635 EI->getOperand(0)->getType() == IE.getType()) {
Chris Lattnere34e9a22007-04-14 23:32:02 +000012636 unsigned ExtractedIdx =
12637 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012638 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012639
12640 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12641 return ReplaceInstUsesWith(IE, VecOp);
12642
12643 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Andersond672ecb2009-07-03 00:17:18 +000012644 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012645
12646 // If we are extracting a value from a vector, then inserting it right
12647 // back into the same place, just use the input vector.
12648 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12649 return ReplaceInstUsesWith(IE, VecOp);
12650
12651 // We could theoretically do this for ANY input. However, doing so could
12652 // turn chains of insertelement instructions into a chain of shufflevector
12653 // instructions, and right now we do not merge shufflevectors. As such,
12654 // only do this in a situation where it is clear that there is benefit.
12655 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12656 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12657 // the values of VecOp, except then one read from EIOp0.
12658 // Build a new shuffle mask.
12659 std::vector<Constant*> Mask;
12660 if (isa<UndefValue>(VecOp))
Owen Andersond672ecb2009-07-03 00:17:18 +000012661 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012662 else {
12663 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Andersond672ecb2009-07-03 00:17:18 +000012664 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012665 NumVectorElts));
12666 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012667 Mask[InsertedIdx] =
12668 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012669 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersond672ecb2009-07-03 00:17:18 +000012670 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012671 }
12672
12673 // If this insertelement isn't used by some other insertelement, turn it
12674 // (and any insertelements it points to), into one big shuffle.
12675 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12676 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012677 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012678 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12679 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012680 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012681 return new ShuffleVectorInst(LHS, RHS,
12682 Context->getConstantVector(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012683 }
12684 }
12685 }
12686
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012687 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12688 APInt UndefElts(VWidth, 0);
12689 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12690 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12691 return &IE;
12692
Chris Lattnerefb47352006-04-15 01:39:45 +000012693 return 0;
12694}
12695
12696
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012697Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12698 Value *LHS = SVI.getOperand(0);
12699 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012700 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012701
12702 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012703
Chris Lattner867b99f2006-10-05 06:55:50 +000012704 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012705 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Andersond672ecb2009-07-03 00:17:18 +000012706 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012707
Dan Gohman488fbfc2008-09-09 18:11:14 +000012708 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012709
12710 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12711 return 0;
12712
Evan Cheng388df622009-02-03 10:05:09 +000012713 APInt UndefElts(VWidth, 0);
12714 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12715 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012716 LHS = SVI.getOperand(0);
12717 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012718 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012719 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012720
Chris Lattner863bcff2006-05-25 23:48:38 +000012721 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12722 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12723 if (LHS == RHS || isa<UndefValue>(LHS)) {
12724 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012725 // shuffle(undef,undef,mask) -> undef.
12726 return ReplaceInstUsesWith(SVI, LHS);
12727 }
12728
Chris Lattner863bcff2006-05-25 23:48:38 +000012729 // Remap any references to RHS to use LHS.
12730 std::vector<Constant*> Elts;
12731 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012732 if (Mask[i] >= 2*e)
Owen Andersond672ecb2009-07-03 00:17:18 +000012733 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012734 else {
12735 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012736 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012737 Mask[i] = 2*e; // Turn into undef.
Owen Andersond672ecb2009-07-03 00:17:18 +000012738 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohman4ce96272008-08-06 18:17:32 +000012739 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012740 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Andersond672ecb2009-07-03 00:17:18 +000012741 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012742 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012743 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012744 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012745 SVI.setOperand(0, SVI.getOperand(1));
Owen Andersond672ecb2009-07-03 00:17:18 +000012746 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12747 SVI.setOperand(2, Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012748 LHS = SVI.getOperand(0);
12749 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012750 MadeChange = true;
12751 }
12752
Chris Lattner7b2e27922006-05-26 00:29:06 +000012753 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012754 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012755
Chris Lattner863bcff2006-05-25 23:48:38 +000012756 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12757 if (Mask[i] >= e*2) continue; // Ignore undef values.
12758 // Is this an identity shuffle of the LHS value?
12759 isLHSID &= (Mask[i] == i);
12760
12761 // Is this an identity shuffle of the RHS value?
12762 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012763 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012764
Chris Lattner863bcff2006-05-25 23:48:38 +000012765 // Eliminate identity shuffles.
12766 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12767 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012768
Chris Lattner7b2e27922006-05-26 00:29:06 +000012769 // If the LHS is a shufflevector itself, see if we can combine it with this
12770 // one without producing an unusual shuffle. Here we are really conservative:
12771 // we are absolutely afraid of producing a shuffle mask not in the input
12772 // program, because the code gen may not be smart enough to turn a merged
12773 // shuffle into two specific shuffles: it may produce worse code. As such,
12774 // we only merge two shuffles if the result is one of the two input shuffle
12775 // masks. In this case, merging the shuffles just removes one instruction,
12776 // which we know is safe. This is good for things like turning:
12777 // (splat(splat)) -> splat.
12778 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12779 if (isa<UndefValue>(RHS)) {
12780 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12781
12782 std::vector<unsigned> NewMask;
12783 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12784 if (Mask[i] >= 2*e)
12785 NewMask.push_back(2*e);
12786 else
12787 NewMask.push_back(LHSMask[Mask[i]]);
12788
12789 // If the result mask is equal to the src shuffle or this shuffle mask, do
12790 // the replacement.
12791 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012792 unsigned LHSInNElts =
12793 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012794 std::vector<Constant*> Elts;
12795 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012796 if (NewMask[i] >= LHSInNElts*2) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012797 Elts.push_back(Context->getUndef(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012798 } else {
Owen Andersond672ecb2009-07-03 00:17:18 +000012799 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012800 }
12801 }
12802 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12803 LHSSVI->getOperand(1),
Owen Andersond672ecb2009-07-03 00:17:18 +000012804 Context->getConstantVector(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012805 }
12806 }
12807 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012808
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012809 return MadeChange ? &SVI : 0;
12810}
12811
12812
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012813
Chris Lattnerea1c4542004-12-08 23:43:58 +000012814
12815/// TryToSinkInstruction - Try to move the specified instruction from its
12816/// current block into the beginning of DestBlock, which can only happen if it's
12817/// safe to move the instruction past all of the instructions between it and the
12818/// end of its block.
12819static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12820 assert(I->hasOneUse() && "Invariants didn't hold!");
12821
Chris Lattner108e9022005-10-27 17:13:11 +000012822 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012823 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012824 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012825
Chris Lattnerea1c4542004-12-08 23:43:58 +000012826 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012827 if (isa<AllocaInst>(I) && I->getParent() ==
12828 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012829 return false;
12830
Chris Lattner96a52a62004-12-09 07:14:34 +000012831 // We can only sink load instructions if there is nothing between the load and
12832 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012833 if (I->mayReadFromMemory()) {
12834 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012835 Scan != E; ++Scan)
12836 if (Scan->mayWriteToMemory())
12837 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012838 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012839
Dan Gohman02dea8b2008-05-23 21:05:58 +000012840 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012841
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012842 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012843 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012844 ++NumSunkInst;
12845 return true;
12846}
12847
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012848
12849/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12850/// all reachable code to the worklist.
12851///
12852/// This has a couple of tricks to make the code faster and more powerful. In
12853/// particular, we constant fold and DCE instructions as we go, to avoid adding
12854/// them to the worklist (this significantly speeds up instcombine on code where
12855/// many instructions are dead or constant). Additionally, if we find a branch
12856/// whose condition is a known constant, we only visit the reachable successors.
12857///
12858static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012859 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012860 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012861 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012862 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012863 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012864
Chris Lattner2c7718a2007-03-23 19:17:18 +000012865 while (!Worklist.empty()) {
12866 BB = Worklist.back();
12867 Worklist.pop_back();
12868
12869 // We have now visited this block! If we've already been here, ignore it.
12870 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012871
12872 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012873 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12874 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012875
Chris Lattner2c7718a2007-03-23 19:17:18 +000012876 // DCE instruction if trivially dead.
12877 if (isInstructionTriviallyDead(Inst)) {
12878 ++NumDeadInst;
12879 DOUT << "IC: DCE: " << *Inst;
12880 Inst->eraseFromParent();
12881 continue;
12882 }
12883
12884 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012885 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000012886 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12887 Inst->replaceAllUsesWith(C);
12888 ++NumConstProp;
12889 Inst->eraseFromParent();
12890 continue;
12891 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012892
Devang Patel7fe1dec2008-11-19 18:56:50 +000012893 // If there are two consecutive llvm.dbg.stoppoint calls then
12894 // it is likely that the optimizer deleted code in between these
12895 // two intrinsics.
12896 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12897 if (DBI_Next) {
12898 if (DBI_Prev
12899 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12900 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12901 IC.RemoveFromWorkList(DBI_Prev);
12902 DBI_Prev->eraseFromParent();
12903 }
12904 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012905 } else {
12906 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012907 }
12908
Chris Lattner2c7718a2007-03-23 19:17:18 +000012909 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012910 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012911
12912 // Recursively visit successors. If this is a branch or switch on a
12913 // constant, only visit the reachable successor.
12914 TerminatorInst *TI = BB->getTerminator();
12915 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12916 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12917 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012918 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012919 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012920 continue;
12921 }
12922 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12923 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12924 // See if this is an explicit destination.
12925 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12926 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012927 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012928 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012929 continue;
12930 }
12931
12932 // Otherwise it is the default destination.
12933 Worklist.push_back(SI->getSuccessor(0));
12934 continue;
12935 }
12936 }
12937
12938 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12939 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012940 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012941}
12942
Chris Lattnerec9c3582007-03-03 02:04:50 +000012943bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012944 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012945 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012946
12947 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12948 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012949
Chris Lattnerb3d59702005-07-07 20:40:38 +000012950 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012951 // Do a depth-first traversal of the function, populate the worklist with
12952 // the reachable instructions. Ignore blocks that are not reachable. Keep
12953 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012954 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012955 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012956
Chris Lattnerb3d59702005-07-07 20:40:38 +000012957 // Do a quick scan over the function. If we find any blocks that are
12958 // unreachable, remove any instructions inside of them. This prevents
12959 // the instcombine code from having to deal with some bad special cases.
12960 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12961 if (!Visited.count(BB)) {
12962 Instruction *Term = BB->getTerminator();
12963 while (Term != BB->begin()) { // Remove instrs bottom-up
12964 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012965
Bill Wendlingb7427032006-11-26 09:46:52 +000012966 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012967 // A debug intrinsic shouldn't force another iteration if we weren't
12968 // going to do one without it.
12969 if (!isa<DbgInfoIntrinsic>(I)) {
12970 ++NumDeadInst;
12971 Changed = true;
12972 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012973 if (!I->use_empty())
Owen Andersond672ecb2009-07-03 00:17:18 +000012974 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012975 I->eraseFromParent();
12976 }
12977 }
12978 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012979
Chris Lattnerdbab3862007-03-02 21:28:56 +000012980 while (!Worklist.empty()) {
12981 Instruction *I = RemoveOneFromWorkList();
12982 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012983
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012984 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012985 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012986 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012987 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012988 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012989 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012990
Bill Wendlingb7427032006-11-26 09:46:52 +000012991 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012992
12993 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012994 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012995 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012996 continue;
12997 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012998
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012999 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000013000 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013001 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000013002
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013003 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000013004 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000013005 ReplaceInstUsesWith(*I, C);
13006
Chris Lattner62b14df2002-09-02 04:59:56 +000013007 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013008 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013009 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000013010 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013011 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000013012 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013013
Eli Friedmanfd2934f2009-07-15 22:13:34 +000013014 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013015 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000013016 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13017 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000013018 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13019 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000013020 if (NewC != CE) {
13021 i->set(NewC);
13022 Changed = true;
13023 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000013024 }
13025
Chris Lattnerea1c4542004-12-08 23:43:58 +000013026 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013027 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013028 BasicBlock *BB = I->getParent();
13029 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13030 if (UserParent != BB) {
13031 bool UserIsSuccessor = false;
13032 // See if the user is one of our successors.
13033 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13034 if (*SI == UserParent) {
13035 UserIsSuccessor = true;
13036 break;
13037 }
13038
13039 // If the user is one of our immediate successors, and if that successor
13040 // only has us as a predecessors (we'd have to split the critical edge
13041 // otherwise), we can keep going.
13042 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13043 next(pred_begin(UserParent)) == pred_end(UserParent))
13044 // Okay, the CFG is simple enough, try to sink this instruction.
13045 Changed |= TryToSinkInstruction(I, UserParent);
13046 }
13047 }
13048
Chris Lattner8a2a3112001-12-14 16:52:21 +000013049 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000013050#ifndef NDEBUG
13051 std::string OrigI;
13052#endif
13053 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000013054 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013055 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013056 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013057 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000013058 DOUT << "IC: Old = " << *I
13059 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000013060
Chris Lattnerf523d062004-06-09 05:08:07 +000013061 // Everything uses the new instruction now.
13062 I->replaceAllUsesWith(Result);
13063
13064 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013065 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000013066 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013067
Chris Lattner6934a042007-02-11 01:23:03 +000013068 // Move the name to the new instruction first.
13069 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013070
13071 // Insert the new instruction into the basic block...
13072 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013073 BasicBlock::iterator InsertPos = I;
13074
13075 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13076 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13077 ++InsertPos;
13078
13079 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013080
Chris Lattner00d51312004-05-01 23:27:23 +000013081 // Make sure that we reprocess all operands now that we reduced their
13082 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013083 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000013084
Chris Lattnerf523d062004-06-09 05:08:07 +000013085 // Instructions can end up on the worklist more than once. Make sure
13086 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013087 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013088
13089 // Erase the old instruction.
13090 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000013091 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013092#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000013093 DOUT << "IC: Mod = " << OrigI
13094 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000013095#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013096
Chris Lattner90ac28c2002-08-02 19:29:35 +000013097 // If the instruction was modified, it's possible that it is now dead.
13098 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013099 if (isInstructionTriviallyDead(I)) {
13100 // Make sure we process all operands now that we are reducing their
13101 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000013102 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000013103
Chris Lattner00d51312004-05-01 23:27:23 +000013104 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013105 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000013106 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000013107 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000013108 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000013109 AddToWorkList(I);
13110 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013111 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013112 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013113 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013114 }
13115 }
13116
Chris Lattnerec9c3582007-03-03 02:04:50 +000013117 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013118
13119 // Do an explicit clear, this shrinks the map if needed.
13120 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013121 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013122}
13123
Chris Lattnerec9c3582007-03-03 02:04:50 +000013124
13125bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013126 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13127
Chris Lattnerec9c3582007-03-03 02:04:50 +000013128 bool EverMadeChange = false;
13129
13130 // Iterate while there is work to do.
13131 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013132 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013133 EverMadeChange = true;
13134 return EverMadeChange;
13135}
13136
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013137FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013138 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013139}