blob: bf287f2c680877484e6280152c8bc355d2376747 [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"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000061#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000062#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000063using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000064using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000065
Chris Lattner0e5f4992006-12-19 21:40:18 +000066STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000073 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 // Worklist of all of the instructions that need to be simplified.
Chris Lattner2806dff2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Chris Lattnerdbab3862007-03-02 21:28:56 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000079 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000080 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000081 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000082 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000084
Chris Lattnerdbab3862007-03-02 21:28:56 +000085 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman6b345ee2008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Chris Lattnerdbab3862007-03-02 21:28:56 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000109
Chris Lattnerdbab3862007-03-02 21:28:56 +0000110
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000115 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000118 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000119 }
120
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif177dd3f2008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000127 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000128 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif177dd3f2008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000141 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000142 // Set the operand to undef to drop the use.
Gabor Greif177dd3f2008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +0000144 }
145
146 return R;
147 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000148
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000149 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000150 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000151
152 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153
Chris Lattner97e52e42002-04-28 21:27:06 +0000154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000155 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000156 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000157 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000158 }
159
Chris Lattner28977af2004-04-05 01:30:19 +0000160 TargetData &getTargetData() const { return *TD; }
161
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000166 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000167 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000168 //
Chris Lattner7e708292002-06-25 16:13:24 +0000169 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000170 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000171 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000172 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000173 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000174 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000175 Instruction *visitURem(BinaryOperator &I);
176 Instruction *visitSRem(BinaryOperator &I);
177 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000178 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000179 Instruction *commonRemTransforms(BinaryOperator &I);
180 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000181 Instruction *commonDivTransforms(BinaryOperator &I);
182 Instruction *commonIDivTransforms(BinaryOperator &I);
183 Instruction *visitUDiv(BinaryOperator &I);
184 Instruction *visitSDiv(BinaryOperator &I);
185 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000186 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000187 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000188 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000189 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000190 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000191 Instruction *visitOr (BinaryOperator &I);
192 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000193 Instruction *visitShl(BinaryOperator &I);
194 Instruction *visitAShr(BinaryOperator &I);
195 Instruction *visitLShr(BinaryOperator &I);
196 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000197 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
198 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Instruction *visitFCmpInst(FCmpInst &I);
200 Instruction *visitICmpInst(ICmpInst &I);
201 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000202 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
203 Instruction *LHS,
204 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000205 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000207
Reid Spencere4d87aa2006-12-23 06:05:41 +0000208 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000210 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000211 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000212 Instruction *commonCastTransforms(CastInst &CI);
213 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000214 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000215 Instruction *visitTrunc(TruncInst &CI);
216 Instruction *visitZExt(ZExtInst &CI);
217 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000218 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000220 Instruction *visitFPToUI(FPToUIInst &FI);
221 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000222 Instruction *visitUIToFP(CastInst &CI);
223 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000224 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000225 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000226 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000227 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
228 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000229 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000230 Instruction *visitSelectInst(SelectInst &SI);
231 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000232 Instruction *visitCallInst(CallInst &CI);
233 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitPHINode(PHINode &PN);
235 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000236 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000237 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000238 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000239 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000240 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000241 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000242 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000243 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000244 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000245 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000246
247 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000248 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000249
Chris Lattner9fe38862003-06-19 17:00:31 +0000250 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000251 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000252 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000253 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000254 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000256 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000257 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
258
Chris Lattner9fe38862003-06-19 17:00:31 +0000259
Chris Lattner28977af2004-04-05 01:30:19 +0000260 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000261 // InsertNewInstBefore - insert an instruction New before instruction Old
262 // in the program. Add the new instruction to the worklist.
263 //
Chris Lattner955f3312004-09-28 21:48:02 +0000264 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000265 assert(New && New->getParent() == 0 &&
266 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000267 BasicBlock *BB = Old.getParent();
268 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000269 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000270 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000271 }
272
Chris Lattner0c967662004-09-24 15:21:34 +0000273 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274 /// This also adds the cast to the worklist. Finally, this returns the
275 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000276 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
277 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000278 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000279
Chris Lattnere2ed0572006-04-06 19:19:17 +0000280 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000281 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000282
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000283 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000284 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000285 return C;
286 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000287
288 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
290 }
291
Chris Lattner0c967662004-09-24 15:21:34 +0000292
Chris Lattner8b170942002-08-09 23:47:40 +0000293 // ReplaceInstUsesWith - This method is to be used when an instruction is
294 // found to be dead, replacable with another preexisting expression. Here
295 // we add all uses of I to the worklist, replace all uses of I with the new
296 // value, then return I, so that the inst combiner will know that I was
297 // modified.
298 //
299 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000300 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000301 if (&I != V) {
302 I.replaceAllUsesWith(V);
303 return &I;
304 } else {
305 // If we are replacing the instruction with itself, this must be in a
306 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000307 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000308 return &I;
309 }
Chris Lattner8b170942002-08-09 23:47:40 +0000310 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000311
312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000319 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000320 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000321 return 0; // Don't do anything with FI
322 }
Chris Lattner173234a2008-06-02 01:18:21 +0000323
324 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325 APInt &KnownOne, unsigned Depth = 0) const {
326 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
327 }
328
329 bool MaskedValueIsZero(Value *V, const APInt &Mask,
330 unsigned Depth = 0) const {
331 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
332 }
333 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334 return llvm::ComputeNumSignBits(Op, TD, Depth);
335 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000336
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000337 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000338
Reid Spencere4d87aa2006-12-23 06:05:41 +0000339 /// SimplifyCommutative - This performs a few simplifications for
340 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000341 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000342
Reid Spencere4d87aa2006-12-23 06:05:41 +0000343 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344 /// most-complex to least-complex order.
345 bool SimplifyCompare(CmpInst &I);
346
Chris Lattner886ab6c2009-01-31 08:15:18 +0000347 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348 /// based on the demanded bits.
349 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
350 APInt& KnownZero, APInt& KnownOne,
351 unsigned Depth);
352 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000353 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000354 unsigned Depth=0);
355
356 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357 /// SimplifyDemandedBits knows about. See if the instruction has any
358 /// properties that allow us to simplify its operands.
359 bool SimplifyDemandedInstructionBits(Instruction &Inst);
360
Evan Cheng388df622009-02-03 10:05:09 +0000361 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000363
Chris Lattner4e998b22004-09-29 05:07:12 +0000364 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365 // PHI node as operand #0, see if we can fold the instruction into the PHI
366 // (which is only possible if all operands to the PHI are constants).
367 Instruction *FoldOpIntoPhi(Instruction &I);
368
Chris Lattnerbac32862004-11-14 19:13:23 +0000369 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370 // operator and they all are only used by the PHI, PHI together their
371 // inputs, and do the operation once, to the result of the PHI.
372 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000373 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000374 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
375
Chris Lattner7da52b22006-11-01 04:51:18 +0000376
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000377 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000379
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000380 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000381 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000382 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000383 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000384 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000385 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000386 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000387 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000388 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000389
Chris Lattnerafe91a52006-06-15 19:07:26 +0000390
Reid Spencerc55b2432006-12-13 18:21:21 +0000391 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000392
Dan Gohman6de29f82009-06-15 22:12:54 +0000393 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000394 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000395 unsigned GetOrEnforceKnownAlignment(Value *V,
396 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000397
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000398 };
399}
400
Dan Gohman844731a2008-05-13 00:00:25 +0000401char InstCombiner::ID = 0;
402static RegisterPass<InstCombiner>
403X("instcombine", "Combine redundant instructions");
404
Chris Lattner4f98c562003-03-10 21:43:22 +0000405// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000406// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000407static unsigned getComplexity(Value *V) {
408 if (isa<Instruction>(V)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000409 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000411 return 3;
412 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000413 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000414 if (isa<Argument>(V)) return 3;
415 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000416}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000417
Chris Lattnerc8802d22003-03-11 00:12:48 +0000418// isOnlyUse - Return true if this instruction will be deleted if we stop using
419// it.
420static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000421 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000422}
423
Chris Lattner4cb170c2004-02-23 06:38:22 +0000424// getPromotedType - Return the specified type promoted as it would be to pass
425// though a va_arg area...
426static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000427 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428 if (ITy->getBitWidth() < 32)
429 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000430 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000431 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000432}
433
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000434/// getBitCastOperand - If the specified operand is a CastInst, a constant
435/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000439 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000440 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000441 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442 // GetElementPtrInst?
443 if (GEP->hasAllZeroIndices())
444 return GEP->getOperand(0);
445 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000446 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000447 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000448 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000449 else if (CE->getOpcode() == Instruction::GetElementPtr) {
450 // GetElementPtr ConstantExp?
451 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452 I != E; ++I) {
453 ConstantInt *CI = dyn_cast<ConstantInt>(I);
454 if (!CI || !CI->isZero())
455 // Any non-zero indices? Not cast-like.
456 return 0;
457 }
458 // All-zero indices? This is just like casting.
459 return CE->getOperand(0);
460 }
461 }
Chris Lattnereed48272005-09-13 00:40:14 +0000462 return 0;
463}
464
Reid Spencer3da59db2006-11-27 01:05:10 +0000465/// This function is a wrapper around CastInst::isEliminableCastPair. It
466/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000467static Instruction::CastOps
468isEliminableCastPair(
469 const CastInst *CI, ///< The first cast instruction
470 unsigned opcode, ///< The opcode of the second cast instruction
471 const Type *DstTy, ///< The target type for the second cast instruction
472 TargetData *TD ///< The target data for pointer size
473) {
474
475 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
476 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000477
Reid Spencer3da59db2006-11-27 01:05:10 +0000478 // Get the opcodes of the two Cast instructions
479 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000481
Chris Lattnera0e69692009-03-24 18:35:40 +0000482 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483 DstTy, TD->getIntPtrType());
484
485 // We don't want to form an inttoptr or ptrtoint that converts to an integer
486 // type that differs from the pointer size.
487 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
489 Res = 0;
490
491 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000492}
493
494/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495/// in any code being generated. It does not require codegen if V is simple
496/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000497static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
498 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000499 if (V->getType() == Ty || isa<Constant>(V)) return false;
500
Chris Lattner01575b72006-05-25 23:24:33 +0000501 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000502 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000504 return false;
505 return true;
506}
507
Chris Lattner4f98c562003-03-10 21:43:22 +0000508// SimplifyCommutative - This performs a few simplifications for commutative
509// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000510//
Chris Lattner4f98c562003-03-10 21:43:22 +0000511// 1. Order operands such that they are listed from right (least complex) to
512// left (most complex). This puts constants before unary operators before
513// binary operators.
514//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000515// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000517//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000518bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000519 bool Changed = false;
520 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000522
Chris Lattner4f98c562003-03-10 21:43:22 +0000523 if (!I.isAssociative()) return Changed;
524 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000525 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000528 Constant *Folded = ConstantExpr::get(I.getOpcode(),
529 cast<Constant>(I.getOperand(1)),
530 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 I.setOperand(0, Op->getOperand(0));
532 I.setOperand(1, Folded);
533 return true;
534 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536 isOnlyUse(Op) && isOnlyUse(Op1)) {
537 Constant *C1 = cast<Constant>(Op->getOperand(1));
538 Constant *C2 = cast<Constant>(Op1->getOperand(1));
539
540 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000541 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000542 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000543 Op1->getOperand(0),
544 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000545 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546 I.setOperand(0, New);
547 I.setOperand(1, Folded);
548 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000549 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000550 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000552}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000553
Reid Spencere4d87aa2006-12-23 06:05:41 +0000554/// SimplifyCompare - For a CmpInst this function just orders the operands
555/// so that theyare listed from right (least complex) to left (most complex).
556/// This puts constants before unary operators before binary operators.
557bool InstCombiner::SimplifyCompare(CmpInst &I) {
558 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
559 return false;
560 I.swapOperands();
561 // Compare instructions are not associative so there's nothing else we can do.
562 return true;
563}
564
Chris Lattner8d969642003-03-10 23:06:50 +0000565// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000567//
Chris Lattner8d969642003-03-10 23:06:50 +0000568static inline Value *dyn_castNegVal(Value *V) {
569 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000570 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000571
Chris Lattner0ce85802004-12-14 20:08:06 +0000572 // Constants can be considered to be negated values if they can be folded.
573 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000575
576 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577 if (C->getType()->getElementType()->isInteger())
578 return ConstantExpr::getNeg(C);
579
Chris Lattner8d969642003-03-10 23:06:50 +0000580 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000581}
582
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000583// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584// instruction if the LHS is a constant negative zero (which is the 'negate'
585// form).
586//
587static inline Value *dyn_castFNegVal(Value *V) {
588 if (BinaryOperator::isFNeg(V))
589 return BinaryOperator::getFNegArgument(V);
590
591 // Constants can be considered to be negated values if they can be folded.
592 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593 return ConstantExpr::getFNeg(C);
594
595 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596 if (C->getType()->getElementType()->isFloatingPoint())
597 return ConstantExpr::getFNeg(C);
598
599 return 0;
600}
601
Chris Lattner8d969642003-03-10 23:06:50 +0000602static inline Value *dyn_castNotVal(Value *V) {
603 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000604 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000605
606 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000607 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000608 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000609 return 0;
610}
611
Chris Lattnerc8802d22003-03-11 00:12:48 +0000612// dyn_castFoldableMul - If this value is a multiply that can be folded into
613// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000614// non-constant operand of the multiply, and set CST to point to the multiplier.
615// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000616//
Chris Lattner50af16a2004-11-13 19:50:12 +0000617static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000618 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000619 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000620 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000621 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000622 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000623 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000624 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000626 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000627 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000628 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000629 return I->getOperand(0);
630 }
631 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000632 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000633}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000634
Chris Lattner574da9b2005-01-13 20:14:25 +0000635/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636/// expression, return it.
637static User *dyn_castGetElementPtr(Value *V) {
638 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640 if (CE->getOpcode() == Instruction::GetElementPtr)
641 return cast<User>(V);
642 return false;
643}
644
Dan Gohmaneee962e2008-04-10 18:43:06 +0000645/// getOpcode - If this is an Instruction or a ConstantExpr, return the
646/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000647static unsigned getOpcode(const Value *V) {
648 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000649 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000650 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000651 return CE->getOpcode();
652 // Use UserOp1 to mean there's no opcode.
653 return Instruction::UserOp1;
654}
655
Reid Spencer7177c3a2007-03-25 05:33:51 +0000656/// AddOne - Add one to a ConstantInt
Dan Gohman6de29f82009-06-15 22:12:54 +0000657static Constant *AddOne(Constant *C) {
658 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000659}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000660/// SubOne - Subtract one from a ConstantInt
Dan Gohman6de29f82009-06-15 22:12:54 +0000661static Constant *SubOne(ConstantInt *C) {
662 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000663}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000664/// MultiplyOverflows - True if the multiply can not be expressed in an int
665/// this size.
666static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
667 uint32_t W = C1->getBitWidth();
668 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
669 if (sign) {
670 LHSExt.sext(W * 2);
671 RHSExt.sext(W * 2);
672 } else {
673 LHSExt.zext(W * 2);
674 RHSExt.zext(W * 2);
675 }
676
677 APInt MulExt = LHSExt * RHSExt;
678
679 if (sign) {
680 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
681 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
682 return MulExt.slt(Min) || MulExt.sgt(Max);
683 } else
684 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
685}
Chris Lattner955f3312004-09-28 21:48:02 +0000686
Reid Spencere7816b52007-03-08 01:52:58 +0000687
Chris Lattner255d8912006-02-11 09:31:47 +0000688/// ShrinkDemandedConstant - Check to see if the specified operand of the
689/// specified instruction is a constant integer. If so, check to see if there
690/// are any bits set in the constant that are not demanded. If so, shrink the
691/// constant and return true.
692static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000693 APInt Demanded) {
694 assert(I && "No instruction?");
695 assert(OpNo < I->getNumOperands() && "Operand index too large");
696
697 // If the operand is not a constant integer, nothing to do.
698 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
699 if (!OpC) return false;
700
701 // If there are no bits set that aren't demanded, nothing to do.
702 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
703 if ((~Demanded & OpC->getValue()) == 0)
704 return false;
705
706 // This instruction is producing bits that are not demanded. Shrink the RHS.
707 Demanded &= OpC->getValue();
708 I->setOperand(OpNo, ConstantInt::get(Demanded));
709 return true;
710}
711
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
713// set of known zero and one bits, compute the maximum and minimum values that
714// could have the specified known zero and known one bits, returning them in
715// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000716static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000717 const APInt& KnownOne,
718 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000719 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
720 KnownZero.getBitWidth() == Min.getBitWidth() &&
721 KnownZero.getBitWidth() == Max.getBitWidth() &&
722 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000723 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000724
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000725 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
726 // bit if it is unknown.
727 Min = KnownOne;
728 Max = KnownOne|UnknownBits;
729
Dan Gohman1c8491e2009-04-25 17:12:48 +0000730 if (UnknownBits.isNegative()) { // Sign bit is unknown
731 Min.set(Min.getBitWidth()-1);
732 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000733 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000734}
735
736// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
737// a set of known zero and one bits, compute the maximum and minimum values that
738// could have the specified known zero and known one bits, returning them in
739// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000740static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000741 const APInt &KnownOne,
742 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000743 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
744 KnownZero.getBitWidth() == Min.getBitWidth() &&
745 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000746 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000747 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000748
749 // The minimum value is when the unknown bits are all zeros.
750 Min = KnownOne;
751 // The maximum value is when the unknown bits are all ones.
752 Max = KnownOne|UnknownBits;
753}
Chris Lattner255d8912006-02-11 09:31:47 +0000754
Chris Lattner886ab6c2009-01-31 08:15:18 +0000755/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
756/// SimplifyDemandedBits knows about. See if the instruction has any
757/// properties that allow us to simplify its operands.
758bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000759 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000760 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
761 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
762
763 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
764 KnownZero, KnownOne, 0);
765 if (V == 0) return false;
766 if (V == &Inst) return true;
767 ReplaceInstUsesWith(Inst, V);
768 return true;
769}
770
771/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
772/// specified instruction operand if possible, updating it in place. It returns
773/// true if it made any change and false otherwise.
774bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
775 APInt &KnownZero, APInt &KnownOne,
776 unsigned Depth) {
777 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
778 KnownZero, KnownOne, Depth);
779 if (NewVal == 0) return false;
780 U.set(NewVal);
781 return true;
782}
783
784
785/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
786/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000787/// that only the bits set in DemandedMask of the result of V are ever used
788/// downstream. Consequently, depending on the mask and V, it may be possible
789/// to replace V with a constant or one of its operands. In such cases, this
790/// function does the replacement and returns true. In all other cases, it
791/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000792/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000793/// to be zero in the expression. These are provided to potentially allow the
794/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
795/// the expression. KnownOne and KnownZero always follow the invariant that
796/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
797/// the bits in KnownOne and KnownZero may only be accurate for those bits set
798/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
799/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000800///
801/// This returns null if it did not change anything and it permits no
802/// simplification. This returns V itself if it did some simplification of V's
803/// operands based on the information about what bits are demanded. This returns
804/// some other non-null value if it found out that V is equal to another value
805/// in the context where the specified bits are demanded, but not for all users.
806Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
807 APInt &KnownZero, APInt &KnownOne,
808 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000809 assert(V != 0 && "Null pointer of Value???");
810 assert(Depth <= 6 && "Limit Search Depth");
811 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000812 const Type *VTy = V->getType();
813 assert((TD || !isa<PointerType>(VTy)) &&
814 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000815 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
816 (!VTy->isIntOrIntVector() ||
817 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000818 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000819 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000820 "Value *V, DemandedMask, KnownZero and KnownOne "
821 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000822 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000826 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000828 if (isa<ConstantPointerNull>(V)) {
829 // We know all of the bits for a constant!
830 KnownOne.clear();
831 KnownZero = DemandedMask;
832 return 0;
833 }
834
Chris Lattner08d2cc72009-01-31 07:26:06 +0000835 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000836 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000837 if (DemandedMask == 0) { // Not demanding any bits from V.
838 if (isa<UndefValue>(V))
839 return 0;
840 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000841 }
842
Chris Lattner4598c942009-01-31 08:24:16 +0000843 if (Depth == 6) // Limit search depth.
844 return 0;
845
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000846 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
847 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
848
Dan Gohman1c8491e2009-04-25 17:12:48 +0000849 Instruction *I = dyn_cast<Instruction>(V);
850 if (!I) {
851 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
852 return 0; // Only analyze instructions.
853 }
854
Chris Lattner4598c942009-01-31 08:24:16 +0000855 // If there are multiple uses of this value and we aren't at the root, then
856 // we can't do any simplifications of the operands, because DemandedMask
857 // only reflects the bits demanded by *one* of the users.
858 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000859 // Despite the fact that we can't simplify this instruction in all User's
860 // context, we can at least compute the knownzero/knownone bits, and we can
861 // do simplifications that apply to *just* the one user if we know that
862 // this instruction has a simpler value in that context.
863 if (I->getOpcode() == Instruction::And) {
864 // If either the LHS or the RHS are Zero, the result is zero.
865 ComputeMaskedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1);
867 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
868 LHSKnownZero, LHSKnownOne, Depth+1);
869
870 // If all of the demanded bits are known 1 on one side, return the other.
871 // These bits cannot contribute to the result of the 'and' in this
872 // context.
873 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
874 (DemandedMask & ~LHSKnownZero))
875 return I->getOperand(0);
876 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
877 (DemandedMask & ~RHSKnownZero))
878 return I->getOperand(1);
879
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
882 return Constant::getNullValue(VTy);
883
884 } else if (I->getOpcode() == Instruction::Or) {
885 // We can simplify (X|Y) -> X or Y in the user's context if we know that
886 // only bits from X or Y are demanded.
887
888 // If either the LHS or the RHS are One, the result is One.
889 ComputeMaskedBits(I->getOperand(1), DemandedMask,
890 RHSKnownZero, RHSKnownOne, Depth+1);
891 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
892 LHSKnownZero, LHSKnownOne, Depth+1);
893
894 // If all of the demanded bits are known zero on one side, return the
895 // other. These bits cannot contribute to the result of the 'or' in this
896 // context.
897 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
898 (DemandedMask & ~LHSKnownOne))
899 return I->getOperand(0);
900 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
901 (DemandedMask & ~RHSKnownOne))
902 return I->getOperand(1);
903
904 // If all of the potentially set bits on one side are known to be set on
905 // the other side, just use the 'other' side.
906 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
907 (DemandedMask & (~RHSKnownZero)))
908 return I->getOperand(0);
909 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
910 (DemandedMask & (~LHSKnownZero)))
911 return I->getOperand(1);
912 }
913
Chris Lattner4598c942009-01-31 08:24:16 +0000914 // Compute the KnownZero/KnownOne bits to simplify things downstream.
915 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
916 return 0;
917 }
918
919 // If this is the root being simplified, allow it to have multiple uses,
920 // just set the DemandedMask to all bits so that we can try to simplify the
921 // operands. This allows visitTruncInst (for example) to simplify the
922 // operand of a trunc without duplicating all the logic below.
923 if (Depth == 0 && !V->hasOneUse())
924 DemandedMask = APInt::getAllOnesValue(BitWidth);
925
Reid Spencer8cb68342007-03-12 17:25:59 +0000926 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000927 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000928 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000929 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000930 case Instruction::And:
931 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
933 RHSKnownZero, RHSKnownOne, Depth+1) ||
934 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000935 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000936 return I;
937 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
938 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000939
940 // If all of the demanded bits are known 1 on one side, return the other.
941 // These bits cannot contribute to the result of the 'and'.
942 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
943 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000945 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
946 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000947 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000948
949 // If all of the demanded bits in the inputs are known zeros, return zero.
950 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000951 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000952
953 // If the RHS is a constant, see if we can simplify it.
954 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000956
957 // Output known-1 bits are only known if set in both the LHS & RHS.
958 RHSKnownOne &= LHSKnownOne;
959 // Output known-0 are known to be clear if zero in either the LHS | RHS.
960 RHSKnownZero |= LHSKnownZero;
961 break;
962 case Instruction::Or:
963 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
965 RHSKnownZero, RHSKnownOne, Depth+1) ||
966 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000967 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 return I;
969 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
970 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000971
972 // If all of the demanded bits are known zero on one side, return the other.
973 // These bits cannot contribute to the result of the 'or'.
974 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
975 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000977 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
978 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000979 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000980
981 // If all of the potentially set bits on one side are known to be set on
982 // the other side, just use the 'other' side.
983 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
984 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000986 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
987 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000989
990 // If the RHS is a constant, see if we can simplify it.
991 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000993
994 // Output known-0 bits are only known if clear in both the LHS & RHS.
995 RHSKnownZero &= LHSKnownZero;
996 // Output known-1 are known to be set if set in either the LHS | RHS.
997 RHSKnownOne |= LHSKnownOne;
998 break;
999 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1001 RHSKnownZero, RHSKnownOne, Depth+1) ||
1002 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001003 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I;
1005 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1006 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001007
1008 // If all of the demanded bits are known zero on one side, return the other.
1009 // These bits cannot contribute to the result of the 'xor'.
1010 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001012 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001013 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001014
1015 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1016 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1017 (RHSKnownOne & LHSKnownOne);
1018 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1019 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1020 (RHSKnownOne & LHSKnownZero);
1021
1022 // If all of the demanded bits are known to be zero on one side or the
1023 // other, turn this into an *inclusive* or.
1024 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1025 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1026 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001027 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001029 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001030 }
1031
1032 // If all of the demanded bits on one side are known, and all of the set
1033 // bits on that side are also known to be set on the other side, turn this
1034 // into an AND, as we know the bits will be cleared.
1035 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1036 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1037 // all known
1038 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1039 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1040 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001041 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 }
1044 }
1045
1046 // If the RHS is a constant, see if we can simplify it.
1047 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1048 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001049 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001050
1051 RHSKnownZero = KnownZeroOut;
1052 RHSKnownOne = KnownOneOut;
1053 break;
1054 }
1055 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return I;
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
1064 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066 ShrinkDemandedConstant(I, 2, DemandedMask))
1067 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001068
1069 // Only known if known in both the LHS and RHS.
1070 RHSKnownOne &= LHSKnownOne;
1071 RHSKnownZero &= LHSKnownZero;
1072 break;
1073 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001074 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001075 DemandedMask.zext(truncBf);
1076 RHSKnownZero.zext(truncBf);
1077 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001079 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001080 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001081 DemandedMask.trunc(BitWidth);
1082 RHSKnownZero.trunc(BitWidth);
1083 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001085 break;
1086 }
1087 case Instruction::BitCast:
1088 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 return false; // vector->int or fp->int?
1090 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001091 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 return I;
1093 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001094 break;
1095 case Instruction::ZExt: {
1096 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001097 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001098
Zhou Shengd48653a2007-03-29 04:45:55 +00001099 DemandedMask.trunc(SrcBitWidth);
1100 RHSKnownZero.trunc(SrcBitWidth);
1101 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001103 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001104 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001105 DemandedMask.zext(BitWidth);
1106 RHSKnownZero.zext(BitWidth);
1107 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001110 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001111 break;
1112 }
1113 case Instruction::SExt: {
1114 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001116
Reid Spencer8cb68342007-03-12 17:25:59 +00001117 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001118 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001119
Zhou Sheng01542f32007-03-29 02:26:30 +00001120 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001121 // If any of the sign extended bits are demanded, we know that the sign
1122 // bit is demanded.
1123 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001124 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001125
Zhou Shengd48653a2007-03-29 04:45:55 +00001126 InputDemandedBits.trunc(SrcBitWidth);
1127 RHSKnownZero.trunc(SrcBitWidth);
1128 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001129 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001130 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 InputDemandedBits.zext(BitWidth);
1133 RHSKnownZero.zext(BitWidth);
1134 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001135 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001136
1137 // If the sign bit of the input is known set or clear, then we know the
1138 // top bits of the result.
1139
1140 // If the input sign bit is known zero, or if the NewBits are not demanded
1141 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001142 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001143 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001146 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001148 }
1149 break;
1150 }
1151 case Instruction::Add: {
1152 // Figure out what the input bits are. If the top bits of the and result
1153 // are not demanded, then the add doesn't demand them from its input
1154 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001155 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001156
1157 // If there is a constant on the RHS, there are a variety of xformations
1158 // we can do.
1159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160 // If null, this should be simplified elsewhere. Some of the xforms here
1161 // won't work if the RHS is zero.
1162 if (RHS->isZero())
1163 break;
1164
1165 // If the top bit of the output is demanded, demand everything from the
1166 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001167 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001168
1169 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001170 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001171 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001173
1174 // If the RHS of the add has bits set that can't affect the input, reduce
1175 // the constant.
1176 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001177 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
1179 // Avoid excess work.
1180 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1181 break;
1182
1183 // Turn it into OR if input bits are zero.
1184 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1185 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001186 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 }
1190
1191 // We can say something about the output known-zero and known-one bits,
1192 // depending on potential carries from the input constant and the
1193 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1194 // bits set and the RHS constant is 0x01001, then we know we have a known
1195 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1196
1197 // To compute this, we first compute the potential carry bits. These are
1198 // the bits which may be modified. I'm not aware of a better way to do
1199 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001201 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001202
1203 // Now that we know which bits have carries, compute the known-1/0 sets.
1204
1205 // Bits are known one if they are known zero in one operand and one in the
1206 // other, and there is no input carry.
1207 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1208 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1209
1210 // Bits are known zero if they are known zero in both operands and there
1211 // is no input carry.
1212 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1213 } else {
1214 // If the high-bits of this ADD are not demanded, then it does not demand
1215 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001216 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 // Right fill the mask of bits for this ADD to demand the most
1218 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001219 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001220 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1221 LHSKnownZero, LHSKnownOne, Depth+1) ||
1222 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001224 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 }
1226 }
1227 break;
1228 }
1229 case Instruction::Sub:
1230 // If the high-bits of this SUB are not demanded, then it does not demand
1231 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001232 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 // Right fill the mask of bits for this SUB to demand the most
1234 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001235 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001236 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001237 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1238 LHSKnownZero, LHSKnownOne, Depth+1) ||
1239 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001240 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001241 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001243 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1244 // the known zeros and ones.
1245 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 break;
1247 case Instruction::Shl:
1248 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001249 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001250 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001251 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001253 return I;
1254 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 RHSKnownZero <<= ShiftAmt;
1256 RHSKnownOne <<= ShiftAmt;
1257 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001258 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001259 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 }
1261 break;
1262 case Instruction::LShr:
1263 // For a logical shift right
1264 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001265 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001266
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001268 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001271 return I;
1272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1274 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001275 if (ShiftAmt) {
1276 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001277 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001278 RHSKnownZero |= HighBits; // high bits known zero.
1279 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001280 }
1281 break;
1282 case Instruction::AShr:
1283 // If this is an arithmetic shift right and only the low-bit is set, we can
1284 // always convert this into a logical shr, even if the shift amount is
1285 // variable. The low bit of the shift cannot be an input sign bit unless
1286 // the shift amount is >= the size of the datatype, which is undefined.
1287 if (DemandedMask == 1) {
1288 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001291 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001293
1294 // If the sign bit is the only bit demanded by this ashr, then there is no
1295 // need to do it, the shift doesn't change the high bit.
1296 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001297 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001298
1299 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001300 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001301
Reid Spencer8cb68342007-03-12 17:25:59 +00001302 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001303 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001304 // If any of the "high bits" are demanded, we should set the sign bit as
1305 // demanded.
1306 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1307 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001310 return I;
1311 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001313 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1315 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1316
1317 // Handle the sign bits.
1318 APInt SignBit(APInt::getSignBit(BitWidth));
1319 // Adjust to where it is now in the mask.
1320 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1321
1322 // If the input sign bit is known to be zero, or if none of the top bits
1323 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001324 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001325 (HighBits & ~DemandedMask) == HighBits) {
1326 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001327 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1331 RHSKnownOne |= HighBits;
1332 }
1333 }
1334 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001335 case Instruction::SRem:
1336 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001337 APInt RA = Rem->getValue().abs();
1338 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001339 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001340 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001341
Nick Lewycky8e394322008-11-02 02:41:50 +00001342 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001343 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001344 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001345 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001346 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001347
1348 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1349 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001350
1351 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001352
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001354 }
1355 }
1356 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001357 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001358 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1359 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001360 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1361 KnownZero2, KnownOne2, Depth+1) ||
1362 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001363 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001364 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001365
Chris Lattner455e9ab2009-01-21 18:09:24 +00001366 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001367 Leaders = std::max(Leaders,
1368 KnownZero2.countLeadingOnes());
1369 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001370 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001371 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001372 case Instruction::Call:
1373 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1374 switch (II->getIntrinsicID()) {
1375 default: break;
1376 case Intrinsic::bswap: {
1377 // If the only bits demanded come from one byte of the bswap result,
1378 // just shift the input byte into position to eliminate the bswap.
1379 unsigned NLZ = DemandedMask.countLeadingZeros();
1380 unsigned NTZ = DemandedMask.countTrailingZeros();
1381
1382 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1383 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1384 // have 14 leading zeros, round to 8.
1385 NLZ &= ~7;
1386 NTZ &= ~7;
1387 // If we need exactly one byte, we can do this transformation.
1388 if (BitWidth-NLZ-NTZ == 8) {
1389 unsigned ResultBit = NTZ;
1390 unsigned InputBit = BitWidth-NTZ-8;
1391
1392 // Replace this with either a left or right shift to get the byte into
1393 // the right place.
1394 Instruction *NewVal;
1395 if (InputBit > ResultBit)
1396 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1397 ConstantInt::get(I->getType(), InputBit-ResultBit));
1398 else
1399 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1400 ConstantInt::get(I->getType(), ResultBit-InputBit));
1401 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001402 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001403 }
1404
1405 // TODO: Could compute known zero/one bits based on the input.
1406 break;
1407 }
1408 }
1409 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001410 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001411 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001412 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001413
1414 // If the client is only demanding bits that we know, return the known
1415 // constant.
Dan Gohman1c8491e2009-04-25 17:12:48 +00001416 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1417 Constant *C = ConstantInt::get(RHSKnownOne);
1418 if (isa<PointerType>(V->getType()))
1419 C = ConstantExpr::getIntToPtr(C, V->getType());
1420 return C;
1421 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001422 return false;
1423}
1424
Chris Lattner867b99f2006-10-05 06:55:50 +00001425
Mon P Wangaeb06d22008-11-10 04:46:22 +00001426/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001427/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001428/// actually used by the caller. This method analyzes which elements of the
1429/// operand are undef and returns that information in UndefElts.
1430///
1431/// If the information about demanded elements can be used to simplify the
1432/// operation, the operation is simplified, then the resultant value is
1433/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001434Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1435 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001436 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001437 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001438 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001439 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001440
1441 if (isa<UndefValue>(V)) {
1442 // If the entire vector is undefined, just return this info.
1443 UndefElts = EltMask;
1444 return 0;
1445 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1446 UndefElts = EltMask;
1447 return UndefValue::get(V->getType());
1448 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001449
Chris Lattner867b99f2006-10-05 06:55:50 +00001450 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001451 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1452 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001453 Constant *Undef = UndefValue::get(EltTy);
1454
1455 std::vector<Constant*> Elts;
1456 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001457 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001459 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1461 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001462 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 } else { // Otherwise, defined.
1464 Elts.push_back(CP->getOperand(i));
1465 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001466
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001468 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001469 return NewCP != CP ? NewCP : 0;
1470 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001471 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001473
1474 // Check if this is identity. If so, return 0 since we are not simplifying
1475 // anything.
1476 if (DemandedElts == ((1ULL << VWidth) -1))
1477 return 0;
1478
Reid Spencer9d6565a2007-02-15 02:26:10 +00001479 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001480 Constant *Zero = Constant::getNullValue(EltTy);
1481 Constant *Undef = UndefValue::get(EltTy);
1482 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001483 for (unsigned i = 0; i != VWidth; ++i) {
1484 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1485 Elts.push_back(Elt);
1486 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001488 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001489 }
1490
Dan Gohman488fbfc2008-09-09 18:11:14 +00001491 // Limit search depth.
1492 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001493 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001494
1495 // If multiple users are using the root value, procede with
1496 // simplification conservatively assuming that all elements
1497 // are needed.
1498 if (!V->hasOneUse()) {
1499 // Quit if we find multiple users of a non-root value though.
1500 // They'll be handled when it's their turn to be visited by
1501 // the main instcombine process.
1502 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001504 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001505
1506 // Conservatively assume that all elements are needed.
1507 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001508 }
1509
1510 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001511 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001512
1513 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001514 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001515 Value *TmpV;
1516 switch (I->getOpcode()) {
1517 default: break;
1518
1519 case Instruction::InsertElement: {
1520 // If this is a variable index, we don't know which element it overwrites.
1521 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001522 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001523 if (Idx == 0) {
1524 // Note that we can't propagate undef elt info, because we don't know
1525 // which elt is getting updated.
1526 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527 UndefElts2, Depth+1);
1528 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529 break;
1530 }
1531
1532 // If this is inserting an element that isn't demanded, remove this
1533 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001534 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001535 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001536 return AddSoonDeadInstToWorklist(*I, 0);
1537
1538 // Otherwise, the element inserted overwrites whatever was there, so the
1539 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001540 APInt DemandedElts2 = DemandedElts;
1541 DemandedElts2.clear(IdxNo);
1542 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001543 UndefElts, Depth+1);
1544 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545
1546 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001547 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001548 break;
1549 }
1550 case Instruction::ShuffleVector: {
1551 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001552 uint64_t LHSVWidth =
1553 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001554 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001555 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001556 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001557 unsigned MaskVal = Shuffle->getMaskValue(i);
1558 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001559 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001561 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001562 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 else
Evan Cheng388df622009-02-03 10:05:09 +00001564 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 }
1566 }
1567 }
1568
Nate Begeman7b254672009-02-11 22:36:25 +00001569 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001571 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1573
Nate Begeman7b254672009-02-11 22:36:25 +00001574 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1576 UndefElts3, Depth+1);
1577 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1578
1579 bool NewUndefElts = false;
1580 for (unsigned i = 0; i < VWidth; i++) {
1581 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001582 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001583 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001584 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001585 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001586 NewUndefElts = true;
1587 UndefElts.set(i);
1588 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001589 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001590 if (UndefElts3[MaskVal - LHSVWidth]) {
1591 NewUndefElts = true;
1592 UndefElts.set(i);
1593 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001594 }
1595 }
1596
1597 if (NewUndefElts) {
1598 // Add additional discovered undefs.
1599 std::vector<Constant*> Elts;
1600 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001601 if (UndefElts[i])
Dan Gohman488fbfc2008-09-09 18:11:14 +00001602 Elts.push_back(UndefValue::get(Type::Int32Ty));
1603 else
1604 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1605 Shuffle->getMaskValue(i)));
1606 }
1607 I->setOperand(2, ConstantVector::get(Elts));
1608 MadeChange = true;
1609 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001610 break;
1611 }
Chris Lattner69878332007-04-14 22:29:23 +00001612 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001613 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001614 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1615 if (!VTy) break;
1616 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001617 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001618 unsigned Ratio;
1619
1620 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001621 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001622 // elements as are demanded of us.
1623 Ratio = 1;
1624 InputDemandedElts = DemandedElts;
1625 } else if (VWidth > InVWidth) {
1626 // Untested so far.
1627 break;
1628
1629 // If there are more elements in the result than there are in the source,
1630 // then an input element is live if any of the corresponding output
1631 // elements are live.
1632 Ratio = VWidth/InVWidth;
1633 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001634 if (DemandedElts[OutIdx])
1635 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001636 }
1637 } else {
1638 // Untested so far.
1639 break;
1640
1641 // If there are more elements in the source than there are in the result,
1642 // then an input element is live if the corresponding output element is
1643 // live.
1644 Ratio = InVWidth/VWidth;
1645 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001646 if (DemandedElts[InIdx/Ratio])
1647 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001648 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001649
Chris Lattner69878332007-04-14 22:29:23 +00001650 // div/rem demand all inputs, because they don't want divide by zero.
1651 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1652 UndefElts2, Depth+1);
1653 if (TmpV) {
1654 I->setOperand(0, TmpV);
1655 MadeChange = true;
1656 }
1657
1658 UndefElts = UndefElts2;
1659 if (VWidth > InVWidth) {
1660 assert(0 && "Unimp");
1661 // If there are more elements in the result than there are in the source,
1662 // then an output element is undef if the corresponding input element is
1663 // undef.
1664 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001665 if (UndefElts2[OutIdx/Ratio])
1666 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001667 } else if (VWidth < InVWidth) {
1668 assert(0 && "Unimp");
1669 // If there are more elements in the source than there are in the result,
1670 // then a result element is undef if all of the corresponding input
1671 // elements are undef.
1672 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1673 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001674 if (!UndefElts2[InIdx]) // Not undef?
1675 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001676 }
1677 break;
1678 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001679 case Instruction::And:
1680 case Instruction::Or:
1681 case Instruction::Xor:
1682 case Instruction::Add:
1683 case Instruction::Sub:
1684 case Instruction::Mul:
1685 // div/rem demand all inputs, because they don't want divide by zero.
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687 UndefElts, Depth+1);
1688 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1690 UndefElts2, Depth+1);
1691 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1692
1693 // Output elements are undefined if both are undefined. Consider things
1694 // like undef&0. The result is known zero, not undef.
1695 UndefElts &= UndefElts2;
1696 break;
1697
1698 case Instruction::Call: {
1699 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1700 if (!II) break;
1701 switch (II->getIntrinsicID()) {
1702 default: break;
1703
1704 // Binary vector operations that work column-wise. A dest element is a
1705 // function of the corresponding input elements from the two inputs.
1706 case Intrinsic::x86_sse_sub_ss:
1707 case Intrinsic::x86_sse_mul_ss:
1708 case Intrinsic::x86_sse_min_ss:
1709 case Intrinsic::x86_sse_max_ss:
1710 case Intrinsic::x86_sse2_sub_sd:
1711 case Intrinsic::x86_sse2_mul_sd:
1712 case Intrinsic::x86_sse2_min_sd:
1713 case Intrinsic::x86_sse2_max_sd:
1714 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1715 UndefElts, Depth+1);
1716 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1717 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1718 UndefElts2, Depth+1);
1719 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1720
1721 // If only the low elt is demanded and this is a scalarizable intrinsic,
1722 // scalarize it now.
1723 if (DemandedElts == 1) {
1724 switch (II->getIntrinsicID()) {
1725 default: break;
1726 case Intrinsic::x86_sse_sub_ss:
1727 case Intrinsic::x86_sse_mul_ss:
1728 case Intrinsic::x86_sse2_sub_sd:
1729 case Intrinsic::x86_sse2_mul_sd:
1730 // TODO: Lower MIN/MAX/ABS/etc
1731 Value *LHS = II->getOperand(1);
1732 Value *RHS = II->getOperand(2);
1733 // Extract the element as scalars.
1734 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1735 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1736
1737 switch (II->getIntrinsicID()) {
1738 default: assert(0 && "Case stmts out of sync!");
1739 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 =
Gabor Greif051a9502008-04-06 20:25:17 +00001752 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1753 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001754 InsertNewInstBefore(New, *II);
1755 AddSoonDeadInstToWorklist(*II, 0);
1756 return New;
1757 }
1758 }
1759
1760 // Output elements are undefined if both are undefined. Consider things
1761 // like undef&0. The result is known zero, not undef.
1762 UndefElts &= UndefElts2;
1763 break;
1764 }
1765 break;
1766 }
1767 }
1768 return MadeChange ? I : 0;
1769}
1770
Dan Gohman45b4e482008-05-19 22:14:15 +00001771
Chris Lattner564a7272003-08-13 19:01:45 +00001772/// AssociativeOpt - Perform an optimization on an associative operator. This
1773/// function is designed to check a chain of associative operators for a
1774/// potential to apply a certain optimization. Since the optimization may be
1775/// applicable if the expression was reassociated, this checks the chain, then
1776/// reassociates the expression as necessary to expose the optimization
1777/// opportunity. This makes use of a special Functor, which must define
1778/// 'shouldApply' and 'apply' methods.
1779///
1780template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001781static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001782 unsigned Opcode = Root.getOpcode();
1783 Value *LHS = Root.getOperand(0);
1784
1785 // Quick check, see if the immediate LHS matches...
1786 if (F.shouldApply(LHS))
1787 return F.apply(Root);
1788
1789 // Otherwise, if the LHS is not of the same opcode as the root, return.
1790 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001791 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001792 // Should we apply this transform to the RHS?
1793 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1794
1795 // If not to the RHS, check to see if we should apply to the LHS...
1796 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1797 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1798 ShouldApply = true;
1799 }
1800
1801 // If the functor wants to apply the optimization to the RHS of LHSI,
1802 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1803 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001804 // Now all of the instructions are in the current basic block, go ahead
1805 // and perform the reassociation.
1806 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1807
1808 // First move the selected RHS to the LHS of the root...
1809 Root.setOperand(0, LHSI->getOperand(1));
1810
1811 // Make what used to be the LHS of the root be the user of the root...
1812 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001813 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001814 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1815 return 0;
1816 }
Chris Lattner65725312004-04-16 18:08:07 +00001817 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001818 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001819 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001820 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001821 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001822
1823 // Now propagate the ExtraOperand down the chain of instructions until we
1824 // get to LHSI.
1825 while (TmpLHSI != LHSI) {
1826 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001827 // Move the instruction to immediately before the chain we are
1828 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001829 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001830 ARI = NextLHSI;
1831
Chris Lattner564a7272003-08-13 19:01:45 +00001832 Value *NextOp = NextLHSI->getOperand(1);
1833 NextLHSI->setOperand(1, ExtraOperand);
1834 TmpLHSI = NextLHSI;
1835 ExtraOperand = NextOp;
1836 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001837
Chris Lattner564a7272003-08-13 19:01:45 +00001838 // Now that the instructions are reassociated, have the functor perform
1839 // the transformation...
1840 return F.apply(Root);
1841 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001842
Chris Lattner564a7272003-08-13 19:01:45 +00001843 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1844 }
1845 return 0;
1846}
1847
Dan Gohman844731a2008-05-13 00:00:25 +00001848namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001849
Nick Lewycky02d639f2008-05-23 04:34:58 +00001850// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001851struct AddRHS {
1852 Value *RHS;
1853 AddRHS(Value *rhs) : RHS(rhs) {}
1854 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1855 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001856 return BinaryOperator::CreateShl(Add.getOperand(0),
1857 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001858 }
1859};
1860
1861// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1862// iff C1&C2 == 0
1863struct AddMaskingAnd {
1864 Constant *C2;
1865 AddMaskingAnd(Constant *c) : C2(c) {}
1866 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001867 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001868 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001869 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001870 }
1871 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001872 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001873 }
1874};
1875
Dan Gohman844731a2008-05-13 00:00:25 +00001876}
1877
Chris Lattner6e7ba452005-01-01 16:22:27 +00001878static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001879 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001880 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001881 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001882 }
1883
Chris Lattner2eefe512004-04-09 19:05:30 +00001884 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001885 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1886 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001887
Chris Lattner2eefe512004-04-09 19:05:30 +00001888 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1889 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001890 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1891 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001892 }
1893
1894 Value *Op0 = SO, *Op1 = ConstOperand;
1895 if (!ConstIsRHS)
1896 std::swap(Op0, Op1);
1897 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001899 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001900 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001901 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001902 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001903 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001904 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001905 abort();
1906 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001907 return IC->InsertNewInstBefore(New, I);
1908}
1909
1910// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1911// constant as the other operand, try to fold the binary operator into the
1912// select arguments. This also works for Cast instructions, which obviously do
1913// not have a second operand.
1914static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1915 InstCombiner *IC) {
1916 // Don't modify shared select instructions
1917 if (!SI->hasOneUse()) return 0;
1918 Value *TV = SI->getOperand(1);
1919 Value *FV = SI->getOperand(2);
1920
1921 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001922 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001923 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001924
Chris Lattner6e7ba452005-01-01 16:22:27 +00001925 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1926 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1927
Gabor Greif051a9502008-04-06 20:25:17 +00001928 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1929 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001930 }
1931 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001932}
1933
Chris Lattner4e998b22004-09-29 05:07:12 +00001934
1935/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1936/// node as operand #0, see if we can fold the instruction into the PHI (which
1937/// is only possible if all operands to the PHI are constants).
1938Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1939 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001940 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001941 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001942
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001943 // Check to see if all of the operands of the PHI are constants. If there is
1944 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001945 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001946 BasicBlock *NonConstBB = 0;
1947 for (unsigned i = 0; i != NumPHIValues; ++i)
1948 if (!isa<Constant>(PN->getIncomingValue(i))) {
1949 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001950 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001951 NonConstBB = PN->getIncomingBlock(i);
1952
1953 // If the incoming non-constant value is in I's block, we have an infinite
1954 // loop.
1955 if (NonConstBB == I.getParent())
1956 return 0;
1957 }
1958
1959 // If there is exactly one non-constant value, we can insert a copy of the
1960 // operation in that block. However, if this is a critical edge, we would be
1961 // inserting the computation one some other paths (e.g. inside a loop). Only
1962 // do this if the pred block is unconditionally branching into the phi block.
1963 if (NonConstBB) {
1964 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1965 if (!BI || !BI->isUnconditional()) return 0;
1966 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001967
1968 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001969 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001970 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001971 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001972 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001973
1974 // Next, add all of the operands to the PHI.
1975 if (I.getNumOperands() == 2) {
1976 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001977 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001978 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001979 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001980 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1981 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1982 else
1983 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001984 } else {
1985 assert(PN->getIncomingBlock(i) == NonConstBB);
1986 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001987 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001988 PN->getIncomingValue(i), C, "phitmp",
1989 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001990 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001991 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001992 CI->getPredicate(),
1993 PN->getIncomingValue(i), C, "phitmp",
1994 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001995 else
1996 assert(0 && "Unknown binop!");
1997
Chris Lattnerdbab3862007-03-02 21:28:56 +00001998 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001999 }
2000 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002001 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002002 } else {
2003 CastInst *CI = cast<CastInst>(&I);
2004 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002005 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006 Value *InV;
2007 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002008 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002009 } else {
2010 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002011 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002012 I.getType(), "phitmp",
2013 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002014 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015 }
2016 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002017 }
2018 }
2019 return ReplaceInstUsesWith(I, NewPN);
2020}
2021
Chris Lattner2454a2e2008-01-29 06:52:45 +00002022
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002023/// WillNotOverflowSignedAdd - Return true if we can prove that:
2024/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2025/// This basically requires proving that the add in the original type would not
2026/// overflow to change the sign bit or have a carry out.
2027bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2028 // There are different heuristics we can use for this. Here are some simple
2029 // ones.
2030
2031 // Add has the property that adding any two 2's complement numbers can only
2032 // have one carry bit which can change a sign. As such, if LHS and RHS each
2033 // have at least two sign bits, we know that the addition of the two values will
2034 // sign extend fine.
2035 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2036 return true;
2037
2038
2039 // If one of the operands only has one non-zero bit, and if the other operand
2040 // has a known-zero bit in a more significant place than it (not including the
2041 // sign bit) the ripple may go up to and fill the zero, but won't change the
2042 // sign. For example, (X & ~4) + 1.
2043
2044 // TODO: Implement.
2045
2046 return false;
2047}
2048
Chris Lattner2454a2e2008-01-29 06:52:45 +00002049
Chris Lattner7e708292002-06-25 16:13:24 +00002050Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002051 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002052 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002053
Chris Lattner66331a42004-04-10 22:01:55 +00002054 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002055 // X + undef -> undef
2056 if (isa<UndefValue>(RHS))
2057 return ReplaceInstUsesWith(I, RHS);
2058
Chris Lattner66331a42004-04-10 22:01:55 +00002059 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002060 if (RHSC->isNullValue())
2061 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002062
Chris Lattner66331a42004-04-10 22:01:55 +00002063 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002064 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002065 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002066 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002067 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002068 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002069
2070 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2071 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002072 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002073 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002074
2075 // zext(i1) - 1 -> select i1, 0, -1
2076 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2077 if (CI->isAllOnesValue() &&
2078 ZI->getOperand(0)->getType() == Type::Int1Ty)
2079 return SelectInst::Create(ZI->getOperand(0),
2080 Constant::getNullValue(I.getType()),
2081 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002082 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002083
2084 if (isa<PHINode>(LHS))
2085 if (Instruction *NV = FoldOpIntoPhi(I))
2086 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002087
Chris Lattner4f637d42006-01-06 17:59:59 +00002088 ConstantInt *XorRHS = 0;
2089 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002090 if (isa<ConstantInt>(RHSC) &&
2091 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002092 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002093 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002094
Zhou Sheng4351c642007-04-02 08:20:41 +00002095 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002096 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2097 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002098 do {
2099 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002100 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2101 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002102 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2103 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002104 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002105 if (!MaskedValueIsZero(XorLHS,
2106 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002107 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002108 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002109 }
2110 }
2111 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002112 C0080Val = APIntOps::lshr(C0080Val, Size);
2113 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2114 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002115
Reid Spencer35c38852007-03-28 01:36:16 +00002116 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002117 // with funny bit widths then this switch statement should be removed. It
2118 // is just here to get the size of the "middle" type back up to something
2119 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002120 const Type *MiddleType = 0;
2121 switch (Size) {
2122 default: break;
2123 case 32: MiddleType = Type::Int32Ty; break;
2124 case 16: MiddleType = Type::Int16Ty; break;
2125 case 8: MiddleType = Type::Int8Ty; break;
2126 }
2127 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002128 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002129 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002130 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002131 }
2132 }
Chris Lattner66331a42004-04-10 22:01:55 +00002133 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002134
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002135 if (I.getType() == Type::Int1Ty)
2136 return BinaryOperator::CreateXor(LHS, RHS);
2137
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002138 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002139 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002140 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002141
2142 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2143 if (RHSI->getOpcode() == Instruction::Sub)
2144 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2145 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2146 }
2147 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2148 if (LHSI->getOpcode() == Instruction::Sub)
2149 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2150 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2151 }
Robert Bocchino71698282004-07-27 21:02:21 +00002152 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002153
Chris Lattner5c4afb92002-05-08 22:46:53 +00002154 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002155 // -A + -B --> -(A + B)
2156 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002157 if (LHS->getType()->isIntOrIntVector()) {
2158 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002159 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002160 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002162 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002163 }
2164
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002165 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002166 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002167
2168 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002169 if (!isa<Constant>(RHS))
2170 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002171 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002172
Misha Brukmanfd939082005-04-21 23:48:37 +00002173
Chris Lattner50af16a2004-11-13 19:50:12 +00002174 ConstantInt *C2;
2175 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2176 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002177 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002178
2179 // X*C1 + X*C2 --> X * (C1+C2)
2180 ConstantInt *C1;
2181 if (X == dyn_castFoldableMul(RHS, C1))
Dan Gohman6de29f82009-06-15 22:12:54 +00002182 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002183 }
2184
2185 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002186 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002187 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002188
Chris Lattnere617c9e2007-01-05 02:17:46 +00002189 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002190 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2191 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002192
Chris Lattnerad3448c2003-02-18 19:57:07 +00002193
Chris Lattner564a7272003-08-13 19:01:45 +00002194 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002195 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002196 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2197 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002198
2199 // A+B --> A|B iff A and B have no bits set in common.
2200 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2201 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2202 APInt LHSKnownOne(IT->getBitWidth(), 0);
2203 APInt LHSKnownZero(IT->getBitWidth(), 0);
2204 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2205 if (LHSKnownZero != 0) {
2206 APInt RHSKnownOne(IT->getBitWidth(), 0);
2207 APInt RHSKnownZero(IT->getBitWidth(), 0);
2208 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2209
2210 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002211 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002212 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002213 }
2214 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002215
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002216 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002217 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002218 Value *W, *X, *Y, *Z;
2219 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2220 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2221 if (W != Y) {
2222 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002223 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002224 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002225 std::swap(W, X);
2226 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002227 std::swap(Y, Z);
2228 std::swap(W, X);
2229 }
2230 }
2231
2232 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002233 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002234 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002235 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002236 }
2237 }
2238 }
2239
Chris Lattner6b032052003-10-02 15:11:26 +00002240 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002241 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002242 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002243 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002244
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002245 // (X & FF00) + xx00 -> (X+xx00) & FF00
2246 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002247 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002248 if (Anded == CRHS) {
2249 // See if all bits from the first bit set in the Add RHS up are included
2250 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002251 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002252
2253 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002254 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002255
2256 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002257 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002258
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002259 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2260 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002261 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002262 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002263 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002264 }
2265 }
2266 }
2267
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002268 // Try to fold constant add into select arguments.
2269 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002270 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002271 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002272 }
2273
Reid Spencer1628cec2006-10-26 06:15:43 +00002274 // add (cast *A to intptrtype) B ->
Dan Gohmana119de82009-06-14 23:30:43 +00002275 // cast (GEP (cast *A to i8*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002276 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002277 CastInst *CI = dyn_cast<CastInst>(LHS);
2278 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002279 if (!CI) {
2280 CI = dyn_cast<CastInst>(RHS);
2281 Other = LHS;
2282 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002283 if (CI && CI->getType()->isSized() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00002284 (CI->getType()->getScalarSizeInBits() ==
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002285 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002286 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002287 unsigned AS =
2288 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002289 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2290 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002291 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002292 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002293 }
2294 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002295
Chris Lattner42790482007-12-20 01:56:58 +00002296 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002297 {
2298 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002299 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002300 if (!SI) {
2301 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002302 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002303 }
Chris Lattner42790482007-12-20 01:56:58 +00002304 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002305 Value *TV = SI->getTrueValue();
2306 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002307 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002308
2309 // Can we fold the add into the argument of the select?
2310 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002311 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2312 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002313 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002314 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2315 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002316 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002317 }
2318 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002319
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002320 // Check for (add (sext x), y), see if we can merge this into an
2321 // integer add followed by a sext.
2322 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2323 // (add (sext x), cst) --> (sext (add x, cst'))
2324 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2325 Constant *CI =
2326 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2327 if (LHSConv->hasOneUse() &&
2328 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2329 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2330 // Insert the new, smaller add.
2331 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2332 CI, "addconv");
2333 InsertNewInstBefore(NewAdd, I);
2334 return new SExtInst(NewAdd, I.getType());
2335 }
2336 }
2337
2338 // (add (sext x), (sext y)) --> (sext (add int x, y))
2339 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2340 // Only do this if x/y have the same type, if at last one of them has a
2341 // single use (so we don't increase the number of sexts), and if the
2342 // integer add will not overflow.
2343 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2344 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2345 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2346 RHSConv->getOperand(0))) {
2347 // Insert the new integer add.
2348 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2349 RHSConv->getOperand(0),
2350 "addconv");
2351 InsertNewInstBefore(NewAdd, I);
2352 return new SExtInst(NewAdd, I.getType());
2353 }
2354 }
2355 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002356
2357 return Changed ? &I : 0;
2358}
2359
2360Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2361 bool Changed = SimplifyCommutative(I);
2362 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2363
2364 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2365 // X + 0 --> X
2366 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2367 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2368 (I.getType())->getValueAPF()))
2369 return ReplaceInstUsesWith(I, LHS);
2370 }
2371
2372 if (isa<PHINode>(LHS))
2373 if (Instruction *NV = FoldOpIntoPhi(I))
2374 return NV;
2375 }
2376
2377 // -A + B --> B - A
2378 // -A + -B --> -(A + B)
2379 if (Value *LHSV = dyn_castFNegVal(LHS))
2380 return BinaryOperator::CreateFSub(RHS, LHSV);
2381
2382 // A + -B --> A - B
2383 if (!isa<Constant>(RHS))
2384 if (Value *V = dyn_castFNegVal(RHS))
2385 return BinaryOperator::CreateFSub(LHS, V);
2386
2387 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2388 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2389 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2390 return ReplaceInstUsesWith(I, LHS);
2391
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002392 // Check for (add double (sitofp x), y), see if we can merge this into an
2393 // integer add followed by a promotion.
2394 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2395 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2396 // ... if the constant fits in the integer value. This is useful for things
2397 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2398 // requires a constant pool load, and generally allows the add to be better
2399 // instcombined.
2400 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2401 Constant *CI =
2402 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2403 if (LHSConv->hasOneUse() &&
2404 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2405 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2406 // Insert the new integer add.
2407 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2408 CI, "addconv");
2409 InsertNewInstBefore(NewAdd, I);
2410 return new SIToFPInst(NewAdd, I.getType());
2411 }
2412 }
2413
2414 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2415 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2416 // Only do this if x/y have the same type, if at last one of them has a
2417 // single use (so we don't increase the number of int->fp conversions),
2418 // and if the integer add will not overflow.
2419 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2420 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2421 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2422 RHSConv->getOperand(0))) {
2423 // Insert the new integer add.
2424 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2425 RHSConv->getOperand(0),
2426 "addconv");
2427 InsertNewInstBefore(NewAdd, I);
2428 return new SIToFPInst(NewAdd, I.getType());
2429 }
2430 }
2431 }
2432
Chris Lattner7e708292002-06-25 16:13:24 +00002433 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002434}
2435
Chris Lattner7e708292002-06-25 16:13:24 +00002436Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002438
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002439 if (Op0 == Op1) // sub X, X -> 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00002440 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002441
Chris Lattner233f7dc2002-08-12 21:17:25 +00002442 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002443 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002444 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002445
Chris Lattnere87597f2004-10-16 18:11:37 +00002446 if (isa<UndefValue>(Op0))
2447 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2448 if (isa<UndefValue>(Op1))
2449 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2450
Chris Lattnerd65460f2003-11-05 01:06:05 +00002451 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2452 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002453 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002454 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002455
Chris Lattnerd65460f2003-11-05 01:06:05 +00002456 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002457 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002458 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002459 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002460
Chris Lattner76b7a062007-01-15 07:02:54 +00002461 // -(X >>u 31) -> (X >>s 31)
2462 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002463 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002464 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002465 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002466 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002467 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002468 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002469 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002470 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002471 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002472 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002473 }
2474 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002475 }
2476 else if (SI->getOpcode() == Instruction::AShr) {
2477 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2478 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002479 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002480 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002481 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002482 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002483 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002484 }
2485 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002486 }
2487 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002488 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002489
2490 // Try to fold constant sub into select arguments.
2491 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002493 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002494 }
2495
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002496 if (I.getType() == Type::Int1Ty)
2497 return BinaryOperator::CreateXor(Op0, Op1);
2498
Chris Lattner43d84d62005-04-07 16:15:25 +00002499 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002500 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002501 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002502 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002503 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002505 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2506 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2507 // C1-(X+C2) --> (C1-C2)-X
Dan Gohman6de29f82009-06-15 22:12:54 +00002508 return BinaryOperator::CreateSub(ConstantExpr::getSub(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002509 Op1I->getOperand(0));
2510 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002511 }
2512
Chris Lattnerfd059242003-10-15 16:48:29 +00002513 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002514 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2515 // is not used by anyone else...
2516 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002517 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002518 // Swap the two operands of the subexpr...
2519 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2520 Op1I->setOperand(0, IIOp1);
2521 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002522
Chris Lattnera2881962003-02-18 19:28:33 +00002523 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002524 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002525 }
2526
2527 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2528 //
2529 if (Op1I->getOpcode() == Instruction::And &&
2530 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2531 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2532
Chris Lattnerf523d062004-06-09 05:08:07 +00002533 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002534 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2535 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002536 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002537
Reid Spencerac5209e2006-10-16 23:08:08 +00002538 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002539 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002540 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002541 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002542 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002543 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002544 ConstantExpr::getNeg(DivRHS));
2545
Chris Lattnerad3448c2003-02-18 19:57:07 +00002546 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002547 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002548 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002549 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2550 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002551 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002552 }
Chris Lattner40371712002-05-09 01:29:19 +00002553 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002554 }
Chris Lattnera2881962003-02-18 19:28:33 +00002555
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002556 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2557 if (Op0I->getOpcode() == Instruction::Add) {
2558 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2559 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2560 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2561 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2562 } else if (Op0I->getOpcode() == Instruction::Sub) {
2563 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2564 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002565 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002566 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002567
Chris Lattner50af16a2004-11-13 19:50:12 +00002568 ConstantInt *C1;
2569 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002570 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002571 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002572
Chris Lattner50af16a2004-11-13 19:50:12 +00002573 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2574 if (X == dyn_castFoldableMul(Op1, C2))
Dan Gohman6de29f82009-06-15 22:12:54 +00002575 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002576 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002577 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002578}
2579
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2581 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2582
2583 // If this is a 'B = x-(-A)', change to B = x+A...
2584 if (Value *V = dyn_castFNegVal(Op1))
2585 return BinaryOperator::CreateFAdd(Op0, V);
2586
2587 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2588 if (Op1I->getOpcode() == Instruction::FAdd) {
2589 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2590 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2591 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2592 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2593 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002594 }
2595
2596 return 0;
2597}
2598
Chris Lattnera0141b92007-07-15 20:42:37 +00002599/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2600/// comparison only checks the sign bit. If it only checks the sign bit, set
2601/// TrueIfSigned if the result of the comparison is true when the input value is
2602/// signed.
2603static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2604 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002605 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002606 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2607 TrueIfSigned = true;
2608 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002609 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2610 TrueIfSigned = true;
2611 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002612 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2613 TrueIfSigned = false;
2614 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002615 case ICmpInst::ICMP_UGT:
2616 // True if LHS u> RHS and RHS == high-bit-mask - 1
2617 TrueIfSigned = true;
2618 return RHS->getValue() ==
2619 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2620 case ICmpInst::ICMP_UGE:
2621 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2622 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002623 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002624 default:
2625 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002626 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002627}
2628
Chris Lattner7e708292002-06-25 16:13:24 +00002629Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002630 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002631 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002632
Dan Gohman77b81fe2009-06-04 17:12:12 +00002633 // TODO: If Op1 is undef and Op0 is finite, return zero.
2634 if (!I.getType()->isFPOrFPVector() &&
2635 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00002636 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2637
Chris Lattner233f7dc2002-08-12 21:17:25 +00002638 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002639 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2640 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002641
2642 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002643 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002644 if (SI->getOpcode() == Instruction::Shl)
2645 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002646 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002647 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002648
Zhou Sheng843f07672007-04-19 05:39:12 +00002649 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002650 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2651 if (CI->equalsInt(1)) // X * 1 == X
2652 return ReplaceInstUsesWith(I, Op0);
2653 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002654 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002655
Zhou Sheng97b52c22007-03-29 01:57:21 +00002656 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002657 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002658 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002659 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002660 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002661 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohman77b81fe2009-06-04 17:12:12 +00002662 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky895f0852008-11-27 20:21:08 +00002663
2664 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2665 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2666 return BinaryOperator::CreateNeg(Op0, I.getName());
2667
2668 // As above, vector X*splat(1.0) -> X in all defined cases.
2669 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002670 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2671 if (CI->equalsInt(1))
2672 return ReplaceInstUsesWith(I, Op0);
2673 }
2674 }
Chris Lattnera2881962003-02-18 19:28:33 +00002675 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002676
2677 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2678 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002679 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002680 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002681 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002682 Op1, "tmp");
2683 InsertNewInstBefore(Add, I);
2684 Value *C1C2 = ConstantExpr::getMul(Op1,
2685 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002687
2688 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002689
2690 // Try to fold constant mul into select arguments.
2691 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002692 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002693 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002694
2695 if (isa<PHINode>(Op0))
2696 if (Instruction *NV = FoldOpIntoPhi(I))
2697 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002698 }
2699
Chris Lattnera4f445b2003-03-10 23:23:04 +00002700 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2701 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002702 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002703
Nick Lewycky0c730792008-11-21 07:33:58 +00002704 // (X / Y) * Y = X - (X % Y)
2705 // (X / Y) * -Y = (X % Y) - X
2706 {
2707 Value *Op1 = I.getOperand(1);
2708 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2709 if (!BO ||
2710 (BO->getOpcode() != Instruction::UDiv &&
2711 BO->getOpcode() != Instruction::SDiv)) {
2712 Op1 = Op0;
2713 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2714 }
2715 Value *Neg = dyn_castNegVal(Op1);
2716 if (BO && BO->hasOneUse() &&
2717 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2718 (BO->getOpcode() == Instruction::UDiv ||
2719 BO->getOpcode() == Instruction::SDiv)) {
2720 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2721
2722 Instruction *Rem;
2723 if (BO->getOpcode() == Instruction::UDiv)
2724 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2725 else
2726 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2727
2728 InsertNewInstBefore(Rem, I);
2729 Rem->takeName(BO);
2730
2731 if (Op1BO == Op1)
2732 return BinaryOperator::CreateSub(Op0BO, Rem);
2733 else
2734 return BinaryOperator::CreateSub(Rem, Op0BO);
2735 }
2736 }
2737
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002738 if (I.getType() == Type::Int1Ty)
2739 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2740
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002741 // If one of the operands of the multiply is a cast from a boolean value, then
2742 // we know the bool is either zero or one, so this is a 'masking' multiply.
2743 // See if we can simplify things based on how the boolean was originally
2744 // formed.
2745 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002746 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002747 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002748 BoolCast = CI;
2749 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002750 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002751 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002752 BoolCast = CI;
2753 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002754 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002755 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2756 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002757 bool TIS = false;
2758
Reid Spencere4d87aa2006-12-23 06:05:41 +00002759 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002760 // multiply into a shift/and combination.
2761 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002762 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2763 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002764 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002765 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002766 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002767 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002768 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002769 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002770 BoolCast->getOperand(0)->getName()+
2771 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002772
2773 // If the multiply type is not the same as the source type, sign extend
2774 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002775 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002776 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2777 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002778 Instruction::CastOps opcode =
2779 (SrcBits == DstBits ? Instruction::BitCast :
2780 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2781 V = InsertCastBefore(opcode, V, I.getType(), I);
2782 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002783
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002784 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002785 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002786 }
2787 }
2788 }
2789
Chris Lattner7e708292002-06-25 16:13:24 +00002790 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002791}
2792
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002793Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2794 bool Changed = SimplifyCommutative(I);
2795 Value *Op0 = I.getOperand(0);
2796
2797 // Simplify mul instructions with a constant RHS...
2798 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2799 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2800 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2801 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2802 if (Op1F->isExactlyValue(1.0))
2803 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2804 } else if (isa<VectorType>(Op1->getType())) {
2805 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2806 // As above, vector X*splat(1.0) -> X in all defined cases.
2807 if (Constant *Splat = Op1V->getSplatValue()) {
2808 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2809 if (F->isExactlyValue(1.0))
2810 return ReplaceInstUsesWith(I, Op0);
2811 }
2812 }
2813 }
2814
2815 // Try to fold constant mul into select arguments.
2816 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2817 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2818 return R;
2819
2820 if (isa<PHINode>(Op0))
2821 if (Instruction *NV = FoldOpIntoPhi(I))
2822 return NV;
2823 }
2824
2825 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2826 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2827 return BinaryOperator::CreateFMul(Op0v, Op1v);
2828
2829 return Changed ? &I : 0;
2830}
2831
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002832/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2833/// instruction.
2834bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2835 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2836
2837 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2838 int NonNullOperand = -1;
2839 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2840 if (ST->isNullValue())
2841 NonNullOperand = 2;
2842 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2843 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2844 if (ST->isNullValue())
2845 NonNullOperand = 1;
2846
2847 if (NonNullOperand == -1)
2848 return false;
2849
2850 Value *SelectCond = SI->getOperand(0);
2851
2852 // Change the div/rem to use 'Y' instead of the select.
2853 I.setOperand(1, SI->getOperand(NonNullOperand));
2854
2855 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2856 // problem. However, the select, or the condition of the select may have
2857 // multiple uses. Based on our knowledge that the operand must be non-zero,
2858 // propagate the known value for the select into other uses of it, and
2859 // propagate a known value of the condition into its other users.
2860
2861 // If the select and condition only have a single use, don't bother with this,
2862 // early exit.
2863 if (SI->use_empty() && SelectCond->hasOneUse())
2864 return true;
2865
2866 // Scan the current block backward, looking for other uses of SI.
2867 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2868
2869 while (BBI != BBFront) {
2870 --BBI;
2871 // If we found a call to a function, we can't assume it will return, so
2872 // information from below it cannot be propagated above it.
2873 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2874 break;
2875
2876 // Replace uses of the select or its condition with the known values.
2877 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2878 I != E; ++I) {
2879 if (*I == SI) {
2880 *I = SI->getOperand(NonNullOperand);
2881 AddToWorkList(BBI);
2882 } else if (*I == SelectCond) {
2883 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2884 ConstantInt::getFalse();
2885 AddToWorkList(BBI);
2886 }
2887 }
2888
2889 // If we past the instruction, quit looking for it.
2890 if (&*BBI == SI)
2891 SI = 0;
2892 if (&*BBI == SelectCond)
2893 SelectCond = 0;
2894
2895 // If we ran out of things to eliminate, break out of the loop.
2896 if (SelectCond == 0 && SI == 0)
2897 break;
2898
2899 }
2900 return true;
2901}
2902
2903
Reid Spencer1628cec2006-10-26 06:15:43 +00002904/// This function implements the transforms on div instructions that work
2905/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2906/// used by the visitors to those instructions.
2907/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002908Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002909 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002910
Chris Lattner50b2ca42008-02-19 06:12:18 +00002911 // undef / X -> 0 for integer.
2912 // undef / X -> undef for FP (the undef could be a snan).
2913 if (isa<UndefValue>(Op0)) {
2914 if (Op0->getType()->isFPOrFPVector())
2915 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002917 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002918
2919 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002920 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002921 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002922
Reid Spencer1628cec2006-10-26 06:15:43 +00002923 return 0;
2924}
Misha Brukmanfd939082005-04-21 23:48:37 +00002925
Reid Spencer1628cec2006-10-26 06:15:43 +00002926/// This function implements the transforms common to both integer division
2927/// instructions (udiv and sdiv). It is called by the visitors to those integer
2928/// division instructions.
2929/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002930Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2932
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002933 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002934 if (Op0 == Op1) {
2935 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002936 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002937 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2938 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2939 }
2940
Dan Gohman6de29f82009-06-15 22:12:54 +00002941 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002942 return ReplaceInstUsesWith(I, CI);
2943 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002944
Reid Spencer1628cec2006-10-26 06:15:43 +00002945 if (Instruction *Common = commonDivTransforms(I))
2946 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002947
2948 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2949 // This does not apply for fdiv.
2950 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2951 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002952
2953 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2954 // div X, 1 == X
2955 if (RHS->equalsInt(1))
2956 return ReplaceInstUsesWith(I, Op0);
2957
2958 // (X / C1) / C2 -> X / (C1*C2)
2959 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2960 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2961 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002962 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2964 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002965 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Dan Gohman6de29f82009-06-15 22:12:54 +00002966 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002967 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002968
Reid Spencerbca0e382007-03-23 20:05:17 +00002969 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002970 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2972 return R;
2973 if (isa<PHINode>(Op0))
2974 if (Instruction *NV = FoldOpIntoPhi(I))
2975 return NV;
2976 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002977 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002978
Chris Lattnera2881962003-02-18 19:28:33 +00002979 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002980 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002981 if (LHS->equalsInt(0))
2982 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2983
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002984 // It can't be division by zero, hence it must be division by one.
2985 if (I.getType() == Type::Int1Ty)
2986 return ReplaceInstUsesWith(I, Op0);
2987
Nick Lewycky895f0852008-11-27 20:21:08 +00002988 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2989 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2990 // div X, 1 == X
2991 if (X->isOne())
2992 return ReplaceInstUsesWith(I, Op0);
2993 }
2994
Reid Spencer1628cec2006-10-26 06:15:43 +00002995 return 0;
2996}
2997
2998Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3000
3001 // Handle the integer div common cases
3002 if (Instruction *Common = commonIDivTransforms(I))
3003 return Common;
3004
Reid Spencer1628cec2006-10-26 06:15:43 +00003005 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003006 // X udiv C^2 -> X >> C
3007 // Check to see if this is an unsigned division with an exact power of 2,
3008 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003009 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003010 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003011 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003012
3013 // X udiv C, where C >= signbit
3014 if (C->getValue().isNegative()) {
3015 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3016 I);
3017 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3018 ConstantInt::get(I.getType(), 1));
3019 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003020 }
3021
3022 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003023 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 if (RHSI->getOpcode() == Instruction::Shl &&
3025 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003026 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003027 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003028 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003029 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003030 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003031 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003032 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003033 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003035 }
3036 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003037 }
3038
Reid Spencer1628cec2006-10-26 06:15:43 +00003039 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3040 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003042 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003043 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003044 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003045 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003047 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003048 // Construct the "on true" case of the select
3049 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003050 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003051 Op0, TC, SI->getName()+".t");
3052 TSI = InsertNewInstBefore(TSI, I);
3053
3054 // Construct the "on false" case of the select
3055 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003056 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003057 Op0, FC, SI->getName()+".f");
3058 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003059
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003060 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003061 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003062 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003063 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003064 return 0;
3065}
3066
Reid Spencer1628cec2006-10-26 06:15:43 +00003067Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3068 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3069
3070 // Handle the integer div common cases
3071 if (Instruction *Common = commonIDivTransforms(I))
3072 return Common;
3073
3074 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3075 // sdiv X, -1 == -X
3076 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003077 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003078 }
3079
3080 // If the sign bits of both operands are zero (i.e. we can prove they are
3081 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003082 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003083 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003084 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003085 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003086 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003087 }
3088 }
3089
3090 return 0;
3091}
3092
3093Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3094 return commonDivTransforms(I);
3095}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003096
Reid Spencer0a783f72006-11-02 01:53:59 +00003097/// This function implements the transforms on rem instructions that work
3098/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3099/// is used by the visitors to those instructions.
3100/// @brief Transforms common to all three rem instructions
3101Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003103
Chris Lattner50b2ca42008-02-19 06:12:18 +00003104 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3105 if (I.getType()->isFPOrFPVector())
3106 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003107 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003108 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003109 if (isa<UndefValue>(Op1))
3110 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003111
3112 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003113 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3114 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003115
Reid Spencer0a783f72006-11-02 01:53:59 +00003116 return 0;
3117}
3118
3119/// This function implements the transforms common to both integer remainder
3120/// instructions (urem and srem). It is called by the visitors to those integer
3121/// remainder instructions.
3122/// @brief Common integer remainder transforms
3123Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3124 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3125
3126 if (Instruction *common = commonRemTransforms(I))
3127 return common;
3128
Dale Johannesened6af242009-01-21 00:35:19 +00003129 // 0 % X == 0 for integer, we don't need to preserve faults!
3130 if (Constant *LHS = dyn_cast<Constant>(Op0))
3131 if (LHS->isNullValue())
3132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3133
Chris Lattner857e8cd2004-12-12 21:48:58 +00003134 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003135 // X % 0 == undef, we don't need to preserve faults!
3136 if (RHS->equalsInt(0))
3137 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3138
Chris Lattnera2881962003-02-18 19:28:33 +00003139 if (RHS->equalsInt(1)) // X % 1 == 0
3140 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3141
Chris Lattner97943922006-02-28 05:49:21 +00003142 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3144 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3145 return R;
3146 } else if (isa<PHINode>(Op0I)) {
3147 if (Instruction *NV = FoldOpIntoPhi(I))
3148 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003149 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003150
3151 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003152 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003153 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003154 }
Chris Lattnera2881962003-02-18 19:28:33 +00003155 }
3156
Reid Spencer0a783f72006-11-02 01:53:59 +00003157 return 0;
3158}
3159
3160Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3161 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3162
3163 if (Instruction *common = commonIRemTransforms(I))
3164 return common;
3165
3166 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3167 // X urem C^2 -> X and C
3168 // Check to see if this is an unsigned remainder with an exact power of 2,
3169 // if so, convert to a bitwise and.
3170 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003171 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003172 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003173 }
3174
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003175 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003176 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3177 if (RHSI->getOpcode() == Instruction::Shl &&
3178 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003179 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003180 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003181 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003182 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003183 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003184 }
3185 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003186 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003187
Reid Spencer0a783f72006-11-02 01:53:59 +00003188 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3189 // where C1&C2 are powers of two.
3190 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3191 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3192 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3193 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003194 if ((STO->getValue().isPowerOf2()) &&
3195 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003196 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003197 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003198 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003199 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003200 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003201 }
3202 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003203 }
3204
Chris Lattner3f5b8772002-05-06 16:14:14 +00003205 return 0;
3206}
3207
Reid Spencer0a783f72006-11-02 01:53:59 +00003208Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3210
Dan Gohmancff55092007-11-05 23:16:33 +00003211 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003212 if (Instruction *common = commonIRemTransforms(I))
3213 return common;
3214
3215 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003216 if (!isa<Constant>(RHSNeg) ||
3217 (isa<ConstantInt>(RHSNeg) &&
3218 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003219 // X % -Y -> X % Y
3220 AddUsesToWorkList(I);
3221 I.setOperand(1, RHSNeg);
3222 return &I;
3223 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003224
Dan Gohmancff55092007-11-05 23:16:33 +00003225 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003226 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003227 if (I.getType()->isInteger()) {
3228 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3229 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3230 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003231 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003232 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003233 }
3234
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003235 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003236 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3237 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003238
Nick Lewycky9dce8732008-12-20 16:48:00 +00003239 bool hasNegative = false;
3240 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3242 if (RHS->getValue().isNegative())
3243 hasNegative = true;
3244
3245 if (hasNegative) {
3246 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003247 for (unsigned i = 0; i != VWidth; ++i) {
3248 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3249 if (RHS->getValue().isNegative())
3250 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3251 else
3252 Elts[i] = RHS;
3253 }
3254 }
3255
3256 Constant *NewRHSV = ConstantVector::get(Elts);
3257 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003258 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003259 I.setOperand(1, NewRHSV);
3260 return &I;
3261 }
3262 }
3263 }
3264
Reid Spencer0a783f72006-11-02 01:53:59 +00003265 return 0;
3266}
3267
3268Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003269 return commonRemTransforms(I);
3270}
3271
Chris Lattner457dd822004-06-09 07:59:58 +00003272// isOneBitSet - Return true if there is exactly one bit set in the specified
3273// constant.
3274static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003275 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003276}
3277
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003278// isHighOnes - Return true if the constant is of the form 1+0+.
3279// This is the same as lowones(~X).
3280static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003281 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003282}
3283
Reid Spencere4d87aa2006-12-23 06:05:41 +00003284/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003285/// are carefully arranged to allow folding of expressions such as:
3286///
3287/// (A < B) | (A > B) --> (A != B)
3288///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003289/// Note that this is only valid if the first and second predicates have the
3290/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003291///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003292/// Three bits are used to represent the condition, as follows:
3293/// 0 A > B
3294/// 1 A == B
3295/// 2 A < B
3296///
3297/// <=> Value Definition
3298/// 000 0 Always false
3299/// 001 1 A > B
3300/// 010 2 A == B
3301/// 011 3 A >= B
3302/// 100 4 A < B
3303/// 101 5 A != B
3304/// 110 6 A <= B
3305/// 111 7 Always true
3306///
3307static unsigned getICmpCode(const ICmpInst *ICI) {
3308 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003309 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003310 case ICmpInst::ICMP_UGT: return 1; // 001
3311 case ICmpInst::ICMP_SGT: return 1; // 001
3312 case ICmpInst::ICMP_EQ: return 2; // 010
3313 case ICmpInst::ICMP_UGE: return 3; // 011
3314 case ICmpInst::ICMP_SGE: return 3; // 011
3315 case ICmpInst::ICMP_ULT: return 4; // 100
3316 case ICmpInst::ICMP_SLT: return 4; // 100
3317 case ICmpInst::ICMP_NE: return 5; // 101
3318 case ICmpInst::ICMP_ULE: return 6; // 110
3319 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003320 // True -> 7
3321 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003322 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003323 return 0;
3324 }
3325}
3326
Evan Cheng8db90722008-10-14 17:15:11 +00003327/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3328/// predicate into a three bit mask. It also returns whether it is an ordered
3329/// predicate by reference.
3330static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3331 isOrdered = false;
3332 switch (CC) {
3333 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3334 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003335 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3336 case FCmpInst::FCMP_UGT: return 1; // 001
3337 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3338 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003339 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3340 case FCmpInst::FCMP_UGE: return 3; // 011
3341 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3342 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003343 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3344 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003345 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3346 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003347 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003348 default:
3349 // Not expecting FCMP_FALSE and FCMP_TRUE;
3350 assert(0 && "Unexpected FCmp predicate!");
3351 return 0;
3352 }
3353}
3354
Reid Spencere4d87aa2006-12-23 06:05:41 +00003355/// getICmpValue - This is the complement of getICmpCode, which turns an
3356/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003357/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003358/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003359static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3360 switch (code) {
3361 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003362 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003363 case 1:
3364 if (sign)
3365 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3366 else
3367 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3368 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3369 case 3:
3370 if (sign)
3371 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3372 else
3373 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3374 case 4:
3375 if (sign)
3376 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3377 else
3378 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3379 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3380 case 6:
3381 if (sign)
3382 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3383 else
3384 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003385 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003386 }
3387}
3388
Evan Cheng8db90722008-10-14 17:15:11 +00003389/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3390/// opcode and two operands into either a FCmp instruction. isordered is passed
3391/// in to determine which kind of predicate to use in the new fcmp instruction.
3392static Value *getFCmpValue(bool isordered, unsigned code,
3393 Value *LHS, Value *RHS) {
3394 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003395 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003396 case 0:
3397 if (isordered)
3398 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3399 else
3400 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3401 case 1:
3402 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003403 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3404 else
3405 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003406 case 2:
3407 if (isordered)
3408 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3409 else
3410 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003411 case 3:
3412 if (isordered)
3413 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3414 else
3415 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3416 case 4:
3417 if (isordered)
3418 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3419 else
3420 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3421 case 5:
3422 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003423 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3424 else
3425 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3426 case 6:
3427 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003428 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3429 else
3430 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003431 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003432 }
3433}
3434
Chris Lattnerb9553d62008-11-16 04:55:20 +00003435/// PredicatesFoldable - Return true if both predicates match sign or if at
3436/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003437static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3438 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003439 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3440 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003441}
3442
3443namespace {
3444// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3445struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003446 InstCombiner &IC;
3447 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003448 ICmpInst::Predicate pred;
3449 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3450 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3451 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003452 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3454 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003455 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3456 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003457 return false;
3458 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003459 Instruction *apply(Instruction &Log) const {
3460 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3461 if (ICI->getOperand(0) != LHS) {
3462 assert(ICI->getOperand(1) == LHS);
3463 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003464 }
3465
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003466 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003468 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003469 unsigned Code;
3470 switch (Log.getOpcode()) {
3471 case Instruction::And: Code = LHSCode & RHSCode; break;
3472 case Instruction::Or: Code = LHSCode | RHSCode; break;
3473 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003474 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003475 }
3476
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003477 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3478 ICmpInst::isSignedPredicate(ICI->getPredicate());
3479
3480 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003481 if (Instruction *I = dyn_cast<Instruction>(RV))
3482 return I;
3483 // Otherwise, it's a constant boolean value...
3484 return IC.ReplaceInstUsesWith(Log, RV);
3485 }
3486};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003487} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003489// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3490// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003491// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003492Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003493 ConstantInt *OpRHS,
3494 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003495 BinaryOperator &TheAnd) {
3496 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003497 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003498 if (!Op->isShift())
Dan Gohman6de29f82009-06-15 22:12:54 +00003499 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003500
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003501 switch (Op->getOpcode()) {
3502 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003503 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003504 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003505 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003506 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003507 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003508 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003509 }
3510 break;
3511 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003512 if (Together == AndRHS) // (X | C) & C --> C
3513 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003514
Chris Lattner6e7ba452005-01-01 16:22:27 +00003515 if (Op->hasOneUse() && Together != OpRHS) {
3516 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003517 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003518 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003519 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003520 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 }
3522 break;
3523 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003524 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003525 // Adding a one to a single bit bit-field should be turned into an XOR
3526 // of the bit. First thing to check is to see if this AND is with a
3527 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003528 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003529
3530 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003531 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003532 // Ok, at this point, we know that we are masking the result of the
3533 // ADD down to exactly one bit. If the constant we are adding has
3534 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003535 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003536
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 // Check to see if any bits below the one bit set in AndRHSV are set.
3538 if ((AddRHS & (AndRHSV-1)) == 0) {
3539 // If not, the only thing that can effect the output of the AND is
3540 // the bit specified by AndRHSV. If that bit is set, the effect of
3541 // the XOR is to toggle the bit. If it is clear, then the ADD has
3542 // no effect.
3543 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3544 TheAnd.setOperand(0, X);
3545 return &TheAnd;
3546 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003548 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003550 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003551 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003552 }
3553 }
3554 }
3555 }
3556 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003557
3558 case Instruction::Shl: {
3559 // We know that the AND will not produce any of the bits shifted in, so if
3560 // the anded constant includes them, clear them now!
3561 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003562 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003563 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003564 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3565 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003566
Zhou Sheng290bec52007-03-29 08:15:12 +00003567 if (CI->getValue() == ShlMask) {
3568 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003569 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3570 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003571 TheAnd.setOperand(1, CI);
3572 return &TheAnd;
3573 }
3574 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003575 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003576 case Instruction::LShr:
3577 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003578 // We know that the AND will not produce any of the bits shifted in, so if
3579 // the anded constant includes them, clear them now! This only applies to
3580 // unsigned shifts, because a signed shr may bring in set bits!
3581 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003582 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003583 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003584 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3585 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003586
Zhou Sheng290bec52007-03-29 08:15:12 +00003587 if (CI->getValue() == ShrMask) {
3588 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003589 return ReplaceInstUsesWith(TheAnd, Op);
3590 } else if (CI != AndRHS) {
3591 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3592 return &TheAnd;
3593 }
3594 break;
3595 }
3596 case Instruction::AShr:
3597 // Signed shr.
3598 // See if this is shifting in some sign extension, then masking it out
3599 // with an and.
3600 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003602 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003603 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3604 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003605 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003606 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003607 // Make the argument unsigned.
3608 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003609 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003610 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003611 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003612 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003613 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003614 }
3615 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003616 }
3617 return 0;
3618}
3619
Chris Lattner8b170942002-08-09 23:47:40 +00003620
Chris Lattnera96879a2004-09-29 17:40:11 +00003621/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3622/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003623/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3624/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003625/// insert new instructions.
3626Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003627 bool isSigned, bool Inside,
3628 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003629 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003630 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003631 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003632
Chris Lattnera96879a2004-09-29 17:40:11 +00003633 if (Inside) {
3634 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003636
Reid Spencere4d87aa2006-12-23 06:05:41 +00003637 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003638 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003639 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003640 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3641 return new ICmpInst(pred, V, Hi);
3642 }
3643
3644 // Emit V-Lo <u Hi-Lo
3645 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003646 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003647 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3649 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003650 }
3651
3652 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003654
Reid Spencere4e40032007-03-21 23:19:50 +00003655 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003656 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003657 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 ICmpInst::Predicate pred = (isSigned ?
3659 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3660 return new ICmpInst(pred, V, Hi);
3661 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003662
Reid Spencere4e40032007-03-21 23:19:50 +00003663 // Emit V-Lo >u Hi-1-Lo
3664 // Note that Hi has already had one subtracted from it, above.
3665 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003666 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003667 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003668 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3669 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003670}
3671
Chris Lattner7203e152005-09-18 07:22:02 +00003672// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3673// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3674// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3675// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003676static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003677 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003678 uint32_t BitWidth = Val->getType()->getBitWidth();
3679 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003680
3681 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003682 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003683 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003684 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003685 return true;
3686}
3687
Chris Lattner7203e152005-09-18 07:22:02 +00003688/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3689/// where isSub determines whether the operator is a sub. If we can fold one of
3690/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003691///
3692/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3693/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3694/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3695///
3696/// return (A +/- B).
3697///
3698Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003699 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003700 Instruction &I) {
3701 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3702 if (!LHSI || LHSI->getNumOperands() != 2 ||
3703 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3704
3705 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3706
3707 switch (LHSI->getOpcode()) {
3708 default: return 0;
3709 case Instruction::And:
Dan Gohman6de29f82009-06-15 22:12:54 +00003710 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003711 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003712 if ((Mask->getValue().countLeadingZeros() +
3713 Mask->getValue().countPopulation()) ==
3714 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003715 break;
3716
3717 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3718 // part, we don't need any explicit masks to take them out of A. If that
3719 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003720 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003721 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003722 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003723 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003724 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003725 break;
3726 }
3727 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003728 return 0;
3729 case Instruction::Or:
3730 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003731 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003732 if ((Mask->getValue().countLeadingZeros() +
3733 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Dan Gohman6de29f82009-06-15 22:12:54 +00003734 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003735 break;
3736 return 0;
3737 }
3738
3739 Instruction *New;
3740 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003741 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003742 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003743 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003744 return InsertNewInstBefore(New, I);
3745}
3746
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003747/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3748Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3749 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003750 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003751 ConstantInt *LHSCst, *RHSCst;
3752 ICmpInst::Predicate LHSCC, RHSCC;
3753
Chris Lattnerea065fb2008-11-16 05:10:52 +00003754 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003755 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003756 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003757 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003758
3759 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3760 // where C is a power of 2
3761 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3762 LHSCst->getValue().isPowerOf2()) {
3763 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3764 InsertNewInstBefore(NewOr, I);
3765 return new ICmpInst(LHSCC, NewOr, LHSCst);
3766 }
3767
3768 // From here on, we only handle:
3769 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3770 if (Val != Val2) return 0;
3771
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003772 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3773 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3774 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3775 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3776 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3777 return 0;
3778
3779 // We can't fold (ugt x, C) & (sgt x, C2).
3780 if (!PredicatesFoldable(LHSCC, RHSCC))
3781 return 0;
3782
3783 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003784 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003785 if (ICmpInst::isSignedPredicate(LHSCC) ||
3786 (ICmpInst::isEquality(LHSCC) &&
3787 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003788 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003789 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003790 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3791
3792 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003793 std::swap(LHS, RHS);
3794 std::swap(LHSCst, RHSCst);
3795 std::swap(LHSCC, RHSCC);
3796 }
3797
3798 // At this point, we know we have have two icmp instructions
3799 // comparing a value against two constants and and'ing the result
3800 // together. Because of the above check, we know that we only have
3801 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3802 // (from the FoldICmpLogical check above), that the two constants
3803 // are not equal and that the larger constant is on the RHS
3804 assert(LHSCst != RHSCst && "Compares not folded above?");
3805
3806 switch (LHSCC) {
3807 default: assert(0 && "Unknown integer condition code!");
3808 case ICmpInst::ICMP_EQ:
3809 switch (RHSCC) {
3810 default: assert(0 && "Unknown integer condition code!");
3811 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3812 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3813 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3814 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3815 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3816 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3817 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3818 return ReplaceInstUsesWith(I, LHS);
3819 }
3820 case ICmpInst::ICMP_NE:
3821 switch (RHSCC) {
3822 default: assert(0 && "Unknown integer condition code!");
3823 case ICmpInst::ICMP_ULT:
3824 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3825 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3826 break; // (X != 13 & X u< 15) -> no change
3827 case ICmpInst::ICMP_SLT:
3828 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3829 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3830 break; // (X != 13 & X s< 15) -> no change
3831 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3832 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3833 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3834 return ReplaceInstUsesWith(I, RHS);
3835 case ICmpInst::ICMP_NE:
3836 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3837 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3838 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3839 Val->getName()+".off");
3840 InsertNewInstBefore(Add, I);
3841 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3842 ConstantInt::get(Add->getType(), 1));
3843 }
3844 break; // (X != 13 & X != 15) -> no change
3845 }
3846 break;
3847 case ICmpInst::ICMP_ULT:
3848 switch (RHSCC) {
3849 default: assert(0 && "Unknown integer condition code!");
3850 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3851 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3852 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3853 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3854 break;
3855 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3856 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3857 return ReplaceInstUsesWith(I, LHS);
3858 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3859 break;
3860 }
3861 break;
3862 case ICmpInst::ICMP_SLT:
3863 switch (RHSCC) {
3864 default: assert(0 && "Unknown integer condition code!");
3865 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3866 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3867 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3868 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3869 break;
3870 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3871 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3872 return ReplaceInstUsesWith(I, LHS);
3873 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3874 break;
3875 }
3876 break;
3877 case ICmpInst::ICMP_UGT:
3878 switch (RHSCC) {
3879 default: assert(0 && "Unknown integer condition code!");
3880 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3881 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3882 return ReplaceInstUsesWith(I, RHS);
3883 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3884 break;
3885 case ICmpInst::ICMP_NE:
3886 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3887 return new ICmpInst(LHSCC, Val, RHSCst);
3888 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003889 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003890 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3891 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3892 break;
3893 }
3894 break;
3895 case ICmpInst::ICMP_SGT:
3896 switch (RHSCC) {
3897 default: assert(0 && "Unknown integer condition code!");
3898 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3899 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3900 return ReplaceInstUsesWith(I, RHS);
3901 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3902 break;
3903 case ICmpInst::ICMP_NE:
3904 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3905 return new ICmpInst(LHSCC, Val, RHSCst);
3906 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003907 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003908 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3909 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3910 break;
3911 }
3912 break;
3913 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003914
3915 return 0;
3916}
3917
3918
Chris Lattner7e708292002-06-25 16:13:24 +00003919Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003920 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003921 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003922
Chris Lattnere87597f2004-10-16 18:11:37 +00003923 if (isa<UndefValue>(Op1)) // X & undef -> 0
3924 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3925
Chris Lattner6e7ba452005-01-01 16:22:27 +00003926 // and X, X = X
3927 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003928 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003929
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003930 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003931 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003932 if (SimplifyDemandedInstructionBits(I))
3933 return &I;
3934 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003935 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003936 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003937 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003938 } else if (isa<ConstantAggregateZero>(Op1)) {
3939 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003940 }
3941 }
Dan Gohman6de29f82009-06-15 22:12:54 +00003942
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003943 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003944 const APInt& AndRHSMask = AndRHS->getValue();
3945 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003946
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003947 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003948 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003949 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003950 Value *Op0LHS = Op0I->getOperand(0);
3951 Value *Op0RHS = Op0I->getOperand(1);
3952 switch (Op0I->getOpcode()) {
3953 case Instruction::Xor:
3954 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003955 // If the mask is only needed on one incoming arm, push it up.
3956 if (Op0I->hasOneUse()) {
3957 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3958 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003959 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003960 Op0RHS->getName()+".masked");
3961 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003962 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003963 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003964 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003965 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003966 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3967 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003968 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003969 Op0LHS->getName()+".masked");
3970 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003971 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003972 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3973 }
3974 }
3975
Chris Lattner6e7ba452005-01-01 16:22:27 +00003976 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003977 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003978 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3979 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3980 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3981 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003982 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003983 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003984 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003985 break;
3986
3987 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003988 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3989 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3990 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3991 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003992 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003993
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003994 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3995 // has 1's for all bits that the subtraction with A might affect.
3996 if (Op0I->hasOneUse()) {
3997 uint32_t BitWidth = AndRHSMask.getBitWidth();
3998 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3999 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4000
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004001 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004002 if (!(A && A->isZero()) && // avoid infinite recursion.
4003 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004004 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4005 InsertNewInstBefore(NewNeg, I);
4006 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4007 }
4008 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004009 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004010
4011 case Instruction::Shl:
4012 case Instruction::LShr:
4013 // (1 << x) & 1 --> zext(x == 0)
4014 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004015 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004016 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4017 Constant::getNullValue(I.getType()));
4018 InsertNewInstBefore(NewICmp, I);
4019 return new ZExtInst(NewICmp, I.getType());
4020 }
4021 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004022 }
4023
Chris Lattner58403262003-07-23 19:25:52 +00004024 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004025 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004026 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004027 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004028 // If this is an integer truncation or change from signed-to-unsigned, and
4029 // if the source is an and/or with immediate, transform it. This
4030 // frequently occurs for bitfield accesses.
4031 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004032 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004033 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004034 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004035 if (CastOp->getOpcode() == Instruction::And) {
4036 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004037 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4038 // This will fold the two constants together, which may allow
4039 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004040 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004041 CastOp->getOperand(0), I.getType(),
4042 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004043 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004044 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004045 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004046 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004047 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004048 } else if (CastOp->getOpcode() == Instruction::Or) {
4049 // Change: and (cast (or X, C1) to T), C2
4050 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004051 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004052 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4053 return ReplaceInstUsesWith(I, AndRHS);
4054 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004055 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004056 }
Chris Lattner06782f82003-07-23 19:36:21 +00004057 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004058
4059 // Try to fold constant and into select arguments.
4060 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004061 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004062 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004063 if (isa<PHINode>(Op0))
4064 if (Instruction *NV = FoldOpIntoPhi(I))
4065 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004066 }
4067
Chris Lattner8d969642003-03-10 23:06:50 +00004068 Value *Op0NotVal = dyn_castNotVal(Op0);
4069 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004070
Chris Lattner5b62aa72004-06-18 06:07:51 +00004071 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4073
Misha Brukmancb6267b2004-07-30 12:50:08 +00004074 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004075 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004076 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004077 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004078 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004080 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004081
4082 {
Chris Lattner003b6202007-06-15 05:58:24 +00004083 Value *A = 0, *B = 0, *C = 0, *D = 0;
4084 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004085 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4086 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004087
4088 // (A|B) & ~(A&B) -> A^B
4089 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4090 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004091 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004092 }
4093 }
4094
4095 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004096 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4097 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004098
4099 // ~(A&B) & (A|B) -> A^B
4100 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4101 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004102 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004103 }
4104 }
Chris Lattner64daab52006-04-01 08:03:55 +00004105
4106 if (Op0->hasOneUse() &&
4107 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4108 if (A == Op1) { // (A^B)&A -> A&(A^B)
4109 I.swapOperands(); // Simplify below
4110 std::swap(Op0, Op1);
4111 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4112 cast<BinaryOperator>(Op0)->swapOperands();
4113 I.swapOperands(); // Simplify below
4114 std::swap(Op0, Op1);
4115 }
4116 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004117
Chris Lattner64daab52006-04-01 08:03:55 +00004118 if (Op1->hasOneUse() &&
4119 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4120 if (B == Op0) { // B&(A^B) -> B&(B^A)
4121 cast<BinaryOperator>(Op1)->swapOperands();
4122 std::swap(A, B);
4123 }
4124 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004125 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004126 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004127 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004128 }
4129 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004130
4131 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004132 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4133 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4134 return BinaryOperator::CreateAnd(A, Op1);
4135 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4136 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4137 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004138 }
4139
Reid Spencere4d87aa2006-12-23 06:05:41 +00004140 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4141 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4142 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004143 return R;
4144
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004145 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4146 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4147 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004148 }
4149
Chris Lattner6fc205f2006-05-05 06:39:07 +00004150 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004151 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4152 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4153 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4154 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004155 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004156 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004157 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4158 I.getType(), TD) &&
4159 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4160 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004161 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004162 Op1C->getOperand(0),
4163 I.getName());
4164 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004165 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004166 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004167 }
Chris Lattnere511b742006-11-14 07:46:50 +00004168
4169 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004170 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4171 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4172 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004173 SI0->getOperand(1) == SI1->getOperand(1) &&
4174 (SI0->hasOneUse() || SI1->hasOneUse())) {
4175 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004176 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004177 SI1->getOperand(0),
4178 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004179 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004180 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004181 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004182 }
4183
Evan Cheng8db90722008-10-14 17:15:11 +00004184 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004185 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4186 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4187 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004188 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4189 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004190 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4191 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4192 // If either of the constants are nans, then the whole thing returns
4193 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004194 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004195 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4196 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4197 RHS->getOperand(0));
4198 }
Evan Cheng8db90722008-10-14 17:15:11 +00004199 } else {
4200 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4201 FCmpInst::Predicate Op0CC, Op1CC;
4202 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4203 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004204 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4205 // Swap RHS operands to match LHS.
4206 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4207 std::swap(Op1LHS, Op1RHS);
4208 }
Evan Cheng8db90722008-10-14 17:15:11 +00004209 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4210 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4211 if (Op0CC == Op1CC)
4212 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4213 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4214 Op1CC == FCmpInst::FCMP_FALSE)
4215 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4216 else if (Op0CC == FCmpInst::FCMP_TRUE)
4217 return ReplaceInstUsesWith(I, Op1);
4218 else if (Op1CC == FCmpInst::FCMP_TRUE)
4219 return ReplaceInstUsesWith(I, Op0);
4220 bool Op0Ordered;
4221 bool Op1Ordered;
4222 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4223 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4224 if (Op1Pred == 0) {
4225 std::swap(Op0, Op1);
4226 std::swap(Op0Pred, Op1Pred);
4227 std::swap(Op0Ordered, Op1Ordered);
4228 }
4229 if (Op0Pred == 0) {
4230 // uno && ueq -> uno && (uno || eq) -> ueq
4231 // ord && olt -> ord && (ord && lt) -> olt
4232 if (Op0Ordered == Op1Ordered)
4233 return ReplaceInstUsesWith(I, Op1);
4234 // uno && oeq -> uno && (ord && eq) -> false
4235 // uno && ord -> false
4236 if (!Op0Ordered)
4237 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4238 // ord && ueq -> ord && (uno || eq) -> oeq
4239 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4240 Op0LHS, Op0RHS));
4241 }
4242 }
4243 }
4244 }
Chris Lattner99c65742007-10-24 05:38:08 +00004245 }
4246 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004247
Chris Lattner7e708292002-06-25 16:13:24 +00004248 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004249}
4250
Chris Lattner8c34cd22008-10-05 02:13:19 +00004251/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4252/// capable of providing pieces of a bswap. The subexpression provides pieces
4253/// of a bswap if it is proven that each of the non-zero bytes in the output of
4254/// the expression came from the corresponding "byte swapped" byte in some other
4255/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4256/// we know that the expression deposits the low byte of %X into the high byte
4257/// of the bswap result and that all other bytes are zero. This expression is
4258/// accepted, the high byte of ByteValues is set to X to indicate a correct
4259/// match.
4260///
4261/// This function returns true if the match was unsuccessful and false if so.
4262/// On entry to the function the "OverallLeftShift" is a signed integer value
4263/// indicating the number of bytes that the subexpression is later shifted. For
4264/// example, if the expression is later right shifted by 16 bits, the
4265/// OverallLeftShift value would be -2 on entry. This is used to specify which
4266/// byte of ByteValues is actually being set.
4267///
4268/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4269/// byte is masked to zero by a user. For example, in (X & 255), X will be
4270/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4271/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4272/// always in the local (OverallLeftShift) coordinate space.
4273///
4274static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4275 SmallVector<Value*, 8> &ByteValues) {
4276 if (Instruction *I = dyn_cast<Instruction>(V)) {
4277 // If this is an or instruction, it may be an inner node of the bswap.
4278 if (I->getOpcode() == Instruction::Or) {
4279 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4280 ByteValues) ||
4281 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4282 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004283 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004284
4285 // If this is a logical shift by a constant multiple of 8, recurse with
4286 // OverallLeftShift and ByteMask adjusted.
4287 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4288 unsigned ShAmt =
4289 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4290 // Ensure the shift amount is defined and of a byte value.
4291 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4292 return true;
4293
4294 unsigned ByteShift = ShAmt >> 3;
4295 if (I->getOpcode() == Instruction::Shl) {
4296 // X << 2 -> collect(X, +2)
4297 OverallLeftShift += ByteShift;
4298 ByteMask >>= ByteShift;
4299 } else {
4300 // X >>u 2 -> collect(X, -2)
4301 OverallLeftShift -= ByteShift;
4302 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004303 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004304 }
4305
4306 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4307 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4308
4309 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4310 ByteValues);
4311 }
4312
4313 // If this is a logical 'and' with a mask that clears bytes, clear the
4314 // corresponding bytes in ByteMask.
4315 if (I->getOpcode() == Instruction::And &&
4316 isa<ConstantInt>(I->getOperand(1))) {
4317 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4318 unsigned NumBytes = ByteValues.size();
4319 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4320 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4321
4322 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4323 // If this byte is masked out by a later operation, we don't care what
4324 // the and mask is.
4325 if ((ByteMask & (1 << i)) == 0)
4326 continue;
4327
4328 // If the AndMask is all zeros for this byte, clear the bit.
4329 APInt MaskB = AndMask & Byte;
4330 if (MaskB == 0) {
4331 ByteMask &= ~(1U << i);
4332 continue;
4333 }
4334
4335 // If the AndMask is not all ones for this byte, it's not a bytezap.
4336 if (MaskB != Byte)
4337 return true;
4338
4339 // Otherwise, this byte is kept.
4340 }
4341
4342 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4343 ByteValues);
4344 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004345 }
4346
Chris Lattner8c34cd22008-10-05 02:13:19 +00004347 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4348 // the input value to the bswap. Some observations: 1) if more than one byte
4349 // is demanded from this input, then it could not be successfully assembled
4350 // into a byteswap. At least one of the two bytes would not be aligned with
4351 // their ultimate destination.
4352 if (!isPowerOf2_32(ByteMask)) return true;
4353 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004354
Chris Lattner8c34cd22008-10-05 02:13:19 +00004355 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4356 // is demanded, it needs to go into byte 0 of the result. This means that the
4357 // byte needs to be shifted until it lands in the right byte bucket. The
4358 // shift amount depends on the position: if the byte is coming from the high
4359 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4360 // low part, it must be shifted left.
4361 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4362 if (InputByteNo < ByteValues.size()/2) {
4363 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4364 return true;
4365 } else {
4366 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4367 return true;
4368 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004369
4370 // If the destination byte value is already defined, the values are or'd
4371 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004372 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004373 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004374 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004375 return false;
4376}
4377
4378/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4379/// If so, insert the new bswap intrinsic and return it.
4380Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004381 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004382 if (!ITy || ITy->getBitWidth() % 16 ||
4383 // ByteMask only allows up to 32-byte values.
4384 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004385 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004386
4387 /// ByteValues - For each byte of the result, we keep track of which value
4388 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004389 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004390 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004391
4392 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004393 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4394 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004395 return 0;
4396
4397 // Check to see if all of the bytes come from the same value.
4398 Value *V = ByteValues[0];
4399 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4400
4401 // Check to make sure that all of the bytes come from the same value.
4402 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4403 if (ByteValues[i] != V)
4404 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004405 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004406 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004407 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004408 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004409}
4410
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004411/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4412/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4413/// we can simplify this expression to "cond ? C : D or B".
4414static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4415 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004416 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004417 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004418 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004419 return 0;
4420
Chris Lattnera6a474d2008-11-16 04:26:55 +00004421 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004422 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004423 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004424 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004425 return SelectInst::Create(Cond, C, B);
4426 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004427 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004428 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004429 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004430 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004431 return 0;
4432}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004433
Chris Lattner69d4ced2008-11-16 05:20:07 +00004434/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4435Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4436 ICmpInst *LHS, ICmpInst *RHS) {
4437 Value *Val, *Val2;
4438 ConstantInt *LHSCst, *RHSCst;
4439 ICmpInst::Predicate LHSCC, RHSCC;
4440
4441 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4442 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4443 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4444 return 0;
4445
4446 // From here on, we only handle:
4447 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4448 if (Val != Val2) return 0;
4449
4450 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4451 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4452 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4453 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4454 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4455 return 0;
4456
4457 // We can't fold (ugt x, C) | (sgt x, C2).
4458 if (!PredicatesFoldable(LHSCC, RHSCC))
4459 return 0;
4460
4461 // Ensure that the larger constant is on the RHS.
4462 bool ShouldSwap;
4463 if (ICmpInst::isSignedPredicate(LHSCC) ||
4464 (ICmpInst::isEquality(LHSCC) &&
4465 ICmpInst::isSignedPredicate(RHSCC)))
4466 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4467 else
4468 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4469
4470 if (ShouldSwap) {
4471 std::swap(LHS, RHS);
4472 std::swap(LHSCst, RHSCst);
4473 std::swap(LHSCC, RHSCC);
4474 }
4475
4476 // At this point, we know we have have two icmp instructions
4477 // comparing a value against two constants and or'ing the result
4478 // together. Because of the above check, we know that we only have
4479 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4480 // FoldICmpLogical check above), that the two constants are not
4481 // equal.
4482 assert(LHSCst != RHSCst && "Compares not folded above?");
4483
4484 switch (LHSCC) {
4485 default: assert(0 && "Unknown integer condition code!");
4486 case ICmpInst::ICMP_EQ:
4487 switch (RHSCC) {
4488 default: assert(0 && "Unknown integer condition code!");
4489 case ICmpInst::ICMP_EQ:
4490 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4491 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4492 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4493 Val->getName()+".off");
4494 InsertNewInstBefore(Add, I);
Dan Gohman6de29f82009-06-15 22:12:54 +00004495 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004496 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4497 }
4498 break; // (X == 13 | X == 15) -> no change
4499 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4500 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4501 break;
4502 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4503 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4504 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4505 return ReplaceInstUsesWith(I, RHS);
4506 }
4507 break;
4508 case ICmpInst::ICMP_NE:
4509 switch (RHSCC) {
4510 default: assert(0 && "Unknown integer condition code!");
4511 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4512 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4513 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4514 return ReplaceInstUsesWith(I, LHS);
4515 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4516 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4517 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4518 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4519 }
4520 break;
4521 case ICmpInst::ICMP_ULT:
4522 switch (RHSCC) {
4523 default: assert(0 && "Unknown integer condition code!");
4524 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4525 break;
4526 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4527 // If RHSCst is [us]MAXINT, it is always false. Not handling
4528 // this can cause overflow.
4529 if (RHSCst->isMaxValue(false))
4530 return ReplaceInstUsesWith(I, LHS);
4531 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4532 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4533 break;
4534 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4535 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4536 return ReplaceInstUsesWith(I, RHS);
4537 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4538 break;
4539 }
4540 break;
4541 case ICmpInst::ICMP_SLT:
4542 switch (RHSCC) {
4543 default: assert(0 && "Unknown integer condition code!");
4544 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4545 break;
4546 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4547 // If RHSCst is [us]MAXINT, it is always false. Not handling
4548 // this can cause overflow.
4549 if (RHSCst->isMaxValue(true))
4550 return ReplaceInstUsesWith(I, LHS);
4551 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4552 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4553 break;
4554 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4555 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4556 return ReplaceInstUsesWith(I, RHS);
4557 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4558 break;
4559 }
4560 break;
4561 case ICmpInst::ICMP_UGT:
4562 switch (RHSCC) {
4563 default: assert(0 && "Unknown integer condition code!");
4564 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4565 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4566 return ReplaceInstUsesWith(I, LHS);
4567 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4568 break;
4569 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4570 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4571 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4572 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4573 break;
4574 }
4575 break;
4576 case ICmpInst::ICMP_SGT:
4577 switch (RHSCC) {
4578 default: assert(0 && "Unknown integer condition code!");
4579 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4580 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4581 return ReplaceInstUsesWith(I, LHS);
4582 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4583 break;
4584 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4585 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4586 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4587 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4588 break;
4589 }
4590 break;
4591 }
4592 return 0;
4593}
4594
Bill Wendlinga698a472008-12-01 08:23:25 +00004595/// FoldOrWithConstants - This helper function folds:
4596///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004597/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004598///
4599/// into:
4600///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004601/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004602///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004603/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004604Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004605 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004606 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4607 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004608
Bill Wendling286a0542008-12-02 06:24:20 +00004609 Value *V1 = 0;
4610 ConstantInt *CI2 = 0;
4611 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004612
Bill Wendling29976b92008-12-02 06:18:11 +00004613 APInt Xor = CI1->getValue() ^ CI2->getValue();
4614 if (!Xor.isAllOnesValue()) return 0;
4615
Bill Wendling286a0542008-12-02 06:24:20 +00004616 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004617 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004618 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4619 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004620 }
4621
4622 return 0;
4623}
4624
Chris Lattner7e708292002-06-25 16:13:24 +00004625Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004626 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004627 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004628
Chris Lattner42593e62007-03-24 23:56:43 +00004629 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004630 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004631
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004632 // or X, X = X
4633 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004634 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004635
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004636 // See if we can simplify any instructions used by the instruction whose sole
4637 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004638 if (SimplifyDemandedInstructionBits(I))
4639 return &I;
4640 if (isa<VectorType>(I.getType())) {
4641 if (isa<ConstantAggregateZero>(Op1)) {
4642 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4643 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4644 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4645 return ReplaceInstUsesWith(I, I.getOperand(1));
4646 }
Chris Lattner42593e62007-03-24 23:56:43 +00004647 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004648
Chris Lattner3f5b8772002-05-06 16:14:14 +00004649 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004650 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004651 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004652 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4653 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004654 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004655 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004656 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004657 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004658 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004659 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004660
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004661 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4662 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004663 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004664 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004665 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004666 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004667 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004668 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004669
4670 // Try to fold constant and into select arguments.
4671 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004672 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004673 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004674 if (isa<PHINode>(Op0))
4675 if (Instruction *NV = FoldOpIntoPhi(I))
4676 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004677 }
4678
Chris Lattner4f637d42006-01-06 17:59:59 +00004679 Value *A = 0, *B = 0;
4680 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004681
4682 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4683 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4684 return ReplaceInstUsesWith(I, Op1);
4685 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4686 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4687 return ReplaceInstUsesWith(I, Op0);
4688
Chris Lattner6423d4c2006-07-10 20:25:24 +00004689 // (A | B) | C and A | (B | C) -> bswap if possible.
4690 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004691 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004692 match(Op1, m_Or(m_Value(), m_Value())) ||
4693 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4694 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004695 if (Instruction *BSwap = MatchBSwap(I))
4696 return BSwap;
4697 }
4698
Chris Lattner6e4c6492005-05-09 04:58:36 +00004699 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4700 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004701 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004702 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004703 InsertNewInstBefore(NOr, I);
4704 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004705 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004706 }
4707
4708 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4709 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004710 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004711 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004712 InsertNewInstBefore(NOr, I);
4713 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004714 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004715 }
4716
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004717 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004718 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004719 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4720 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004721 Value *V1 = 0, *V2 = 0, *V3 = 0;
4722 C1 = dyn_cast<ConstantInt>(C);
4723 C2 = dyn_cast<ConstantInt>(D);
4724 if (C1 && C2) { // (A & C1)|(B & C2)
4725 // If we have: ((V + N) & C1) | (V & C2)
4726 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4727 // replace with V+N.
4728 if (C1->getValue() == ~C2->getValue()) {
4729 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4730 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4731 // Add commutes, try both ways.
4732 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4733 return ReplaceInstUsesWith(I, A);
4734 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4735 return ReplaceInstUsesWith(I, A);
4736 }
4737 // Or commutes, try both ways.
4738 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4739 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4740 // Add commutes, try both ways.
4741 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4742 return ReplaceInstUsesWith(I, B);
4743 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4744 return ReplaceInstUsesWith(I, B);
4745 }
4746 }
Chris Lattner044e5332007-04-08 08:01:49 +00004747 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004748 }
4749
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004750 // Check to see if we have any common things being and'ed. If so, find the
4751 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004752 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4753 if (A == B) // (A & C)|(A & D) == A & (C|D)
4754 V1 = A, V2 = C, V3 = D;
4755 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4756 V1 = A, V2 = B, V3 = C;
4757 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4758 V1 = C, V2 = A, V3 = D;
4759 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4760 V1 = C, V2 = A, V3 = B;
4761
4762 if (V1) {
4763 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004764 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4765 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004766 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004767 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004768
Dan Gohman1975d032008-10-30 20:40:10 +00004769 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004770 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4771 return Match;
4772 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4773 return Match;
4774 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4775 return Match;
4776 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4777 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004778
Bill Wendlingb01865c2008-11-30 13:52:49 +00004779 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004780 if ((match(C, m_Not(m_Specific(D))) &&
4781 match(B, m_Not(m_Specific(A)))))
4782 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004783 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004784 if ((match(A, m_Not(m_Specific(D))) &&
4785 match(B, m_Not(m_Specific(C)))))
4786 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004787 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004788 if ((match(C, m_Not(m_Specific(B))) &&
4789 match(D, m_Not(m_Specific(A)))))
4790 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004791 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004792 if ((match(A, m_Not(m_Specific(B))) &&
4793 match(D, m_Not(m_Specific(C)))))
4794 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004795 }
Chris Lattnere511b742006-11-14 07:46:50 +00004796
4797 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004798 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4799 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4800 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004801 SI0->getOperand(1) == SI1->getOperand(1) &&
4802 (SI0->hasOneUse() || SI1->hasOneUse())) {
4803 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004804 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004805 SI1->getOperand(0),
4806 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004807 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004808 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004809 }
4810 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004811
Bill Wendlingb3833d12008-12-01 01:07:11 +00004812 // ((A|B)&1)|(B&-2) -> (A&1) | B
4813 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4814 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004815 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004816 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004817 }
4818 // (B&-2)|((A|B)&1) -> (A&1) | B
4819 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4820 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004821 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004822 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004823 }
4824
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004825 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4826 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004827 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004828 } else {
4829 A = 0;
4830 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004831 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004832 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4833 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004834 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004835
Misha Brukmancb6267b2004-07-30 12:50:08 +00004836 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004837 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004838 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004839 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004840 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004841 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004842 }
Chris Lattnera2881962003-02-18 19:28:33 +00004843
Reid Spencere4d87aa2006-12-23 06:05:41 +00004844 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4845 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4846 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004847 return R;
4848
Chris Lattner69d4ced2008-11-16 05:20:07 +00004849 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4850 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4851 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004852 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004853
4854 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004855 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004856 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004857 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004858 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4859 !isa<ICmpInst>(Op1C->getOperand(0))) {
4860 const Type *SrcTy = Op0C->getOperand(0)->getType();
4861 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4862 // Only do this if the casts both really cause code to be
4863 // generated.
4864 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4865 I.getType(), TD) &&
4866 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4867 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004868 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004869 Op1C->getOperand(0),
4870 I.getName());
4871 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004872 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004873 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004874 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004875 }
Chris Lattner99c65742007-10-24 05:38:08 +00004876 }
4877
4878
4879 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4880 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4881 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4882 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004883 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004884 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004885 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4886 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4887 // If either of the constants are nans, then the whole thing returns
4888 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004889 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004890 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4891
4892 // Otherwise, no need to compare the two constants, compare the
4893 // rest.
4894 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4895 RHS->getOperand(0));
4896 }
Evan Cheng40300622008-10-14 18:44:08 +00004897 } else {
4898 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4899 FCmpInst::Predicate Op0CC, Op1CC;
4900 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4901 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4902 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4903 // Swap RHS operands to match LHS.
4904 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4905 std::swap(Op1LHS, Op1RHS);
4906 }
4907 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4908 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4909 if (Op0CC == Op1CC)
4910 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4911 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4912 Op1CC == FCmpInst::FCMP_TRUE)
4913 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4914 else if (Op0CC == FCmpInst::FCMP_FALSE)
4915 return ReplaceInstUsesWith(I, Op1);
4916 else if (Op1CC == FCmpInst::FCMP_FALSE)
4917 return ReplaceInstUsesWith(I, Op0);
4918 bool Op0Ordered;
4919 bool Op1Ordered;
4920 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4921 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4922 if (Op0Ordered == Op1Ordered) {
4923 // If both are ordered or unordered, return a new fcmp with
4924 // or'ed predicates.
4925 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4926 Op0LHS, Op0RHS);
4927 if (Instruction *I = dyn_cast<Instruction>(RV))
4928 return I;
4929 // Otherwise, it's a constant boolean value...
4930 return ReplaceInstUsesWith(I, RV);
4931 }
4932 }
4933 }
4934 }
Chris Lattner99c65742007-10-24 05:38:08 +00004935 }
4936 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004937
Chris Lattner7e708292002-06-25 16:13:24 +00004938 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004939}
4940
Dan Gohman844731a2008-05-13 00:00:25 +00004941namespace {
4942
Chris Lattnerc317d392004-02-16 01:20:27 +00004943// XorSelf - Implements: X ^ X --> 0
4944struct XorSelf {
4945 Value *RHS;
4946 XorSelf(Value *rhs) : RHS(rhs) {}
4947 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4948 Instruction *apply(BinaryOperator &Xor) const {
4949 return &Xor;
4950 }
4951};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004952
Dan Gohman844731a2008-05-13 00:00:25 +00004953}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004954
Chris Lattner7e708292002-06-25 16:13:24 +00004955Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004956 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004958
Evan Chengd34af782008-03-25 20:07:13 +00004959 if (isa<UndefValue>(Op1)) {
4960 if (isa<UndefValue>(Op0))
4961 // Handle undef ^ undef -> 0 special case. This is a common
4962 // idiom (misuse).
4963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004964 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004965 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004966
Chris Lattnerc317d392004-02-16 01:20:27 +00004967 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4968 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004969 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004971 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004972
4973 // See if we can simplify any instructions used by the instruction whose sole
4974 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004975 if (SimplifyDemandedInstructionBits(I))
4976 return &I;
4977 if (isa<VectorType>(I.getType()))
4978 if (isa<ConstantAggregateZero>(Op1))
4979 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00004980
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004981 // Is this a ~ operation?
4982 if (Value *NotOp = dyn_castNotVal(&I)) {
4983 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4984 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4985 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4986 if (Op0I->getOpcode() == Instruction::And ||
4987 Op0I->getOpcode() == Instruction::Or) {
4988 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4989 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4990 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004991 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004992 Op0I->getOperand(1)->getName()+".not");
4993 InsertNewInstBefore(NotY, I);
4994 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004995 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004996 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004997 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004998 }
4999 }
5000 }
5001 }
5002
5003
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005004 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005005 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005006 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005007 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005008 return new ICmpInst(ICI->getInversePredicate(),
5009 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005010
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005011 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5012 return new FCmpInst(FCI->getInversePredicate(),
5013 FCI->getOperand(0), FCI->getOperand(1));
5014 }
5015
Nick Lewycky517e1f52008-05-31 19:01:33 +00005016 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5017 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5018 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5019 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5020 Instruction::CastOps Opcode = Op0C->getOpcode();
5021 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5022 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5023 Op0C->getDestTy())) {
5024 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5025 CI->getOpcode(), CI->getInversePredicate(),
5026 CI->getOperand(0), CI->getOperand(1)), I);
5027 NewCI->takeName(CI);
5028 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5029 }
5030 }
5031 }
5032 }
5033 }
5034
Reid Spencere4d87aa2006-12-23 06:05:41 +00005035 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005036 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005037 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5038 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005039 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5040 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005041 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005042 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005043 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005044
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005045 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005046 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005047 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005048 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005049 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005050 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005051 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005052 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005053 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005054 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005055 // (X + C) ^ signbit -> (X + C + signbit)
5056 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005057 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005058
Chris Lattner7c4049c2004-01-12 19:35:11 +00005059 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005060 } else if (Op0I->getOpcode() == Instruction::Or) {
5061 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005062 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005063 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5064 // Anything in both C1 and C2 is known to be zero, remove it from
5065 // NewRHS.
Dan Gohman6de29f82009-06-15 22:12:54 +00005066 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005067 NewRHS = ConstantExpr::getAnd(NewRHS,
5068 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005069 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005070 I.setOperand(0, Op0I->getOperand(0));
5071 I.setOperand(1, NewRHS);
5072 return &I;
5073 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005074 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005075 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005076 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005077
5078 // Try to fold constant and into select arguments.
5079 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005080 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005081 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005082 if (isa<PHINode>(Op0))
5083 if (Instruction *NV = FoldOpIntoPhi(I))
5084 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005085 }
5086
Chris Lattner8d969642003-03-10 23:06:50 +00005087 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005088 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005089 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005090
Chris Lattner8d969642003-03-10 23:06:50 +00005091 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005092 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005093 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005094
Chris Lattner318bf792007-03-18 22:51:34 +00005095
5096 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5097 if (Op1I) {
5098 Value *A, *B;
5099 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5100 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005101 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005102 I.swapOperands();
5103 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005104 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005105 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005106 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005107 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005108 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5109 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5110 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5111 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005112 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005113 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005114 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005115 std::swap(A, B);
5116 }
Chris Lattner318bf792007-03-18 22:51:34 +00005117 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005118 I.swapOperands(); // Simplified below.
5119 std::swap(Op0, Op1);
5120 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005121 }
Chris Lattner318bf792007-03-18 22:51:34 +00005122 }
5123
5124 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5125 if (Op0I) {
5126 Value *A, *B;
5127 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5128 if (A == Op1) // (B|A)^B == (A|B)^B
5129 std::swap(A, B);
5130 if (B == Op1) { // (A|B)^B == A & ~B
5131 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005132 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5133 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005134 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005135 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5136 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5137 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5138 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005139 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5140 if (A == Op1) // (A&B)^A -> (B&A)^A
5141 std::swap(A, B);
5142 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005143 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005144 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005145 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5146 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005147 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005148 }
Chris Lattner318bf792007-03-18 22:51:34 +00005149 }
5150
5151 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5152 if (Op0I && Op1I && Op0I->isShift() &&
5153 Op0I->getOpcode() == Op1I->getOpcode() &&
5154 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5155 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5156 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005157 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005158 Op1I->getOperand(0),
5159 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005160 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005161 Op1I->getOperand(1));
5162 }
5163
5164 if (Op0I && Op1I) {
5165 Value *A, *B, *C, *D;
5166 // (A & B)^(A | B) -> A ^ B
5167 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5168 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5169 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005170 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005171 }
5172 // (A | B)^(A & B) -> A ^ B
5173 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5174 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5175 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005176 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005177 }
5178
5179 // (A & B)^(C & D)
5180 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5181 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5182 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5183 // (X & Y)^(X & Y) -> (Y^Z) & X
5184 Value *X = 0, *Y = 0, *Z = 0;
5185 if (A == C)
5186 X = A, Y = B, Z = D;
5187 else if (A == D)
5188 X = A, Y = B, Z = C;
5189 else if (B == C)
5190 X = B, Y = A, Z = D;
5191 else if (B == D)
5192 X = B, Y = A, Z = C;
5193
5194 if (X) {
5195 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005196 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5197 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005198 }
5199 }
5200 }
5201
Reid Spencere4d87aa2006-12-23 06:05:41 +00005202 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5203 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5204 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005205 return R;
5206
Chris Lattner6fc205f2006-05-05 06:39:07 +00005207 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005208 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005209 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005210 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5211 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005212 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005213 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005214 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5215 I.getType(), TD) &&
5216 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5217 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005218 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005219 Op1C->getOperand(0),
5220 I.getName());
5221 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005222 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005223 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005224 }
Chris Lattner99c65742007-10-24 05:38:08 +00005225 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005226
Chris Lattner7e708292002-06-25 16:13:24 +00005227 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005228}
5229
Dan Gohman6de29f82009-06-15 22:12:54 +00005230static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
5231 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5232}
Chris Lattnera96879a2004-09-29 17:40:11 +00005233
Dan Gohman6de29f82009-06-15 22:12:54 +00005234static bool HasAddOverflow(ConstantInt *Result,
5235 ConstantInt *In1, ConstantInt *In2,
5236 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005237 if (IsSigned)
5238 if (In2->getValue().isNegative())
5239 return Result->getValue().sgt(In1->getValue());
5240 else
5241 return Result->getValue().slt(In1->getValue());
5242 else
5243 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005244}
5245
Dan Gohman6de29f82009-06-15 22:12:54 +00005246/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005247/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005248static bool AddWithOverflow(Constant *&Result, Constant *In1,
5249 Constant *In2, bool IsSigned = false) {
5250 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005251
Dan Gohman6de29f82009-06-15 22:12:54 +00005252 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5253 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5254 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5255 if (HasAddOverflow(ExtractElement(Result, Idx),
5256 ExtractElement(In1, Idx),
5257 ExtractElement(In2, Idx),
5258 IsSigned))
5259 return true;
5260 }
5261 return false;
5262 }
5263
5264 return HasAddOverflow(cast<ConstantInt>(Result),
5265 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5266 IsSigned);
5267}
5268
5269static bool HasSubOverflow(ConstantInt *Result,
5270 ConstantInt *In1, ConstantInt *In2,
5271 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005272 if (IsSigned)
5273 if (In2->getValue().isNegative())
5274 return Result->getValue().slt(In1->getValue());
5275 else
5276 return Result->getValue().sgt(In1->getValue());
5277 else
5278 return Result->getValue().ugt(In1->getValue());
5279}
5280
Dan Gohman6de29f82009-06-15 22:12:54 +00005281/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5282/// overflowed for this type.
5283static bool SubWithOverflow(Constant *&Result, Constant *In1,
5284 Constant *In2, bool IsSigned = false) {
5285 Result = ConstantExpr::getSub(In1, In2);
5286
5287 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5288 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5289 Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5290 if (HasSubOverflow(ExtractElement(Result, Idx),
5291 ExtractElement(In1, Idx),
5292 ExtractElement(In2, Idx),
5293 IsSigned))
5294 return true;
5295 }
5296 return false;
5297 }
5298
5299 return HasSubOverflow(cast<ConstantInt>(Result),
5300 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5301 IsSigned);
5302}
5303
Chris Lattner574da9b2005-01-13 20:14:25 +00005304/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5305/// code necessary to compute the offset from the base pointer (without adding
5306/// in the base pointer). Return the result as a signed integer of intptr size.
5307static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5308 TargetData &TD = IC.getTargetData();
5309 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005310 const Type *IntPtrTy = TD.getIntPtrType();
5311 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005312
5313 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005314 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005315 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005316
Gabor Greif177dd3f2008-06-12 21:37:33 +00005317 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5318 ++i, ++GTI) {
5319 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005320 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005321 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5322 if (OpC->isZero()) continue;
5323
5324 // Handle a struct index, which adds its field offset to the pointer.
5325 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5326 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5327
5328 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5329 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005330 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005331 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005332 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005333 ConstantInt::get(IntPtrTy, Size),
5334 GEP->getName()+".offs"), I);
5335 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005336 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005337
5338 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5339 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5340 Scale = ConstantExpr::getMul(OC, Scale);
5341 if (Constant *RC = dyn_cast<Constant>(Result))
5342 Result = ConstantExpr::getAdd(RC, Scale);
5343 else {
5344 // Emit an add instruction.
5345 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005346 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005347 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005348 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005349 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005350 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005351 // Convert to correct type.
5352 if (Op->getType() != IntPtrTy) {
5353 if (Constant *OpC = dyn_cast<Constant>(Op))
Chris Lattner62ce3b32009-04-07 05:03:34 +00005354 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
Chris Lattnere62f0212007-04-28 04:52:43 +00005355 else
Chris Lattner62ce3b32009-04-07 05:03:34 +00005356 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5357 true,
5358 Op->getName()+".c"), I);
Chris Lattnere62f0212007-04-28 04:52:43 +00005359 }
5360 if (Size != 1) {
5361 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5362 if (Constant *OpC = dyn_cast<Constant>(Op))
5363 Op = ConstantExpr::getMul(OpC, Scale);
5364 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005365 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005366 GEP->getName()+".idx"), I);
5367 }
5368
5369 // Emit an add instruction.
5370 if (isa<Constant>(Op) && isa<Constant>(Result))
5371 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5372 cast<Constant>(Result));
5373 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005374 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005375 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005376 }
5377 return Result;
5378}
5379
Chris Lattner10c0d912008-04-22 02:53:33 +00005380
5381/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5382/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5383/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5384/// complex, and scales are involved. The above expression would also be legal
5385/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5386/// later form is less amenable to optimization though, and we are allowed to
5387/// generate the first by knowing that pointer arithmetic doesn't overflow.
5388///
5389/// If we can't emit an optimized form for this expression, this returns null.
5390///
5391static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5392 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005393 TargetData &TD = IC.getTargetData();
5394 gep_type_iterator GTI = gep_type_begin(GEP);
5395
5396 // Check to see if this gep only has a single variable index. If so, and if
5397 // any constant indices are a multiple of its scale, then we can compute this
5398 // in terms of the scale of the variable index. For example, if the GEP
5399 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5400 // because the expression will cross zero at the same point.
5401 unsigned i, e = GEP->getNumOperands();
5402 int64_t Offset = 0;
5403 for (i = 1; i != e; ++i, ++GTI) {
5404 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5405 // Compute the aggregate offset of constant indices.
5406 if (CI->isZero()) continue;
5407
5408 // Handle a struct index, which adds its field offset to the pointer.
5409 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5410 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5411 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005412 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005413 Offset += Size*CI->getSExtValue();
5414 }
5415 } else {
5416 // Found our variable index.
5417 break;
5418 }
5419 }
5420
5421 // If there are no variable indices, we must have a constant offset, just
5422 // evaluate it the general way.
5423 if (i == e) return 0;
5424
5425 Value *VariableIdx = GEP->getOperand(i);
5426 // Determine the scale factor of the variable element. For example, this is
5427 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005428 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005429
5430 // Verify that there are no other variable indices. If so, emit the hard way.
5431 for (++i, ++GTI; i != e; ++i, ++GTI) {
5432 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5433 if (!CI) return 0;
5434
5435 // Compute the aggregate offset of constant indices.
5436 if (CI->isZero()) continue;
5437
5438 // Handle a struct index, which adds its field offset to the pointer.
5439 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5440 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5441 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005442 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005443 Offset += Size*CI->getSExtValue();
5444 }
5445 }
5446
5447 // Okay, we know we have a single variable index, which must be a
5448 // pointer/array/vector index. If there is no offset, life is simple, return
5449 // the index.
5450 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5451 if (Offset == 0) {
5452 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5453 // we don't need to bother extending: the extension won't affect where the
5454 // computation crosses zero.
5455 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5456 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5457 VariableIdx->getNameStart(), &I);
5458 return VariableIdx;
5459 }
5460
5461 // Otherwise, there is an index. The computation we will do will be modulo
5462 // the pointer size, so get it.
5463 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5464
5465 Offset &= PtrSizeMask;
5466 VariableScale &= PtrSizeMask;
5467
5468 // To do this transformation, any constant index must be a multiple of the
5469 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5470 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5471 // multiple of the variable scale.
5472 int64_t NewOffs = Offset / (int64_t)VariableScale;
5473 if (Offset != NewOffs*(int64_t)VariableScale)
5474 return 0;
5475
5476 // Okay, we can do this evaluation. Start by converting the index to intptr.
5477 const Type *IntPtrTy = TD.getIntPtrType();
5478 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005479 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005480 true /*SExt*/,
5481 VariableIdx->getNameStart(), &I);
5482 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005483 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005484}
5485
5486
Reid Spencere4d87aa2006-12-23 06:05:41 +00005487/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005488/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005489Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5490 ICmpInst::Predicate Cond,
5491 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005492 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005493
Chris Lattner10c0d912008-04-22 02:53:33 +00005494 // Look through bitcasts.
5495 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5496 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005497
Chris Lattner574da9b2005-01-13 20:14:25 +00005498 Value *PtrBase = GEPLHS->getOperand(0);
5499 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005500 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005501 // This transformation (ignoring the base and scales) is valid because we
5502 // know pointers can't overflow. See if we can output an optimized form.
5503 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5504
5505 // If not, synthesize the offset the hard way.
5506 if (Offset == 0)
5507 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005508 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5509 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005510 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005511 // If the base pointers are different, but the indices are the same, just
5512 // compare the base pointer.
5513 if (PtrBase != GEPRHS->getOperand(0)) {
5514 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005515 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005516 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005517 if (IndicesTheSame)
5518 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5519 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5520 IndicesTheSame = false;
5521 break;
5522 }
5523
5524 // If all indices are the same, just compare the base pointers.
5525 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005526 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5527 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005528
5529 // Otherwise, the base pointers are different and the indices are
5530 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005531 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005532 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005533
Chris Lattnere9d782b2005-01-13 22:25:21 +00005534 // If one of the GEPs has all zero indices, recurse.
5535 bool AllZeros = true;
5536 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5537 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5538 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5539 AllZeros = false;
5540 break;
5541 }
5542 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005543 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5544 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005545
5546 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005547 AllZeros = true;
5548 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5549 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5550 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5551 AllZeros = false;
5552 break;
5553 }
5554 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005555 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005556
Chris Lattner4401c9c2005-01-14 00:20:05 +00005557 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5558 // If the GEPs only differ by one index, compare it.
5559 unsigned NumDifferences = 0; // Keep track of # differences.
5560 unsigned DiffOperand = 0; // The operand that differs.
5561 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5562 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005563 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5564 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005565 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005566 NumDifferences = 2;
5567 break;
5568 } else {
5569 if (NumDifferences++) break;
5570 DiffOperand = i;
5571 }
5572 }
5573
5574 if (NumDifferences == 0) // SAME GEP?
5575 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005576 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005577 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005578
Chris Lattner4401c9c2005-01-14 00:20:05 +00005579 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005580 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5581 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005582 // Make sure we do a signed comparison here.
5583 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005584 }
5585 }
5586
Reid Spencere4d87aa2006-12-23 06:05:41 +00005587 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005588 // the result to fold to a constant!
5589 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5590 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5591 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5592 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5593 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005594 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005595 }
5596 }
5597 return 0;
5598}
5599
Chris Lattnera5406232008-05-19 20:18:56 +00005600/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5601///
5602Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5603 Instruction *LHSI,
5604 Constant *RHSC) {
5605 if (!isa<ConstantFP>(RHSC)) return 0;
5606 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5607
5608 // Get the width of the mantissa. We don't want to hack on conversions that
5609 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005610 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005611 if (MantissaWidth == -1) return 0; // Unknown.
5612
5613 // Check to see that the input is converted from an integer type that is small
5614 // enough that preserves all bits. TODO: check here for "known" sign bits.
5615 // 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 +00005616 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005617
5618 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005619 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5620 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005621 ++InputSize;
5622
5623 // If the conversion would lose info, don't hack on this.
5624 if ((int)InputSize > MantissaWidth)
5625 return 0;
5626
5627 // Otherwise, we can potentially simplify the comparison. We know that it
5628 // will always come through as an integer value and we know the constant is
5629 // not a NAN (it would have been previously simplified).
5630 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5631
5632 ICmpInst::Predicate Pred;
5633 switch (I.getPredicate()) {
5634 default: assert(0 && "Unexpected predicate!");
5635 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005636 case FCmpInst::FCMP_OEQ:
5637 Pred = ICmpInst::ICMP_EQ;
5638 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005639 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005640 case FCmpInst::FCMP_OGT:
5641 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5642 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005643 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005644 case FCmpInst::FCMP_OGE:
5645 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5646 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005647 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005648 case FCmpInst::FCMP_OLT:
5649 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5650 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005651 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005652 case FCmpInst::FCMP_OLE:
5653 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5654 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005655 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005656 case FCmpInst::FCMP_ONE:
5657 Pred = ICmpInst::ICMP_NE;
5658 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005659 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005660 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005661 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005662 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005663 }
5664
5665 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5666
5667 // Now we know that the APFloat is a normal number, zero or inf.
5668
Chris Lattner85162782008-05-20 03:50:52 +00005669 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005670 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005671 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005672
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005673 if (!LHSUnsigned) {
5674 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5675 // and large values.
5676 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5677 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5678 APFloat::rmNearestTiesToEven);
5679 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5680 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5681 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005682 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5683 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005684 }
5685 } else {
5686 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5687 // +INF and large values.
5688 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5689 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5690 APFloat::rmNearestTiesToEven);
5691 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5692 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5693 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005694 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005696 }
Chris Lattnera5406232008-05-19 20:18:56 +00005697 }
5698
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005699 if (!LHSUnsigned) {
5700 // See if the RHS value is < SignedMin.
5701 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5702 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5703 APFloat::rmNearestTiesToEven);
5704 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5705 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5706 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005707 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005709 }
Chris Lattnera5406232008-05-19 20:18:56 +00005710 }
5711
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005712 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5713 // [0, UMAX], but it may still be fractional. See if it is fractional by
5714 // casting the FP value to the integer value and back, checking for equality.
5715 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005716 Constant *RHSInt = LHSUnsigned
5717 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5718 : ConstantExpr::getFPToSI(RHSC, IntTy);
5719 if (!RHS.isZero()) {
5720 bool Equal = LHSUnsigned
5721 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5722 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5723 if (!Equal) {
5724 // If we had a comparison against a fractional value, we have to adjust
5725 // the compare predicate and sometimes the value. RHSC is rounded towards
5726 // zero at this point.
5727 switch (Pred) {
5728 default: assert(0 && "Unexpected integer comparison!");
5729 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005730 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005731 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5732 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5733 case ICmpInst::ICMP_ULE:
5734 // (float)int <= 4.4 --> int <= 4
5735 // (float)int <= -4.4 --> false
5736 if (RHS.isNegative())
5737 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5738 break;
5739 case ICmpInst::ICMP_SLE:
5740 // (float)int <= 4.4 --> int <= 4
5741 // (float)int <= -4.4 --> int < -4
5742 if (RHS.isNegative())
5743 Pred = ICmpInst::ICMP_SLT;
5744 break;
5745 case ICmpInst::ICMP_ULT:
5746 // (float)int < -4.4 --> false
5747 // (float)int < 4.4 --> int <= 4
5748 if (RHS.isNegative())
5749 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5750 Pred = ICmpInst::ICMP_ULE;
5751 break;
5752 case ICmpInst::ICMP_SLT:
5753 // (float)int < -4.4 --> int < -4
5754 // (float)int < 4.4 --> int <= 4
5755 if (!RHS.isNegative())
5756 Pred = ICmpInst::ICMP_SLE;
5757 break;
5758 case ICmpInst::ICMP_UGT:
5759 // (float)int > 4.4 --> int > 4
5760 // (float)int > -4.4 --> true
5761 if (RHS.isNegative())
5762 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5763 break;
5764 case ICmpInst::ICMP_SGT:
5765 // (float)int > 4.4 --> int > 4
5766 // (float)int > -4.4 --> int >= -4
5767 if (RHS.isNegative())
5768 Pred = ICmpInst::ICMP_SGE;
5769 break;
5770 case ICmpInst::ICMP_UGE:
5771 // (float)int >= -4.4 --> true
5772 // (float)int >= 4.4 --> int > 4
5773 if (!RHS.isNegative())
5774 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5775 Pred = ICmpInst::ICMP_UGT;
5776 break;
5777 case ICmpInst::ICMP_SGE:
5778 // (float)int >= -4.4 --> int >= -4
5779 // (float)int >= 4.4 --> int > 4
5780 if (!RHS.isNegative())
5781 Pred = ICmpInst::ICMP_SGT;
5782 break;
5783 }
Chris Lattnera5406232008-05-19 20:18:56 +00005784 }
5785 }
5786
5787 // Lower this FP comparison into an appropriate integer version of the
5788 // comparison.
5789 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5790}
5791
Reid Spencere4d87aa2006-12-23 06:05:41 +00005792Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5793 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005794 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005795
Chris Lattner58e97462007-01-14 19:42:17 +00005796 // Fold trivial predicates.
5797 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005798 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005799 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005800 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005801
5802 // Simplify 'fcmp pred X, X'
5803 if (Op0 == Op1) {
5804 switch (I.getPredicate()) {
5805 default: assert(0 && "Unknown predicate!");
5806 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5807 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5808 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005809 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005810 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5811 case FCmpInst::FCMP_OLT: // True if ordered and less than
5812 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005813 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005814
5815 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5816 case FCmpInst::FCMP_ULT: // True if unordered or less than
5817 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5818 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5819 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5820 I.setPredicate(FCmpInst::FCMP_UNO);
5821 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5822 return &I;
5823
5824 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5825 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5826 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5827 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5828 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5829 I.setPredicate(FCmpInst::FCMP_ORD);
5830 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5831 return &I;
5832 }
5833 }
5834
Reid Spencere4d87aa2006-12-23 06:05:41 +00005835 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005836 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005837
Reid Spencere4d87aa2006-12-23 06:05:41 +00005838 // Handle fcmp with constant RHS
5839 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005840 // If the constant is a nan, see if we can fold the comparison based on it.
5841 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5842 if (CFP->getValueAPF().isNaN()) {
5843 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005844 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005845 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5846 "Comparison must be either ordered or unordered!");
5847 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005848 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005849 }
5850 }
5851
Reid Spencere4d87aa2006-12-23 06:05:41 +00005852 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5853 switch (LHSI->getOpcode()) {
5854 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005855 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5856 // block. If in the same block, we're encouraging jump threading. If
5857 // not, we are just pessimizing the code by making an i1 phi.
5858 if (LHSI->getParent() == I.getParent())
5859 if (Instruction *NV = FoldOpIntoPhi(I))
5860 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005861 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005862 case Instruction::SIToFP:
5863 case Instruction::UIToFP:
5864 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5865 return NV;
5866 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005867 case Instruction::Select:
5868 // If either operand of the select is a constant, we can fold the
5869 // comparison into the select arms, which will cause one to be
5870 // constant folded and the select turned into a bitwise or.
5871 Value *Op1 = 0, *Op2 = 0;
5872 if (LHSI->hasOneUse()) {
5873 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5874 // Fold the known value into the constant operand.
5875 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5876 // Insert a new FCmp of the other select operand.
5877 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5878 LHSI->getOperand(2), RHSC,
5879 I.getName()), I);
5880 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5881 // Fold the known value into the constant operand.
5882 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5883 // Insert a new FCmp of the other select operand.
5884 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5885 LHSI->getOperand(1), RHSC,
5886 I.getName()), I);
5887 }
5888 }
5889
5890 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005891 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 break;
5893 }
5894 }
5895
5896 return Changed ? &I : 0;
5897}
5898
5899Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5900 bool Changed = SimplifyCompare(I);
5901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5902 const Type *Ty = Op0->getType();
5903
5904 // icmp X, X
5905 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005906 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005907 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005908
5909 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005910 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005911
Reid Spencere4d87aa2006-12-23 06:05:41 +00005912 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005913 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005914 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5915 isa<ConstantPointerNull>(Op0)) &&
5916 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005917 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005918 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005919 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005920
Reid Spencere4d87aa2006-12-23 06:05:41 +00005921 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005922 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005923 switch (I.getPredicate()) {
5924 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005925 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005926 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005927 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005928 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005929 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005930 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005931 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005932
Reid Spencere4d87aa2006-12-23 06:05:41 +00005933 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005934 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005935 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005936 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005937 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005938 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005939 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005940 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005941 case ICmpInst::ICMP_SGT:
5942 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005943 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005944 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5945 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5946 InsertNewInstBefore(Not, I);
5947 return BinaryOperator::CreateAnd(Not, Op0);
5948 }
5949 case ICmpInst::ICMP_UGE:
5950 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5951 // FALL THROUGH
5952 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005953 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005954 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005955 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005956 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005957 case ICmpInst::ICMP_SGE:
5958 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5959 // FALL THROUGH
5960 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5961 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5962 InsertNewInstBefore(Not, I);
5963 return BinaryOperator::CreateOr(Not, Op0);
5964 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005965 }
Chris Lattner8b170942002-08-09 23:47:40 +00005966 }
5967
Dan Gohman1c8491e2009-04-25 17:12:48 +00005968 unsigned BitWidth = 0;
5969 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005970 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5971 else if (Ty->isIntOrIntVector())
5972 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005973
5974 bool isSignBit = false;
5975
Dan Gohman81b28ce2008-09-16 18:46:06 +00005976 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005977 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005978 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005979
Chris Lattnerb6566012008-01-05 01:18:20 +00005980 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5981 if (I.isEquality() && CI->isNullValue() &&
5982 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5983 // (icmp cond A B) if cond is equality
5984 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005985 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005986
Dan Gohman81b28ce2008-09-16 18:46:06 +00005987 // If we have an icmp le or icmp ge instruction, turn it into the
5988 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5989 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005990 switch (I.getPredicate()) {
5991 default: break;
5992 case ICmpInst::ICMP_ULE:
5993 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5994 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5995 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5996 case ICmpInst::ICMP_SLE:
5997 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5998 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5999 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
6000 case ICmpInst::ICMP_UGE:
6001 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6002 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6003 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
6004 case ICmpInst::ICMP_SGE:
6005 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6006 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6007 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
6008 }
6009
Chris Lattner183661e2008-07-11 05:40:05 +00006010 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006011 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006012 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006013 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6014 }
6015
6016 // See if we can fold the comparison based on range information we can get
6017 // by checking whether bits are known to be zero or one in the input.
6018 if (BitWidth != 0) {
6019 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6020 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6021
6022 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006023 isSignBit ? APInt::getSignBit(BitWidth)
6024 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006025 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006026 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006027 if (SimplifyDemandedBits(I.getOperandUse(1),
6028 APInt::getAllOnesValue(BitWidth),
6029 Op1KnownZero, Op1KnownOne, 0))
6030 return &I;
6031
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006032 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006033 // in. Compute the Min, Max and RHS values based on the known bits. For the
6034 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006035 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6036 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6037 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6038 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6039 Op0Min, Op0Max);
6040 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6041 Op1Min, Op1Max);
6042 } else {
6043 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6044 Op0Min, Op0Max);
6045 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6046 Op1Min, Op1Max);
6047 }
6048
Chris Lattner183661e2008-07-11 05:40:05 +00006049 // If Min and Max are known to be the same, then SimplifyDemandedBits
6050 // figured out that the LHS is a constant. Just constant fold this now so
6051 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006052 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6053 return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6054 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6055 return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6056
Chris Lattner183661e2008-07-11 05:40:05 +00006057 // Based on the range information we know about the LHS, see if we can
6058 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006059 switch (I.getPredicate()) {
Chris Lattner84dff672008-07-11 05:08:55 +00006060 default: assert(0 && "Unknown icmp opcode!");
6061 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006062 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00006063 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6064 break;
6065 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006066 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Chris Lattner84dff672008-07-11 05:08:55 +00006067 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6068 break;
6069 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006070 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006071 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006072 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006075 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6077 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6078 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6079
6080 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6081 if (CI->isMinValue(true))
6082 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Chris Lattner183661e2008-07-11 05:40:05 +00006083 ConstantInt::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084 }
Chris Lattner84dff672008-07-11 05:08:55 +00006085 break;
6086 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006087 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006088 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006089 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006090 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006091
6092 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006093 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6095 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6096 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6097
6098 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6099 if (CI->isMaxValue(true))
6100 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6101 ConstantInt::getNullValue(Op0->getType()));
6102 }
Chris Lattner84dff672008-07-11 05:08:55 +00006103 break;
6104 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Chris Lattner84dff672008-07-11 05:08:55 +00006106 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006107 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Chris Lattner84dff672008-07-11 05:08:55 +00006108 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006109 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006110 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6112 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6113 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6114 }
Chris Lattner84dff672008-07-11 05:08:55 +00006115 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 case ICmpInst::ICMP_SGT:
6117 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006118 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Chris Lattner84dff672008-07-11 05:08:55 +00006120 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohman1c8491e2009-04-25 17:12:48 +00006121
6122 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Chris Lattner183661e2008-07-11 05:40:05 +00006123 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006124 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6125 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6126 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6127 }
6128 break;
6129 case ICmpInst::ICMP_SGE:
6130 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6131 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6132 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6133 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6134 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6135 break;
6136 case ICmpInst::ICMP_SLE:
6137 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6138 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6139 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6140 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6141 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6142 break;
6143 case ICmpInst::ICMP_UGE:
6144 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6145 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6146 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6147 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6148 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6149 break;
6150 case ICmpInst::ICMP_ULE:
6151 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6152 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6153 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6154 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6155 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner84dff672008-07-11 05:08:55 +00006156 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006157 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158
6159 // Turn a signed comparison into an unsigned one if both operands
6160 // are known to have the same sign.
6161 if (I.isSignedPredicate() &&
6162 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6163 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6164 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006165 }
6166
6167 // Test if the ICmpInst instruction is used exclusively by a select as
6168 // part of a minimum or maximum operation. If so, refrain from doing
6169 // any other folding. This helps out other analyses which understand
6170 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6171 // and CodeGen. And in this case, at least one of the comparison
6172 // operands has at least one user besides the compare (the select),
6173 // which would often largely negate the benefit of folding anyway.
6174 if (I.hasOneUse())
6175 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6176 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6177 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6178 return 0;
6179
6180 // See if we are doing a comparison between a constant and an instruction that
6181 // can be folded into the comparison.
6182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006183 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006184 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006185 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006186 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006187 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6188 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006189 }
6190
Chris Lattner01deb9d2007-04-03 17:43:25 +00006191 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006192 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6193 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6194 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006195 case Instruction::GetElementPtr:
6196 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006197 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006198 bool isAllZeros = true;
6199 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6200 if (!isa<Constant>(LHSI->getOperand(i)) ||
6201 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6202 isAllZeros = false;
6203 break;
6204 }
6205 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006206 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006207 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6208 }
6209 break;
6210
Chris Lattner6970b662005-04-23 15:31:55 +00006211 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006212 // Only fold icmp into the PHI if the phi and fcmp are in the same
6213 // block. If in the same block, we're encouraging jump threading. If
6214 // not, we are just pessimizing the code by making an i1 phi.
6215 if (LHSI->getParent() == I.getParent())
6216 if (Instruction *NV = FoldOpIntoPhi(I))
6217 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006218 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006219 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006220 // If either operand of the select is a constant, we can fold the
6221 // comparison into the select arms, which will cause one to be
6222 // constant folded and the select turned into a bitwise or.
6223 Value *Op1 = 0, *Op2 = 0;
6224 if (LHSI->hasOneUse()) {
6225 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6226 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006227 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6228 // Insert a new ICmp of the other select operand.
6229 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6230 LHSI->getOperand(2), RHSC,
6231 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006232 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6233 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006234 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6235 // Insert a new ICmp of the other select operand.
6236 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6237 LHSI->getOperand(1), RHSC,
6238 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006239 }
6240 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006241
Chris Lattner6970b662005-04-23 15:31:55 +00006242 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006243 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006244 break;
6245 }
Chris Lattner4802d902007-04-06 18:57:34 +00006246 case Instruction::Malloc:
6247 // If we have (malloc != null), and if the malloc has a single use, we
6248 // can assume it is successful and remove the malloc.
6249 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6250 AddToWorkList(LHSI);
6251 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006252 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006253 }
6254 break;
6255 }
Chris Lattner6970b662005-04-23 15:31:55 +00006256 }
6257
Reid Spencere4d87aa2006-12-23 06:05:41 +00006258 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006259 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006260 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006261 return NI;
6262 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006263 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6264 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006265 return NI;
6266
Reid Spencere4d87aa2006-12-23 06:05:41 +00006267 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006268 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6269 // now.
6270 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6271 if (isa<PointerType>(Op0->getType()) &&
6272 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006273 // We keep moving the cast from the left operand over to the right
6274 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006275 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006276
Chris Lattner57d86372007-01-06 01:45:59 +00006277 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6278 // so eliminate it as well.
6279 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6280 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006281
Chris Lattnerde90b762003-11-03 04:25:02 +00006282 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006283 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006284 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006285 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006286 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006287 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006288 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006289 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006290 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006291 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006292 }
Chris Lattner57d86372007-01-06 01:45:59 +00006293 }
6294
6295 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006296 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006297 // This comes up when you have code like
6298 // int X = A < B;
6299 // if (X) ...
6300 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006301 // with a constant or another cast from the same type.
6302 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006303 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006304 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006305 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006306
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006307 // See if it's the same type of instruction on the left and right.
6308 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6309 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006310 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006311 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006312 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006313 default: break;
6314 case Instruction::Add:
6315 case Instruction::Sub:
6316 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006317 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006318 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6319 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006320 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6322 if (CI->getValue().isSignBit()) {
6323 ICmpInst::Predicate Pred = I.isSignedPredicate()
6324 ? I.getUnsignedPredicate()
6325 : I.getSignedPredicate();
6326 return new ICmpInst(Pred, Op0I->getOperand(0),
6327 Op1I->getOperand(0));
6328 }
6329
6330 if (CI->getValue().isMaxSignedValue()) {
6331 ICmpInst::Predicate Pred = I.isSignedPredicate()
6332 ? I.getUnsignedPredicate()
6333 : I.getSignedPredicate();
6334 Pred = I.getSwappedPredicate(Pred);
6335 return new ICmpInst(Pred, Op0I->getOperand(0),
6336 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006337 }
6338 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006339 break;
6340 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006341 if (!I.isEquality())
6342 break;
6343
Nick Lewycky5d52c452008-08-21 05:56:10 +00006344 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6345 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6346 // Mask = -1 >> count-trailing-zeros(Cst).
6347 if (!CI->isZero() && !CI->isOne()) {
6348 const APInt &AP = CI->getValue();
6349 ConstantInt *Mask = ConstantInt::get(
6350 APInt::getLowBitsSet(AP.getBitWidth(),
6351 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006352 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006353 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6354 Mask);
6355 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6356 Mask);
6357 InsertNewInstBefore(And1, I);
6358 InsertNewInstBefore(And2, I);
6359 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006360 }
6361 }
6362 break;
6363 }
6364 }
6365 }
6366 }
6367
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006368 // ~x < ~y --> y < x
6369 { Value *A, *B;
6370 if (match(Op0, m_Not(m_Value(A))) &&
6371 match(Op1, m_Not(m_Value(B))))
6372 return new ICmpInst(I.getPredicate(), B, A);
6373 }
6374
Chris Lattner65b72ba2006-09-18 04:22:48 +00006375 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006376 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006377
6378 // -x == -y --> x == y
6379 if (match(Op0, m_Neg(m_Value(A))) &&
6380 match(Op1, m_Neg(m_Value(B))))
6381 return new ICmpInst(I.getPredicate(), A, B);
6382
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006383 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6384 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6385 Value *OtherVal = A == Op1 ? B : A;
6386 return new ICmpInst(I.getPredicate(), OtherVal,
6387 Constant::getNullValue(A->getType()));
6388 }
6389
6390 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6391 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006392 ConstantInt *C1, *C2;
6393 if (match(B, m_ConstantInt(C1)) &&
6394 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6395 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6396 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6397 return new ICmpInst(I.getPredicate(), A,
6398 InsertNewInstBefore(Xor, I));
6399 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006400
6401 // A^B == A^D -> B == D
6402 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6403 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6404 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6405 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6406 }
6407 }
6408
6409 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6410 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006411 // A == (A^B) -> B == 0
6412 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006413 return new ICmpInst(I.getPredicate(), OtherVal,
6414 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006415 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006416
6417 // (A-B) == A -> B == 0
6418 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6419 return new ICmpInst(I.getPredicate(), B,
6420 Constant::getNullValue(B->getType()));
6421
6422 // A == (A-B) -> B == 0
6423 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006424 return new ICmpInst(I.getPredicate(), B,
6425 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006426
Chris Lattner9c2328e2006-11-14 06:06:06 +00006427 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6428 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6429 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6430 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6431 Value *X = 0, *Y = 0, *Z = 0;
6432
6433 if (A == C) {
6434 X = B; Y = D; Z = A;
6435 } else if (A == D) {
6436 X = B; Y = C; Z = A;
6437 } else if (B == C) {
6438 X = A; Y = D; Z = B;
6439 } else if (B == D) {
6440 X = A; Y = C; Z = B;
6441 }
6442
6443 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006444 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6445 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006446 I.setOperand(0, Op1);
6447 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6448 return &I;
6449 }
6450 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006451 }
Chris Lattner7e708292002-06-25 16:13:24 +00006452 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006453}
6454
Chris Lattner562ef782007-06-20 23:46:26 +00006455
6456/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6457/// and CmpRHS are both known to be integer constants.
6458Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6459 ConstantInt *DivRHS) {
6460 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6461 const APInt &CmpRHSV = CmpRHS->getValue();
6462
6463 // FIXME: If the operand types don't match the type of the divide
6464 // then don't attempt this transform. The code below doesn't have the
6465 // logic to deal with a signed divide and an unsigned compare (and
6466 // vice versa). This is because (x /s C1) <s C2 produces different
6467 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6468 // (x /u C1) <u C2. Simply casting the operands and result won't
6469 // work. :( The if statement below tests that condition and bails
6470 // if it finds it.
6471 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6472 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6473 return 0;
6474 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006475 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006476 if (DivIsSigned && DivRHS->isAllOnesValue())
6477 return 0; // The overflow computation also screws up here
6478 if (DivRHS->isOne())
6479 return 0; // Not worth bothering, and eliminates some funny cases
6480 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006481
6482 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6483 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6484 // C2 (CI). By solving for X we can turn this into a range check
6485 // instead of computing a divide.
Dan Gohman6de29f82009-06-15 22:12:54 +00006486 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006487
6488 // Determine if the product overflows by seeing if the product is
6489 // not equal to the divide. Make sure we do the same kind of divide
6490 // as in the LHS instruction that we're folding.
6491 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6492 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6493
6494 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006495 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006496
Chris Lattner1dbfd482007-06-21 18:11:19 +00006497 // Figure out the interval that is being checked. For example, a comparison
6498 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6499 // Compute this interval based on the constants involved and the signedness of
6500 // the compare/divide. This computes a half-open interval, keeping track of
6501 // whether either value in the interval overflows. After analysis each
6502 // overflow variable is set to 0 if it's corresponding bound variable is valid
6503 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6504 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006505 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006506
Chris Lattner562ef782007-06-20 23:46:26 +00006507 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006508 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006509 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006510 HiOverflow = LoOverflow = ProdOV;
6511 if (!HiOverflow)
6512 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006513 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006514 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006515 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006516 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6517 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006518 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006519 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6520 HiOverflow = LoOverflow = ProdOV;
6521 if (!HiOverflow)
6522 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006523 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006524 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006525 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006526 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6527 if (!LoOverflow) {
6528 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6529 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6530 true) ? -1 : 0;
6531 }
Chris Lattner562ef782007-06-20 23:46:26 +00006532 }
Dan Gohman76491272008-02-13 22:09:18 +00006533 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006534 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006535 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006536 LoBound = AddOne(DivRHS);
6537 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006538 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6539 HiOverflow = 1; // [INTMIN+1, overflow)
6540 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6541 }
Dan Gohman76491272008-02-13 22:09:18 +00006542 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006543 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006544 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006545 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006546 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006547 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006548 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006549 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6550 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006551 if (!HiOverflow)
6552 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006553 }
6554
Chris Lattner1dbfd482007-06-21 18:11:19 +00006555 // Dividing by a negative swaps the condition. LT <-> GT
6556 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006557 }
6558
6559 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006560 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006561 default: assert(0 && "Unhandled icmp opcode!");
6562 case ICmpInst::ICMP_EQ:
6563 if (LoOverflow && HiOverflow)
6564 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6565 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006566 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006567 ICmpInst::ICMP_UGE, X, LoBound);
6568 else if (LoOverflow)
6569 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6570 ICmpInst::ICMP_ULT, X, HiBound);
6571 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006572 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006573 case ICmpInst::ICMP_NE:
6574 if (LoOverflow && HiOverflow)
6575 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6576 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006577 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006578 ICmpInst::ICMP_ULT, X, LoBound);
6579 else if (LoOverflow)
6580 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6581 ICmpInst::ICMP_UGE, X, HiBound);
6582 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006583 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006584 case ICmpInst::ICMP_ULT:
6585 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006586 if (LoOverflow == +1) // Low bound is greater than input range.
6587 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6588 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006589 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006590 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006591 case ICmpInst::ICMP_UGT:
6592 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006593 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006594 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006595 else if (HiOverflow == -1) // High bound less than input range.
6596 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6597 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006598 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6599 else
6600 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6601 }
6602}
6603
6604
Chris Lattner01deb9d2007-04-03 17:43:25 +00006605/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6606///
6607Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6608 Instruction *LHSI,
6609 ConstantInt *RHS) {
6610 const APInt &RHSV = RHS->getValue();
6611
6612 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006613 case Instruction::Trunc:
6614 if (ICI.isEquality() && LHSI->hasOneUse()) {
6615 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6616 // of the high bits truncated out of x are known.
6617 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6618 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6619 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6620 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6621 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6622
6623 // If all the high bits are known, we can do this xform.
6624 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6625 // Pull in the high bits from known-ones set.
6626 APInt NewRHS(RHS->getValue());
6627 NewRHS.zext(SrcBits);
6628 NewRHS |= KnownOne;
6629 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6630 ConstantInt::get(NewRHS));
6631 }
6632 }
6633 break;
6634
Duncan Sands0091bf22007-04-04 06:42:45 +00006635 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006636 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6637 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6638 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006639 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6640 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006641 Value *CompareVal = LHSI->getOperand(0);
6642
6643 // If the sign bit of the XorCST is not set, there is no change to
6644 // the operation, just stop using the Xor.
6645 if (!XorCST->getValue().isNegative()) {
6646 ICI.setOperand(0, CompareVal);
6647 AddToWorkList(LHSI);
6648 return &ICI;
6649 }
6650
6651 // Was the old condition true if the operand is positive?
6652 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6653
6654 // If so, the new one isn't.
6655 isTrueIfPositive ^= true;
6656
6657 if (isTrueIfPositive)
6658 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6659 else
6660 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6661 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006662
6663 if (LHSI->hasOneUse()) {
6664 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6665 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6666 const APInt &SignBit = XorCST->getValue();
6667 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6668 ? ICI.getUnsignedPredicate()
6669 : ICI.getSignedPredicate();
6670 return new ICmpInst(Pred, LHSI->getOperand(0),
6671 ConstantInt::get(RHSV ^ SignBit));
6672 }
6673
6674 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006675 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006676 const APInt &NotSignBit = XorCST->getValue();
6677 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6678 ? ICI.getUnsignedPredicate()
6679 : ICI.getSignedPredicate();
6680 Pred = ICI.getSwappedPredicate(Pred);
6681 return new ICmpInst(Pred, LHSI->getOperand(0),
6682 ConstantInt::get(RHSV ^ NotSignBit));
6683 }
6684 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006685 }
6686 break;
6687 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6688 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6689 LHSI->getOperand(0)->hasOneUse()) {
6690 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6691
6692 // If the LHS is an AND of a truncating cast, we can widen the
6693 // and/compare to be the input width without changing the value
6694 // produced, eliminating a cast.
6695 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6696 // We can do this transformation if either the AND constant does not
6697 // have its sign bit set or if it is an equality comparison.
6698 // Extending a relational comparison when we're checking the sign
6699 // bit would not work.
6700 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006701 (ICI.isEquality() ||
6702 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006703 uint32_t BitWidth =
6704 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6705 APInt NewCST = AndCST->getValue();
6706 NewCST.zext(BitWidth);
6707 APInt NewCI = RHSV;
6708 NewCI.zext(BitWidth);
6709 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006710 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006711 ConstantInt::get(NewCST),LHSI->getName());
6712 InsertNewInstBefore(NewAnd, ICI);
6713 return new ICmpInst(ICI.getPredicate(), NewAnd,
6714 ConstantInt::get(NewCI));
6715 }
6716 }
6717
6718 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6719 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6720 // happens a LOT in code produced by the C front-end, for bitfield
6721 // access.
6722 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6723 if (Shift && !Shift->isShift())
6724 Shift = 0;
6725
6726 ConstantInt *ShAmt;
6727 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6728 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6729 const Type *AndTy = AndCST->getType(); // Type of the and.
6730
6731 // We can fold this as long as we can't shift unknown bits
6732 // into the mask. This can only happen with signed shift
6733 // rights, as they sign-extend.
6734 if (ShAmt) {
6735 bool CanFold = Shift->isLogicalShift();
6736 if (!CanFold) {
6737 // To test for the bad case of the signed shr, see if any
6738 // of the bits shifted in could be tested after the mask.
6739 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6740 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6741
6742 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6743 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6744 AndCST->getValue()) == 0)
6745 CanFold = true;
6746 }
6747
6748 if (CanFold) {
6749 Constant *NewCst;
6750 if (Shift->getOpcode() == Instruction::Shl)
6751 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6752 else
6753 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6754
6755 // Check to see if we are shifting out any of the bits being
6756 // compared.
6757 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6758 // If we shifted bits out, the fold is not going to work out.
6759 // As a special case, check to see if this means that the
6760 // result is always true or false now.
6761 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6762 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6763 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6764 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6765 } else {
6766 ICI.setOperand(1, NewCst);
6767 Constant *NewAndCST;
6768 if (Shift->getOpcode() == Instruction::Shl)
6769 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6770 else
6771 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6772 LHSI->setOperand(1, NewAndCST);
6773 LHSI->setOperand(0, Shift->getOperand(0));
6774 AddToWorkList(Shift); // Shift is dead.
6775 AddUsesToWorkList(ICI);
6776 return &ICI;
6777 }
6778 }
6779 }
6780
6781 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6782 // preferable because it allows the C<<Y expression to be hoisted out
6783 // of a loop if Y is invariant and X is not.
6784 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006785 ICI.isEquality() && !Shift->isArithmeticShift() &&
6786 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006787 // Compute C << Y.
6788 Value *NS;
6789 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006790 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006791 Shift->getOperand(1), "tmp");
6792 } else {
6793 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006794 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006795 Shift->getOperand(1), "tmp");
6796 }
6797 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6798
6799 // Compute X & (C << Y).
6800 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006801 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006802 InsertNewInstBefore(NewAnd, ICI);
6803
6804 ICI.setOperand(0, NewAnd);
6805 return &ICI;
6806 }
6807 }
6808 break;
6809
Chris Lattnera0141b92007-07-15 20:42:37 +00006810 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6811 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6812 if (!ShAmt) break;
6813
6814 uint32_t TypeBits = RHSV.getBitWidth();
6815
6816 // Check that the shift amount is in range. If not, don't perform
6817 // undefined shifts. When the shift is visited it will be
6818 // simplified.
6819 if (ShAmt->uge(TypeBits))
6820 break;
6821
6822 if (ICI.isEquality()) {
6823 // If we are comparing against bits always shifted out, the
6824 // comparison cannot succeed.
6825 Constant *Comp =
6826 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6827 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6828 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6829 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6830 return ReplaceInstUsesWith(ICI, Cst);
6831 }
6832
6833 if (LHSI->hasOneUse()) {
6834 // Otherwise strength reduce the shift into an and.
6835 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6836 Constant *Mask =
6837 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006838
Chris Lattnera0141b92007-07-15 20:42:37 +00006839 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006840 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006841 Mask, LHSI->getName()+".mask");
6842 Value *And = InsertNewInstBefore(AndI, ICI);
6843 return new ICmpInst(ICI.getPredicate(), And,
6844 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006845 }
6846 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006847
6848 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6849 bool TrueIfSigned = false;
6850 if (LHSI->hasOneUse() &&
6851 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6852 // (X << 31) <s 0 --> (X&1) != 0
6853 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6854 (TypeBits-ShAmt->getZExtValue()-1));
6855 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006856 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006857 Mask, LHSI->getName()+".mask");
6858 Value *And = InsertNewInstBefore(AndI, ICI);
6859
6860 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6861 And, Constant::getNullValue(And->getType()));
6862 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006863 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006864 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006865
6866 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006867 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006868 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006869 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006870 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006871
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006872 // Check that the shift amount is in range. If not, don't perform
6873 // undefined shifts. When the shift is visited it will be
6874 // simplified.
6875 uint32_t TypeBits = RHSV.getBitWidth();
6876 if (ShAmt->uge(TypeBits))
6877 break;
6878
6879 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006880
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006881 // If we are comparing against bits always shifted out, the
6882 // comparison cannot succeed.
6883 APInt Comp = RHSV << ShAmtVal;
6884 if (LHSI->getOpcode() == Instruction::LShr)
6885 Comp = Comp.lshr(ShAmtVal);
6886 else
6887 Comp = Comp.ashr(ShAmtVal);
6888
6889 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6890 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6891 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6892 return ReplaceInstUsesWith(ICI, Cst);
6893 }
6894
6895 // Otherwise, check to see if the bits shifted out are known to be zero.
6896 // If so, we can compare against the unshifted value:
6897 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006898 if (LHSI->hasOneUse() &&
6899 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006900 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6901 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6902 ConstantExpr::getShl(RHS, ShAmt));
6903 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006904
Evan Chengf30752c2008-04-23 00:38:06 +00006905 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006906 // Otherwise strength reduce the shift into an and.
6907 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6908 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006909
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006910 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006911 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006912 Mask, LHSI->getName()+".mask");
6913 Value *And = InsertNewInstBefore(AndI, ICI);
6914 return new ICmpInst(ICI.getPredicate(), And,
6915 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006916 }
6917 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006918 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006919
6920 case Instruction::SDiv:
6921 case Instruction::UDiv:
6922 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6923 // Fold this div into the comparison, producing a range check.
6924 // Determine, based on the divide type, what the range is being
6925 // checked. If there is an overflow on the low or high side, remember
6926 // it, otherwise compute the range [low, hi) bounding the new value.
6927 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006928 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6929 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6930 DivRHS))
6931 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006932 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006933
6934 case Instruction::Add:
6935 // Fold: icmp pred (add, X, C1), C2
6936
6937 if (!ICI.isEquality()) {
6938 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6939 if (!LHSC) break;
6940 const APInt &LHSV = LHSC->getValue();
6941
6942 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6943 .subtract(LHSV);
6944
6945 if (ICI.isSignedPredicate()) {
6946 if (CR.getLower().isSignBit()) {
6947 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6948 ConstantInt::get(CR.getUpper()));
6949 } else if (CR.getUpper().isSignBit()) {
6950 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6951 ConstantInt::get(CR.getLower()));
6952 }
6953 } else {
6954 if (CR.getLower().isMinValue()) {
6955 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6956 ConstantInt::get(CR.getUpper()));
6957 } else if (CR.getUpper().isMinValue()) {
6958 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6959 ConstantInt::get(CR.getLower()));
6960 }
6961 }
6962 }
6963 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006964 }
6965
6966 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6967 if (ICI.isEquality()) {
6968 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6969
6970 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6971 // the second operand is a constant, simplify a bit.
6972 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6973 switch (BO->getOpcode()) {
6974 case Instruction::SRem:
6975 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6976 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6977 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6978 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6979 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006980 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006981 BO->getName());
6982 InsertNewInstBefore(NewRem, ICI);
6983 return new ICmpInst(ICI.getPredicate(), NewRem,
6984 Constant::getNullValue(BO->getType()));
6985 }
6986 }
6987 break;
6988 case Instruction::Add:
6989 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6990 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6991 if (BO->hasOneUse())
6992 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Dan Gohman6de29f82009-06-15 22:12:54 +00006993 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006994 } else if (RHSV == 0) {
6995 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6996 // efficiently invertible, or if the add has just this one use.
6997 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6998
6999 if (Value *NegVal = dyn_castNegVal(BOp1))
7000 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7001 else if (Value *NegVal = dyn_castNegVal(BOp0))
7002 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7003 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007004 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007005 InsertNewInstBefore(Neg, ICI);
7006 Neg->takeName(BO);
7007 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7008 }
7009 }
7010 break;
7011 case Instruction::Xor:
7012 // For the xor case, we can xor two constants together, eliminating
7013 // the explicit xor.
7014 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7015 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7016 ConstantExpr::getXor(RHS, BOC));
7017
7018 // FALLTHROUGH
7019 case Instruction::Sub:
7020 // Replace (([sub|xor] A, B) != 0) with (A != B)
7021 if (RHSV == 0)
7022 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7023 BO->getOperand(1));
7024 break;
7025
7026 case Instruction::Or:
7027 // If bits are being or'd in that are not present in the constant we
7028 // are comparing against, then the comparison could never succeed!
7029 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7030 Constant *NotCI = ConstantExpr::getNot(RHS);
7031 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7032 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7033 isICMP_NE));
7034 }
7035 break;
7036
7037 case Instruction::And:
7038 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7039 // If bits are being compared against that are and'd out, then the
7040 // comparison can never succeed!
7041 if ((RHSV & ~BOC->getValue()) != 0)
7042 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7043 isICMP_NE));
7044
7045 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7046 if (RHS == BOC && RHSV.isPowerOf2())
7047 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7048 ICmpInst::ICMP_NE, LHSI,
7049 Constant::getNullValue(RHS->getType()));
7050
7051 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007052 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007053 Value *X = BO->getOperand(0);
7054 Constant *Zero = Constant::getNullValue(X->getType());
7055 ICmpInst::Predicate pred = isICMP_NE ?
7056 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7057 return new ICmpInst(pred, X, Zero);
7058 }
7059
7060 // ((X & ~7) == 0) --> X < 8
7061 if (RHSV == 0 && isHighOnes(BOC)) {
7062 Value *X = BO->getOperand(0);
7063 Constant *NegX = ConstantExpr::getNeg(BOC);
7064 ICmpInst::Predicate pred = isICMP_NE ?
7065 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7066 return new ICmpInst(pred, X, NegX);
7067 }
7068 }
7069 default: break;
7070 }
7071 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7072 // Handle icmp {eq|ne} <intrinsic>, intcst.
7073 if (II->getIntrinsicID() == Intrinsic::bswap) {
7074 AddToWorkList(II);
7075 ICI.setOperand(0, II->getOperand(1));
7076 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7077 return &ICI;
7078 }
7079 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007080 }
7081 return 0;
7082}
7083
7084/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7085/// We only handle extending casts so far.
7086///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007087Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7088 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007089 Value *LHSCIOp = LHSCI->getOperand(0);
7090 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007091 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007092 Value *RHSCIOp;
7093
Chris Lattner8c756c12007-05-05 22:41:33 +00007094 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7095 // integer type is the same size as the pointer type.
7096 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7097 getTargetData().getPointerSizeInBits() ==
7098 cast<IntegerType>(DestTy)->getBitWidth()) {
7099 Value *RHSOp = 0;
7100 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00007101 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007102 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7103 RHSOp = RHSC->getOperand(0);
7104 // If the pointer types don't match, insert a bitcast.
7105 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007106 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007107 }
7108
7109 if (RHSOp)
7110 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7111 }
7112
7113 // The code below only handles extension cast instructions, so far.
7114 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007115 if (LHSCI->getOpcode() != Instruction::ZExt &&
7116 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007117 return 0;
7118
Reid Spencere4d87aa2006-12-23 06:05:41 +00007119 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7120 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007121
Reid Spencere4d87aa2006-12-23 06:05:41 +00007122 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007123 // Not an extension from the same type?
7124 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007125 if (RHSCIOp->getType() != LHSCIOp->getType())
7126 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007127
Nick Lewycky4189a532008-01-28 03:48:02 +00007128 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007129 // and the other is a zext), then we can't handle this.
7130 if (CI->getOpcode() != LHSCI->getOpcode())
7131 return 0;
7132
Nick Lewycky4189a532008-01-28 03:48:02 +00007133 // Deal with equality cases early.
7134 if (ICI.isEquality())
7135 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7136
7137 // A signed comparison of sign extended values simplifies into a
7138 // signed comparison.
7139 if (isSignedCmp && isSignedExt)
7140 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7141
7142 // The other three cases all fold into an unsigned comparison.
7143 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007144 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007145
Reid Spencere4d87aa2006-12-23 06:05:41 +00007146 // If we aren't dealing with a constant on the RHS, exit early
7147 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7148 if (!CI)
7149 return 0;
7150
7151 // Compute the constant that would happen if we truncated to SrcTy then
7152 // reextended to DestTy.
7153 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7154 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7155
7156 // If the re-extended constant didn't change...
7157 if (Res2 == CI) {
7158 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7159 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007160 // %A = sext i16 %X to i32
7161 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007162 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007163 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007164 // because %A may have negative value.
7165 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007166 // However, we allow this when the compare is EQ/NE, because they are
7167 // signless.
7168 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00007169 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007170 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007171 }
7172
7173 // The re-extended constant changed so the constant cannot be represented
7174 // in the shorter type. Consequently, we cannot emit a simple comparison.
7175
7176 // First, handle some easy cases. We know the result cannot be equal at this
7177 // point so handle the ICI.isEquality() cases
7178 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007179 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007180 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007181 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007182
7183 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7184 // should have been folded away previously and not enter in here.
7185 Value *Result;
7186 if (isSignedCmp) {
7187 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007188 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007189 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007190 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007191 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007192 } else {
7193 // We're performing an unsigned comparison.
7194 if (isSignedExt) {
7195 // We're performing an unsigned comp with a sign extended value.
7196 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007197 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007198 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7199 NegOne, ICI.getName()), ICI);
7200 } else {
7201 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007202 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007203 }
7204 }
7205
7206 // Finally, return the value computed.
7207 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007208 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007209 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007210
7211 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7212 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7213 "ICmp should be folded!");
7214 if (Constant *CI = dyn_cast<Constant>(Result))
7215 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7216 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007217}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007218
Reid Spencer832254e2007-02-02 02:16:23 +00007219Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7220 return commonShiftTransforms(I);
7221}
7222
7223Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7224 return commonShiftTransforms(I);
7225}
7226
7227Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007228 if (Instruction *R = commonShiftTransforms(I))
7229 return R;
7230
7231 Value *Op0 = I.getOperand(0);
7232
7233 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7234 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7235 if (CSI->isAllOnesValue())
7236 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007237
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007238 // See if we can turn a signed shr into an unsigned shr.
7239 if (MaskedValueIsZero(Op0,
7240 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7241 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7242
7243 // Arithmetic shifting an all-sign-bit value is a no-op.
7244 unsigned NumSignBits = ComputeNumSignBits(Op0);
7245 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7246 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007247
Chris Lattner348f6652007-12-06 01:59:46 +00007248 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007249}
7250
7251Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7252 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007254
7255 // shl X, 0 == X and shr X, 0 == X
7256 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007257 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007258 Op0 == Constant::getNullValue(Op0->getType()))
7259 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007260
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261 if (isa<UndefValue>(Op0)) {
7262 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007263 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007264 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007265 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7266 }
7267 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7269 return ReplaceInstUsesWith(I, Op0);
7270 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007271 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007272 }
7273
Dan Gohman9004c8a2009-05-21 02:28:33 +00007274 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007275 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007276 return &I;
7277
Chris Lattner2eefe512004-04-09 19:05:30 +00007278 // Try to fold constant and into select arguments.
7279 if (isa<Constant>(Op0))
7280 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007281 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007282 return R;
7283
Reid Spencerb83eb642006-10-20 07:07:24 +00007284 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007285 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7286 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007287 return 0;
7288}
7289
Reid Spencerb83eb642006-10-20 07:07:24 +00007290Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007291 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007292 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007293
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007294 // See if we can simplify any instructions used by the instruction whose sole
7295 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007296 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007297
Dan Gohmana119de82009-06-14 23:30:43 +00007298 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7299 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007300 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007301 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007302 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007303 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7304 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007305 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007306 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007307 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007308 }
7309
7310 // ((X*C1) << C2) == (X * (C1 << C2))
7311 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7312 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7313 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007314 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007315 ConstantExpr::getShl(BOOp, Op1));
7316
7317 // Try to fold constant and into select arguments.
7318 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7320 return R;
7321 if (isa<PHINode>(Op0))
7322 if (Instruction *NV = FoldOpIntoPhi(I))
7323 return NV;
7324
Chris Lattner8999dd32007-12-22 09:07:47 +00007325 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7326 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7327 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7328 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7329 // place. Don't try to do this transformation in this case. Also, we
7330 // require that the input operand is a shift-by-constant so that we have
7331 // confidence that the shifts will get folded together. We could do this
7332 // xform in more cases, but it is unlikely to be profitable.
7333 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7334 isa<ConstantInt>(TrOp->getOperand(1))) {
7335 // Okay, we'll do this xform. Make the shift of shift.
7336 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007337 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007338 I.getName());
7339 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7340
7341 // For logical shifts, the truncation has the effect of making the high
7342 // part of the register be zeros. Emulate this by inserting an AND to
7343 // clear the top bits as needed. This 'and' will usually be zapped by
7344 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007345 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7346 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007347 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7348
7349 // The mask we constructed says what the trunc would do if occurring
7350 // between the shifts. We want to know the effect *after* the second
7351 // shift. We know that it is a logical shift by a constant, so adjust the
7352 // mask as appropriate.
7353 if (I.getOpcode() == Instruction::Shl)
7354 MaskV <<= Op1->getZExtValue();
7355 else {
7356 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7357 MaskV = MaskV.lshr(Op1->getZExtValue());
7358 }
7359
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007360 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007361 TI->getName());
7362 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7363
7364 // Return the value truncated to the interesting size.
7365 return new TruncInst(And, I.getType());
7366 }
7367 }
7368
Chris Lattner4d5542c2006-01-06 07:12:35 +00007369 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007370 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7371 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7372 Value *V1, *V2;
7373 ConstantInt *CC;
7374 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007375 default: break;
7376 case Instruction::Add:
7377 case Instruction::And:
7378 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007379 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007380 // These operators commute.
7381 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007382 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007383 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007384 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007385 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007386 Op0BO->getName());
7387 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007388 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007389 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007390 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007391 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007392 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007393 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007394 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007395 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007396
Chris Lattner150f12a2005-09-18 06:30:59 +00007397 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007398 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007399 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007400 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007401 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7402 m_ConstantInt(CC))) &&
7403 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007404 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007405 Op0BO->getOperand(0), Op1,
7406 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007407 InsertNewInstBefore(YS, I); // (Y << C)
7408 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007409 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007410 V1->getName()+".mask");
7411 InsertNewInstBefore(XM, I); // X & (CC << C)
7412
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007413 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007414 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007415 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007416
Reid Spencera07cb7d2007-02-02 14:41:37 +00007417 // FALL THROUGH.
7418 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007419 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007420 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007421 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007422 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007423 Op0BO->getOperand(1), Op1,
7424 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007425 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007426 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007427 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007428 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007429 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007430 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007431 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007432 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007433 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007434
Chris Lattner13d4ab42006-05-31 21:14:00 +00007435 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007436 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7437 match(Op0BO->getOperand(0),
7438 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007439 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007440 cast<BinaryOperator>(Op0BO->getOperand(0))
7441 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007442 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007443 Op0BO->getOperand(1), Op1,
7444 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007445 InsertNewInstBefore(YS, I); // (Y << C)
7446 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007447 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007448 V1->getName()+".mask");
7449 InsertNewInstBefore(XM, I); // X & (CC << C)
7450
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007451 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007452 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007453
Chris Lattner11021cb2005-09-18 05:12:10 +00007454 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007455 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007456 }
7457
7458
7459 // If the operand is an bitwise operator with a constant RHS, and the
7460 // shift is the only use, we can pull it out of the shift.
7461 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7462 bool isValid = true; // Valid only for And, Or, Xor
7463 bool highBitSet = false; // Transform if high bit of constant set?
7464
7465 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007466 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007467 case Instruction::Add:
7468 isValid = isLeftShift;
7469 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007470 case Instruction::Or:
7471 case Instruction::Xor:
7472 highBitSet = false;
7473 break;
7474 case Instruction::And:
7475 highBitSet = true;
7476 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007477 }
7478
7479 // If this is a signed shift right, and the high bit is modified
7480 // by the logical operation, do not perform the transformation.
7481 // The highBitSet boolean indicates the value of the high bit of
7482 // the constant which would cause it to be modified for this
7483 // operation.
7484 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007485 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007486 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007487
7488 if (isValid) {
7489 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7490
7491 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007492 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007493 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007494 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007495
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007496 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007497 NewRHS);
7498 }
7499 }
7500 }
7501 }
7502
Chris Lattnerad0124c2006-01-06 07:52:12 +00007503 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007504 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7505 if (ShiftOp && !ShiftOp->isShift())
7506 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007507
Reid Spencerb83eb642006-10-20 07:07:24 +00007508 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007509 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007510 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7511 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007512 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7513 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7514 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007515
Zhou Sheng4351c642007-04-02 08:20:41 +00007516 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007517
7518 const IntegerType *Ty = cast<IntegerType>(I.getType());
7519
7520 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007521 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007522 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7523 // saturates.
7524 if (AmtSum >= TypeBits) {
7525 if (I.getOpcode() != Instruction::AShr)
7526 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7527 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7528 }
7529
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007530 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007531 ConstantInt::get(Ty, AmtSum));
7532 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7533 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007534 if (AmtSum >= TypeBits)
7535 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7536
Chris Lattnerb87056f2007-02-05 00:57:54 +00007537 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007538 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007539 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7540 I.getOpcode() == Instruction::LShr) {
7541 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007542 if (AmtSum >= TypeBits)
7543 AmtSum = TypeBits-1;
7544
Chris Lattnerb87056f2007-02-05 00:57:54 +00007545 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007546 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007547 InsertNewInstBefore(Shift, I);
7548
Zhou Shenge9e03f62007-03-28 15:02:20 +00007549 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007550 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007551 }
7552
Chris Lattnerb87056f2007-02-05 00:57:54 +00007553 // Okay, if we get here, one shift must be left, and the other shift must be
7554 // right. See if the amounts are equal.
7555 if (ShiftAmt1 == ShiftAmt2) {
7556 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7557 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007558 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007559 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007560 }
7561 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7562 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007563 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007564 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007565 }
7566 // We can simplify ((X << C) >>s C) into a trunc + sext.
7567 // NOTE: we could do this for any C, but that would make 'unusual' integer
7568 // types. For now, just stick to ones well-supported by the code
7569 // generators.
7570 const Type *SExtType = 0;
7571 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007572 case 1 :
7573 case 8 :
7574 case 16 :
7575 case 32 :
7576 case 64 :
7577 case 128:
7578 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7579 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007580 default: break;
7581 }
7582 if (SExtType) {
7583 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7584 InsertNewInstBefore(NewTrunc, I);
7585 return new SExtInst(NewTrunc, Ty);
7586 }
7587 // Otherwise, we can't handle it yet.
7588 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007589 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007590
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007591 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007592 if (I.getOpcode() == Instruction::Shl) {
7593 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7594 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007595 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007596 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007597 InsertNewInstBefore(Shift, I);
7598
Reid Spencer55702aa2007-03-25 21:11:44 +00007599 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007600 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007601 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007602
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007603 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007604 if (I.getOpcode() == Instruction::LShr) {
7605 assert(ShiftOp->getOpcode() == Instruction::Shl);
7606 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007607 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007608 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007609
Reid Spencerd5e30f02007-03-26 17:18:58 +00007610 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007611 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007612 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007613
7614 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7615 } else {
7616 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007617 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007619 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007620 if (I.getOpcode() == Instruction::Shl) {
7621 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7622 ShiftOp->getOpcode() == Instruction::AShr);
7623 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007624 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007625 ConstantInt::get(Ty, ShiftDiff));
7626 InsertNewInstBefore(Shift, I);
7627
Reid Spencer55702aa2007-03-25 21:11:44 +00007628 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007629 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007630 }
7631
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007632 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007633 if (I.getOpcode() == Instruction::LShr) {
7634 assert(ShiftOp->getOpcode() == Instruction::Shl);
7635 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007636 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007637 InsertNewInstBefore(Shift, I);
7638
Reid Spencer68d27cf2007-03-26 23:45:51 +00007639 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007640 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007641 }
7642
7643 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007644 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007645 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007646 return 0;
7647}
7648
Chris Lattnera1be5662002-05-02 17:06:02 +00007649
Chris Lattnercfd65102005-10-29 04:36:15 +00007650/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7651/// expression. If so, decompose it, returning some value X, such that Val is
7652/// X*Scale+Offset.
7653///
7654static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007655 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007656 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007657 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007658 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007659 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007660 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007661 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7662 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7663 if (I->getOpcode() == Instruction::Shl) {
7664 // This is a value scaled by '1 << the shift amt'.
7665 Scale = 1U << RHS->getZExtValue();
7666 Offset = 0;
7667 return I->getOperand(0);
7668 } else if (I->getOpcode() == Instruction::Mul) {
7669 // This value is scaled by 'RHS'.
7670 Scale = RHS->getZExtValue();
7671 Offset = 0;
7672 return I->getOperand(0);
7673 } else if (I->getOpcode() == Instruction::Add) {
7674 // We have X+C. Check to see if we really have (X*C2)+C1,
7675 // where C1 is divisible by C2.
7676 unsigned SubScale;
7677 Value *SubVal =
7678 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7679 Offset += RHS->getZExtValue();
7680 Scale = SubScale;
7681 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007682 }
7683 }
7684 }
7685
7686 // Otherwise, we can't look past this.
7687 Scale = 1;
7688 Offset = 0;
7689 return Val;
7690}
7691
7692
Chris Lattnerb3f83972005-10-24 06:03:58 +00007693/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7694/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007695Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007696 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007697 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007698
Chris Lattnerb53c2382005-10-24 06:22:12 +00007699 // Remove any uses of AI that are dead.
7700 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007701
Chris Lattnerb53c2382005-10-24 06:22:12 +00007702 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7703 Instruction *User = cast<Instruction>(*UI++);
7704 if (isInstructionTriviallyDead(User)) {
7705 while (UI != E && *UI == User)
7706 ++UI; // If this instruction uses AI more than once, don't break UI.
7707
Chris Lattnerb53c2382005-10-24 06:22:12 +00007708 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007709 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007710 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007711 }
7712 }
7713
Chris Lattnerb3f83972005-10-24 06:03:58 +00007714 // Get the type really allocated and the type casted to.
7715 const Type *AllocElTy = AI.getAllocatedType();
7716 const Type *CastElTy = PTy->getElementType();
7717 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007718
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007719 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7720 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007721 if (CastElTyAlign < AllocElTyAlign) return 0;
7722
Chris Lattner39387a52005-10-24 06:35:18 +00007723 // If the allocation has multiple uses, only promote it if we are strictly
7724 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007725 // same, we open the door to infinite loops of various kinds. (A reference
7726 // from a dbg.declare doesn't count as a use for this purpose.)
7727 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7728 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007729
Duncan Sands777d2302009-05-09 07:06:46 +00007730 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7731 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007732 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007733
Chris Lattner455fcc82005-10-29 03:19:53 +00007734 // See if we can satisfy the modulus by pulling a scale out of the array
7735 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007736 unsigned ArraySizeScale;
7737 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007738 Value *NumElements = // See if the array size is a decomposable linear expr.
7739 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7740
Chris Lattner455fcc82005-10-29 03:19:53 +00007741 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7742 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007743 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7744 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007745
Chris Lattner455fcc82005-10-29 03:19:53 +00007746 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7747 Value *Amt = 0;
7748 if (Scale == 1) {
7749 Amt = NumElements;
7750 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007751 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007752 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7753 if (isa<ConstantInt>(NumElements))
Dan Gohman6de29f82009-06-15 22:12:54 +00007754 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7755 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007756 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007757 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007758 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007759 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007760 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007761 }
7762
Jeff Cohen86796be2007-04-04 16:58:57 +00007763 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7764 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007765 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007766 Amt = InsertNewInstBefore(Tmp, AI);
7767 }
7768
Chris Lattnerb3f83972005-10-24 06:03:58 +00007769 AllocationInst *New;
7770 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007771 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007772 else
Chris Lattner6934a042007-02-11 01:23:03 +00007773 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007774 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007775 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007776
Dale Johannesena0a66372009-03-05 00:39:02 +00007777 // If the allocation has one real use plus a dbg.declare, just remove the
7778 // declare.
7779 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7780 EraseInstFromFunction(*DI);
7781 }
7782 // If the allocation has multiple real uses, insert a cast and change all
7783 // things that used it to use the new cast. This will also hack on CI, but it
7784 // will die soon.
7785 else if (!AI.hasOneUse()) {
Chris Lattner39387a52005-10-24 06:35:18 +00007786 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007787 // New is the allocation instruction, pointer typed. AI is the original
7788 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7789 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007790 InsertNewInstBefore(NewCast, AI);
7791 AI.replaceAllUsesWith(NewCast);
7792 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007793 return ReplaceInstUsesWith(CI, New);
7794}
7795
Chris Lattner70074e02006-05-13 02:06:03 +00007796/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007797/// and return it as type Ty without inserting any new casts and without
7798/// changing the computed value. This is used by code that tries to decide
7799/// whether promoting or shrinking integer operations to wider or smaller types
7800/// will allow us to eliminate a truncate or extend.
7801///
7802/// This is a truncation operation if Ty is smaller than V->getType(), or an
7803/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007804///
7805/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7806/// should return true if trunc(V) can be computed by computing V in the smaller
7807/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7808/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7809/// efficiently truncated.
7810///
7811/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7812/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7813/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007814bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007815 unsigned CastOpc,
7816 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007817 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007818 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007819 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007820
7821 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007822 if (!I) return false;
7823
Dan Gohman6de29f82009-06-15 22:12:54 +00007824 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007825
Chris Lattner951626b2007-08-02 06:11:14 +00007826 // If this is an extension or truncate, we can often eliminate it.
7827 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7828 // If this is a cast from the destination type, we can trivially eliminate
7829 // it, and this will remove a cast overall.
7830 if (I->getOperand(0)->getType() == Ty) {
7831 // If the first operand is itself a cast, and is eliminable, do not count
7832 // this as an eliminable cast. We would prefer to eliminate those two
7833 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007834 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007835 ++NumCastsRemoved;
7836 return true;
7837 }
7838 }
7839
7840 // We can't extend or shrink something that has multiple uses: doing so would
7841 // require duplicating the instruction in general, which isn't profitable.
7842 if (!I->hasOneUse()) return false;
7843
Evan Chengf35fd542009-01-15 17:01:23 +00007844 unsigned Opc = I->getOpcode();
7845 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007846 case Instruction::Add:
7847 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007848 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007849 case Instruction::And:
7850 case Instruction::Or:
7851 case Instruction::Xor:
7852 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007853 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007854 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007855 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007856 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007857
Chris Lattner46b96052006-11-29 07:18:39 +00007858 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007859 // If we are truncating the result of this SHL, and if it's a shift of a
7860 // constant amount, we can always perform a SHL in a smaller type.
7861 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007862 uint32_t BitWidth = Ty->getScalarSizeInBits();
7863 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007864 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007865 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007866 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007867 }
7868 break;
7869 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007870 // If this is a truncate of a logical shr, we can truncate it to a smaller
7871 // lshr iff we know that the bits we would otherwise be shifting in are
7872 // already zeros.
7873 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007874 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7875 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007876 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007877 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007878 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7879 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007880 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007881 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007882 }
7883 }
Chris Lattner46b96052006-11-29 07:18:39 +00007884 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007885 case Instruction::ZExt:
7886 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007887 case Instruction::Trunc:
7888 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007889 // can safely replace it. Note that replacing it does not reduce the number
7890 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007891 if (Opc == CastOpc)
7892 return true;
7893
7894 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007895 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007896 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007897 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007898 case Instruction::Select: {
7899 SelectInst *SI = cast<SelectInst>(I);
7900 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007901 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007902 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007903 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007904 }
Chris Lattner8114b712008-06-18 04:00:49 +00007905 case Instruction::PHI: {
7906 // We can change a phi if we can change all operands.
7907 PHINode *PN = cast<PHINode>(I);
7908 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7909 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007910 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007911 return false;
7912 return true;
7913 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007914 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007915 // TODO: Can handle more cases here.
7916 break;
7917 }
7918
7919 return false;
7920}
7921
7922/// EvaluateInDifferentType - Given an expression that
7923/// CanEvaluateInDifferentType returns true for, actually insert the code to
7924/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007925Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007926 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007927 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007928 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007929
7930 // Otherwise, it must be an instruction.
7931 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007932 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007933 unsigned Opc = I->getOpcode();
7934 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007935 case Instruction::Add:
7936 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007937 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007938 case Instruction::And:
7939 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007941 case Instruction::AShr:
7942 case Instruction::LShr:
7943 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007944 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007945 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007946 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007947 break;
7948 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007949 case Instruction::Trunc:
7950 case Instruction::ZExt:
7951 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007952 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007953 // just return the source. There's no need to insert it because it is not
7954 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007955 if (I->getOperand(0)->getType() == Ty)
7956 return I->getOperand(0);
7957
Chris Lattner8114b712008-06-18 04:00:49 +00007958 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007959 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007960 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007961 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007962 case Instruction::Select: {
7963 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7964 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7965 Res = SelectInst::Create(I->getOperand(0), True, False);
7966 break;
7967 }
Chris Lattner8114b712008-06-18 04:00:49 +00007968 case Instruction::PHI: {
7969 PHINode *OPN = cast<PHINode>(I);
7970 PHINode *NPN = PHINode::Create(Ty);
7971 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7972 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7973 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7974 }
7975 Res = NPN;
7976 break;
7977 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007978 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007979 // TODO: Can handle more cases here.
7980 assert(0 && "Unreachable!");
7981 break;
7982 }
7983
Chris Lattner8114b712008-06-18 04:00:49 +00007984 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007985 return InsertNewInstBefore(Res, *I);
7986}
7987
Reid Spencer3da59db2006-11-27 01:05:10 +00007988/// @brief Implement the transforms common to all CastInst visitors.
7989Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007990 Value *Src = CI.getOperand(0);
7991
Dan Gohman23d9d272007-05-11 21:10:54 +00007992 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007993 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007994 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007995 if (Instruction::CastOps opc =
7996 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7997 // The first cast (CSrc) is eliminable so we need to fix up or replace
7998 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007999 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008000 }
8001 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008002
Reid Spencer3da59db2006-11-27 01:05:10 +00008003 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008004 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8005 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8006 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008007
8008 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008009 if (isa<PHINode>(Src))
8010 if (Instruction *NV = FoldOpIntoPhi(CI))
8011 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008012
Reid Spencer3da59db2006-11-27 01:05:10 +00008013 return 0;
8014}
8015
Chris Lattner46cd5a12009-01-09 05:44:56 +00008016/// FindElementAtOffset - Given a type and a constant offset, determine whether
8017/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008018/// the specified offset. If so, fill them into NewIndices and return the
8019/// resultant element type, otherwise return null.
8020static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8021 SmallVectorImpl<Value*> &NewIndices,
8022 const TargetData *TD) {
8023 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008024
8025 // Start with the index over the outer type. Note that the type size
8026 // might be zero (even if the offset isn't zero) if the indexed type
8027 // is something like [0 x {int, int}]
8028 const Type *IntPtrTy = TD->getIntPtrType();
8029 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008030 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008031 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008032 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008033
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008034 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008035 if (Offset < 0) {
8036 --FirstIdx;
8037 Offset += TySize;
8038 assert(Offset >= 0);
8039 }
8040 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8041 }
8042
8043 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8044
8045 // Index into the types. If we fail, set OrigBase to null.
8046 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008047 // Indexing into tail padding between struct/array elements.
8048 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008049 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008050
Chris Lattner46cd5a12009-01-09 05:44:56 +00008051 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8052 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008053 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8054 "Offset must stay within the indexed type");
8055
Chris Lattner46cd5a12009-01-09 05:44:56 +00008056 unsigned Elt = SL->getElementContainingOffset(Offset);
8057 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8058
8059 Offset -= SL->getElementOffset(Elt);
8060 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008061 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008062 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008063 assert(EltSize && "Cannot index into a zero-sized array");
8064 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8065 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008066 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008067 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008068 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008069 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008070 }
8071 }
8072
Chris Lattner3914f722009-01-24 01:00:13 +00008073 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008074}
8075
Chris Lattnerd3e28342007-04-27 17:44:50 +00008076/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8077Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8078 Value *Src = CI.getOperand(0);
8079
Chris Lattnerd3e28342007-04-27 17:44:50 +00008080 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008081 // If casting the result of a getelementptr instruction with no offset, turn
8082 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008083 if (GEP->hasAllZeroIndices()) {
8084 // Changing the cast operand is usually not a good idea but it is safe
8085 // here because the pointer operand is being replaced with another
8086 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00008087 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008088 CI.setOperand(0, GEP->getOperand(0));
8089 return &CI;
8090 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008091
8092 // If the GEP has a single use, and the base pointer is a bitcast, and the
8093 // GEP computes a constant offset, see if we can convert these three
8094 // instructions into fewer. This typically happens with unions and other
8095 // non-type-safe code.
8096 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8097 if (GEP->hasAllConstantIndices()) {
8098 // We are guaranteed to get a constant from EmitGEPOffset.
8099 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8100 int64_t Offset = OffsetV->getSExtValue();
8101
8102 // Get the base pointer input of the bitcast, and the type it points to.
8103 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8104 const Type *GEPIdxTy =
8105 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008106 SmallVector<Value*, 8> NewIndices;
8107 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8108 // If we were able to index down into an element, create the GEP
8109 // and bitcast the result. This eliminates one bitcast, potentially
8110 // two.
8111 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8112 NewIndices.begin(),
8113 NewIndices.end(), "");
8114 InsertNewInstBefore(NGEP, CI);
8115 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008116
Chris Lattner46cd5a12009-01-09 05:44:56 +00008117 if (isa<BitCastInst>(CI))
8118 return new BitCastInst(NGEP, CI.getType());
8119 assert(isa<PtrToIntInst>(CI));
8120 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008121 }
8122 }
8123 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008124 }
8125
8126 return commonCastTransforms(CI);
8127}
8128
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008129/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8130/// type like i42. We don't want to introduce operations on random non-legal
8131/// integer types where they don't already exist in the code. In the future,
8132/// we should consider making this based off target-data, so that 32-bit targets
8133/// won't get i64 operations etc.
8134static bool isSafeIntegerType(const Type *Ty) {
8135 switch (Ty->getPrimitiveSizeInBits()) {
8136 case 8:
8137 case 16:
8138 case 32:
8139 case 64:
8140 return true;
8141 default:
8142 return false;
8143 }
8144}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008145
Chris Lattnerc739cd62007-03-03 05:27:34 +00008146/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8147/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00008148/// cases.
8149/// @brief Implement the transforms common to CastInst with integer operands
8150Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8151 if (Instruction *Result = commonCastTransforms(CI))
8152 return Result;
8153
8154 Value *Src = CI.getOperand(0);
8155 const Type *SrcTy = Src->getType();
8156 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008157 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8158 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008159
Reid Spencer3da59db2006-11-27 01:05:10 +00008160 // See if we can simplify any instructions used by the LHS whose sole
8161 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008162 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008163 return &CI;
8164
8165 // If the source isn't an instruction or has more than one use then we
8166 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008167 Instruction *SrcI = dyn_cast<Instruction>(Src);
8168 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008169 return 0;
8170
Chris Lattnerc739cd62007-03-03 05:27:34 +00008171 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008172 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008173 if (!isa<BitCastInst>(CI) &&
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008174 // Only do this if the dest type is a simple type, don't convert the
8175 // expression tree to something weird like i93 unless the source is also
8176 // strange.
Dan Gohman6de29f82009-06-15 22:12:54 +00008177 (isSafeIntegerType(DestTy->getScalarType()) ||
8178 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8179 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008180 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008181 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008182 // eliminates the cast, so it is always a win. If this is a zero-extension,
8183 // we need to do an AND to maintain the clear top-part of the computation,
8184 // so we require that the input have eliminated at least one cast. If this
8185 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008186 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008187 bool DoXForm = false;
8188 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008189 switch (CI.getOpcode()) {
8190 default:
8191 // All the others use floating point so we shouldn't actually
8192 // get here because of the check above.
8193 assert(0 && "Unknown cast type");
8194 case Instruction::Trunc:
8195 DoXForm = true;
8196 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008197 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008198 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008199 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008200 // If it's unnecessary to issue an AND to clear the high bits, it's
8201 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008202 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008203 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8204 if (MaskedValueIsZero(TryRes, Mask))
8205 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008206
8207 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008208 if (TryI->use_empty())
8209 EraseInstFromFunction(*TryI);
8210 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008211 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008212 }
Evan Chengf35fd542009-01-15 17:01:23 +00008213 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008214 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008215 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008216 // If we do not have to emit the truncate + sext pair, then it's always
8217 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008218 //
8219 // It's not safe to eliminate the trunc + sext pair if one of the
8220 // eliminated cast is a truncate. e.g.
8221 // t2 = trunc i32 t1 to i16
8222 // t3 = sext i16 t2 to i32
8223 // !=
8224 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008225 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008226 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8227 if (NumSignBits > (DestBitSize - SrcBitSize))
8228 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008229
8230 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008231 if (TryI->use_empty())
8232 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008233 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008234 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008235 }
Evan Chengf35fd542009-01-15 17:01:23 +00008236 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008237
8238 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00008239 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8240 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00008241 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8242 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008243 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008244 // Just replace this cast with the result.
8245 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008246
Reid Spencer3da59db2006-11-27 01:05:10 +00008247 assert(Res->getType() == DestTy);
8248 switch (CI.getOpcode()) {
8249 default: assert(0 && "Unknown cast type!");
8250 case Instruction::Trunc:
8251 case Instruction::BitCast:
8252 // Just replace this cast with the result.
8253 return ReplaceInstUsesWith(CI, Res);
8254 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008255 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008256
8257 // If the high bits are already zero, just replace this cast with the
8258 // result.
8259 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8260 if (MaskedValueIsZero(Res, Mask))
8261 return ReplaceInstUsesWith(CI, Res);
8262
8263 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008264 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8265 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008266 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008267 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008268 case Instruction::SExt: {
8269 // If the high bits are already filled with sign bit, just replace this
8270 // cast with the result.
8271 unsigned NumSignBits = ComputeNumSignBits(Res);
8272 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008273 return ReplaceInstUsesWith(CI, Res);
8274
Reid Spencer3da59db2006-11-27 01:05:10 +00008275 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008276 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008277 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8278 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008279 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008280 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008281 }
8282 }
8283
8284 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8285 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8286
8287 switch (SrcI->getOpcode()) {
8288 case Instruction::Add:
8289 case Instruction::Mul:
8290 case Instruction::And:
8291 case Instruction::Or:
8292 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008293 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008294 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8295 // Don't insert two casts if they cannot be eliminated. We allow
8296 // two casts to be inserted if the sizes are the same. This could
8297 // only be converting signedness, which is a noop.
8298 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008299 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8300 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008301 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008302 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8303 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008304 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008305 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008306 }
8307 }
8308
8309 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8310 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8311 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008312 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008313 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008314 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008315 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008316 }
8317 break;
8318 case Instruction::SDiv:
8319 case Instruction::UDiv:
8320 case Instruction::SRem:
8321 case Instruction::URem:
8322 // If we are just changing the sign, rewrite.
8323 if (DestBitSize == SrcBitSize) {
8324 // Don't insert two casts if they cannot be eliminated. We allow
8325 // two casts to be inserted if the sizes are the same. This could
8326 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008327 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8328 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008329 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8330 Op0, DestTy, *SrcI);
8331 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8332 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008333 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008334 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8335 }
8336 }
8337 break;
8338
8339 case Instruction::Shl:
8340 // Allow changing the sign of the source operand. Do not allow
8341 // changing the size of the shift, UNLESS the shift amount is a
8342 // constant. We must not change variable sized shifts to a smaller
8343 // size, because it is undefined to shift more bits out than exist
8344 // in the value.
8345 if (DestBitSize == SrcBitSize ||
8346 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008347 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8348 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008349 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8350 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008351 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008352 }
8353 break;
8354 case Instruction::AShr:
8355 // If this is a signed shr, and if all bits shifted in are about to be
8356 // truncated off, turn it into an unsigned shr to allow greater
8357 // simplifications.
8358 if (DestBitSize < SrcBitSize &&
8359 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008360 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008361 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8362 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008363 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008364 }
8365 }
8366 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008367 }
8368 return 0;
8369}
8370
Chris Lattner8a9f5712007-04-11 06:57:46 +00008371Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008372 if (Instruction *Result = commonIntCastTransforms(CI))
8373 return Result;
8374
8375 Value *Src = CI.getOperand(0);
8376 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008377 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8378 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008379
8380 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00008381 if (DestBitWidth == 1 &&
8382 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008383 Constant *One = ConstantInt::get(Src->getType(), 1);
8384 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8385 Value *Zero = Constant::getNullValue(Src->getType());
8386 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8387 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008388
Chris Lattner4f9797d2009-03-24 18:15:30 +00008389 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8390 ConstantInt *ShAmtV = 0;
8391 Value *ShiftOp = 0;
8392 if (Src->hasOneUse() &&
8393 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8394 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8395
8396 // Get a mask for the bits shifting in.
8397 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8398 if (MaskedValueIsZero(ShiftOp, Mask)) {
8399 if (ShAmt >= DestBitWidth) // All zeros.
8400 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8401
8402 // Okay, we can shrink this. Truncate the input, then return a new
8403 // shift.
8404 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8405 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8406 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008407 }
8408 }
8409
8410 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008411}
8412
Evan Chengb98a10e2008-03-24 00:21:34 +00008413/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8414/// in order to eliminate the icmp.
8415Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8416 bool DoXform) {
8417 // If we are just checking for a icmp eq of a single bit and zext'ing it
8418 // to an integer, then shift the bit to the appropriate place and then
8419 // cast to integer to avoid the comparison.
8420 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8421 const APInt &Op1CV = Op1C->getValue();
8422
8423 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8424 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8425 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8426 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8427 if (!DoXform) return ICI;
8428
8429 Value *In = ICI->getOperand(0);
8430 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008431 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008432 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008433 In->getName()+".lobit"),
8434 CI);
8435 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008436 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008437 false/*ZExt*/, "tmp", &CI);
8438
8439 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8440 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008441 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008442 In->getName()+".not"),
8443 CI);
8444 }
8445
8446 return ReplaceInstUsesWith(CI, In);
8447 }
8448
8449
8450
8451 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8452 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8453 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8454 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8455 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8456 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8457 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8458 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8459 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8460 // This only works for EQ and NE
8461 ICI->isEquality()) {
8462 // If Op1C some other power of two, convert:
8463 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8464 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8465 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8466 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8467
8468 APInt KnownZeroMask(~KnownZero);
8469 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8470 if (!DoXform) return ICI;
8471
8472 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8473 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8474 // (X&4) == 2 --> false
8475 // (X&4) != 2 --> true
8476 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8477 Res = ConstantExpr::getZExt(Res, CI.getType());
8478 return ReplaceInstUsesWith(CI, Res);
8479 }
8480
8481 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8482 Value *In = ICI->getOperand(0);
8483 if (ShiftAmt) {
8484 // Perform a logical shr by shiftamt.
8485 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008486 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008487 ConstantInt::get(In->getType(), ShiftAmt),
8488 In->getName()+".lobit"), CI);
8489 }
8490
8491 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8492 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008493 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008494 InsertNewInstBefore(cast<Instruction>(In), CI);
8495 }
8496
8497 if (CI.getType() == In->getType())
8498 return ReplaceInstUsesWith(CI, In);
8499 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008500 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008501 }
8502 }
8503 }
8504
8505 return 0;
8506}
8507
Chris Lattner8a9f5712007-04-11 06:57:46 +00008508Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008509 // If one of the common conversion will work ..
8510 if (Instruction *Result = commonIntCastTransforms(CI))
8511 return Result;
8512
8513 Value *Src = CI.getOperand(0);
8514
Chris Lattnera84f47c2009-02-17 20:47:23 +00008515 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8516 // types and if the sizes are just right we can convert this into a logical
8517 // 'and' which will be much cheaper than the pair of casts.
8518 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8519 // Get the sizes of the types involved. We know that the intermediate type
8520 // will be smaller than A or C, but don't know the relation between A and C.
8521 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008522 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8523 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8524 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008525 // If we're actually extending zero bits, then if
8526 // SrcSize < DstSize: zext(a & mask)
8527 // SrcSize == DstSize: a & mask
8528 // SrcSize > DstSize: trunc(a) & mask
8529 if (SrcSize < DstSize) {
8530 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Dan Gohman6de29f82009-06-15 22:12:54 +00008531 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008532 Instruction *And =
8533 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8534 InsertNewInstBefore(And, CI);
8535 return new ZExtInst(And, CI.getType());
8536 } else if (SrcSize == DstSize) {
8537 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Dan Gohman6de29f82009-06-15 22:12:54 +00008538 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8539 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008540 } else if (SrcSize > DstSize) {
8541 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8542 InsertNewInstBefore(Trunc, CI);
8543 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Dan Gohman6de29f82009-06-15 22:12:54 +00008544 return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Trunc->getType(),
8545 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008546 }
8547 }
8548
Evan Chengb98a10e2008-03-24 00:21:34 +00008549 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8550 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008551
Evan Chengb98a10e2008-03-24 00:21:34 +00008552 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8553 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8554 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8555 // of the (zext icmp) will be transformed.
8556 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8557 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8558 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8559 (transformZExtICmp(LHS, CI, false) ||
8560 transformZExtICmp(RHS, CI, false))) {
8561 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8562 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008563 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008564 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008565 }
8566
Dan Gohmana392c782009-06-17 23:17:05 +00008567 // zext(trunc(t) & C) -> (t & C) if C is a mask.
8568 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8569 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8570 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8571 Value *TI0 = TI->getOperand(0);
8572 if (TI0->getType() == CI.getType()) {
8573 unsigned TO = C->getValue().countTrailingOnes();
8574 if (APIntOps::isMask(TO, C->getValue()))
8575 return
8576 BinaryOperator::Create(Instruction::And, TI0,
8577 ConstantExpr::getZExt(C, CI.getType()));
8578 }
8579 }
8580
Reid Spencer3da59db2006-11-27 01:05:10 +00008581 return 0;
8582}
8583
Chris Lattner8a9f5712007-04-11 06:57:46 +00008584Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008585 if (Instruction *I = commonIntCastTransforms(CI))
8586 return I;
8587
Chris Lattner8a9f5712007-04-11 06:57:46 +00008588 Value *Src = CI.getOperand(0);
8589
Dan Gohman1975d032008-10-30 20:40:10 +00008590 // Canonicalize sign-extend from i1 to a select.
8591 if (Src->getType() == Type::Int1Ty)
8592 return SelectInst::Create(Src,
8593 ConstantInt::getAllOnesValue(CI.getType()),
8594 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008595
8596 // See if the value being truncated is already sign extended. If so, just
8597 // eliminate the trunc/sext pair.
8598 if (getOpcode(Src) == Instruction::Trunc) {
8599 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008600 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8601 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8602 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008603 unsigned NumSignBits = ComputeNumSignBits(Op);
8604
8605 if (OpBits == DestBits) {
8606 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8607 // bits, it is already ready.
8608 if (NumSignBits > DestBits-MidBits)
8609 return ReplaceInstUsesWith(CI, Op);
8610 } else if (OpBits < DestBits) {
8611 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8612 // bits, just sext from i32.
8613 if (NumSignBits > OpBits-MidBits)
8614 return new SExtInst(Op, CI.getType(), "tmp");
8615 } else {
8616 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8617 // bits, just truncate to i32.
8618 if (NumSignBits > OpBits-MidBits)
8619 return new TruncInst(Op, CI.getType(), "tmp");
8620 }
8621 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008622
8623 // If the input is a shl/ashr pair of a same constant, then this is a sign
8624 // extension from a smaller value. If we could trust arbitrary bitwidth
8625 // integers, we could turn this into a truncate to the smaller bit and then
8626 // use a sext for the whole extension. Since we don't, look deeper and check
8627 // for a truncate. If the source and dest are the same type, eliminate the
8628 // trunc and extend and just do shifts. For example, turn:
8629 // %a = trunc i32 %i to i8
8630 // %b = shl i8 %a, 6
8631 // %c = ashr i8 %b, 6
8632 // %d = sext i8 %c to i32
8633 // into:
8634 // %a = shl i32 %i, 30
8635 // %d = ashr i32 %a, 30
8636 Value *A = 0;
8637 ConstantInt *BA = 0, *CA = 0;
8638 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8639 m_ConstantInt(CA))) &&
8640 BA == CA && isa<TruncInst>(A)) {
8641 Value *I = cast<TruncInst>(A)->getOperand(0);
8642 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008643 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8644 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008645 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8646 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8647 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8648 CI.getName()), CI);
8649 return BinaryOperator::CreateAShr(I, ShAmtV);
8650 }
8651 }
8652
Chris Lattnerba417832007-04-11 06:12:58 +00008653 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008654}
8655
Chris Lattnerb7530652008-01-27 05:29:54 +00008656/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8657/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008658static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008659 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008660 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008661 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8662 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008663 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008664 return 0;
8665}
8666
8667/// LookThroughFPExtensions - If this is an fp extension instruction, look
8668/// through it until we get the source value.
8669static Value *LookThroughFPExtensions(Value *V) {
8670 if (Instruction *I = dyn_cast<Instruction>(V))
8671 if (I->getOpcode() == Instruction::FPExt)
8672 return LookThroughFPExtensions(I->getOperand(0));
8673
8674 // If this value is a constant, return the constant in the smallest FP type
8675 // that can accurately represent it. This allows us to turn
8676 // (float)((double)X+2.0) into x+2.0f.
8677 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8678 if (CFP->getType() == Type::PPC_FP128Ty)
8679 return V; // No constant folding of this.
8680 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008681 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008682 return V;
8683 if (CFP->getType() == Type::DoubleTy)
8684 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008685 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008686 return V;
8687 // Don't try to shrink to various long double types.
8688 }
8689
8690 return V;
8691}
8692
8693Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8694 if (Instruction *I = commonCastTransforms(CI))
8695 return I;
8696
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008697 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008698 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008699 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008700 // many builtins (sqrt, etc).
8701 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8702 if (OpI && OpI->hasOneUse()) {
8703 switch (OpI->getOpcode()) {
8704 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008705 case Instruction::FAdd:
8706 case Instruction::FSub:
8707 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008708 case Instruction::FDiv:
8709 case Instruction::FRem:
8710 const Type *SrcTy = OpI->getType();
8711 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8712 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8713 if (LHSTrunc->getType() != SrcTy &&
8714 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008715 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008716 // If the source types were both smaller than the destination type of
8717 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008718 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8719 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008720 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8721 CI.getType(), CI);
8722 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8723 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008724 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008725 }
8726 }
8727 break;
8728 }
8729 }
8730 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008731}
8732
8733Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8734 return commonCastTransforms(CI);
8735}
8736
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008737Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008738 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8739 if (OpI == 0)
8740 return commonCastTransforms(FI);
8741
8742 // fptoui(uitofp(X)) --> X
8743 // fptoui(sitofp(X)) --> X
8744 // This is safe if the intermediate type has enough bits in its mantissa to
8745 // accurately represent all values of X. For example, do not do this with
8746 // i64->float->i64. This is also safe for sitofp case, because any negative
8747 // 'X' value would cause an undefined result for the fptoui.
8748 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8749 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008750 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008751 OpI->getType()->getFPMantissaWidth())
8752 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008753
8754 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008755}
8756
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008757Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008758 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8759 if (OpI == 0)
8760 return commonCastTransforms(FI);
8761
8762 // fptosi(sitofp(X)) --> X
8763 // fptosi(uitofp(X)) --> X
8764 // This is safe if the intermediate type has enough bits in its mantissa to
8765 // accurately represent all values of X. For example, do not do this with
8766 // i64->float->i64. This is also safe for sitofp case, because any negative
8767 // 'X' value would cause an undefined result for the fptoui.
8768 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8769 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008770 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008771 OpI->getType()->getFPMantissaWidth())
8772 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008773
8774 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008775}
8776
8777Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8778 return commonCastTransforms(CI);
8779}
8780
8781Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8782 return commonCastTransforms(CI);
8783}
8784
Chris Lattnera0e69692009-03-24 18:35:40 +00008785Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8786 // If the destination integer type is smaller than the intptr_t type for
8787 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8788 // trunc to be exposed to other transforms. Don't do this for extending
8789 // ptrtoint's, because we don't know if the target sign or zero extends its
8790 // pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008791 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008792 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8793 TD->getIntPtrType(),
8794 "tmp"), CI);
8795 return new TruncInst(P, CI.getType());
8796 }
8797
Chris Lattnerd3e28342007-04-27 17:44:50 +00008798 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008799}
8800
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008801Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008802 // If the source integer type is larger than the intptr_t type for
8803 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8804 // allows the trunc to be exposed to other transforms. Don't do this for
8805 // extending inttoptr's, because we don't know if the target sign or zero
8806 // extends to pointers.
Dan Gohman6de29f82009-06-15 22:12:54 +00008807 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008808 TD->getPointerSizeInBits()) {
8809 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8810 TD->getIntPtrType(),
8811 "tmp"), CI);
8812 return new IntToPtrInst(P, CI.getType());
8813 }
8814
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008815 if (Instruction *I = commonCastTransforms(CI))
8816 return I;
8817
8818 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8819 if (!DestPointee->isSized()) return 0;
8820
8821 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8822 ConstantInt *Cst;
8823 Value *X;
8824 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8825 m_ConstantInt(Cst)))) {
8826 // If the source and destination operands have the same type, see if this
8827 // is a single-index GEP.
8828 if (X->getType() == CI.getType()) {
8829 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008830 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008831
8832 // Convert the constant to intptr type.
8833 APInt Offset = Cst->getValue();
8834 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8835
8836 // If Offset is evenly divisible by Size, we can do this xform.
8837 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8838 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008839 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008840 }
8841 }
8842 // TODO: Could handle other cases, e.g. where add is indexing into field of
8843 // struct etc.
8844 } else if (CI.getOperand(0)->hasOneUse() &&
8845 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8846 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8847 // "inttoptr+GEP" instead of "add+intptr".
8848
8849 // Get the size of the pointee type.
Duncan Sands777d2302009-05-09 07:06:46 +00008850 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008851
8852 // Convert the constant to intptr type.
8853 APInt Offset = Cst->getValue();
8854 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8855
8856 // If Offset is evenly divisible by Size, we can do this xform.
8857 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8858 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8859
8860 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8861 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008862 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008863 }
8864 }
8865 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008866}
8867
Chris Lattnerd3e28342007-04-27 17:44:50 +00008868Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008869 // If the operands are integer typed then apply the integer transforms,
8870 // otherwise just apply the common ones.
8871 Value *Src = CI.getOperand(0);
8872 const Type *SrcTy = Src->getType();
8873 const Type *DestTy = CI.getType();
8874
Chris Lattner42a75512007-01-15 02:27:26 +00008875 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008876 if (Instruction *Result = commonIntCastTransforms(CI))
8877 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008878 } else if (isa<PointerType>(SrcTy)) {
8879 if (Instruction *I = commonPointerCastTransforms(CI))
8880 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008881 } else {
8882 if (Instruction *Result = commonCastTransforms(CI))
8883 return Result;
8884 }
8885
8886
8887 // Get rid of casts from one type to the same type. These are useless and can
8888 // be replaced by the operand.
8889 if (DestTy == Src->getType())
8890 return ReplaceInstUsesWith(CI, Src);
8891
Reid Spencer3da59db2006-11-27 01:05:10 +00008892 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008893 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8894 const Type *DstElTy = DstPTy->getElementType();
8895 const Type *SrcElTy = SrcPTy->getElementType();
8896
Nate Begeman83ad90a2008-03-31 00:22:16 +00008897 // If the address spaces don't match, don't eliminate the bitcast, which is
8898 // required for changing types.
8899 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8900 return 0;
8901
Chris Lattnerd3e28342007-04-27 17:44:50 +00008902 // If we are casting a malloc or alloca to a pointer to a type of the same
8903 // size, rewrite the allocation instruction to allocate the "right" type.
8904 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8905 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8906 return V;
8907
Chris Lattnerd717c182007-05-05 22:32:24 +00008908 // If the source and destination are pointers, and this cast is equivalent
8909 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008910 // This can enhance SROA and other transforms that want type-safe pointers.
8911 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8912 unsigned NumZeros = 0;
8913 while (SrcElTy != DstElTy &&
8914 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8915 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8916 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8917 ++NumZeros;
8918 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008919
Chris Lattnerd3e28342007-04-27 17:44:50 +00008920 // If we found a path from the src to dest, create the getelementptr now.
8921 if (SrcElTy == DstElTy) {
8922 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008923 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8924 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008925 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008926 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008927
Reid Spencer3da59db2006-11-27 01:05:10 +00008928 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8929 if (SVI->hasOneUse()) {
8930 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8931 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008932 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008933 cast<VectorType>(DestTy)->getNumElements() ==
8934 SVI->getType()->getNumElements() &&
8935 SVI->getType()->getNumElements() ==
8936 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008937 CastInst *Tmp;
8938 // If either of the operands is a cast from CI.getType(), then
8939 // evaluating the shuffle in the casted destination's type will allow
8940 // us to eliminate at least one cast.
8941 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8942 Tmp->getOperand(0)->getType() == DestTy) ||
8943 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8944 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008945 Value *LHS = InsertCastBefore(Instruction::BitCast,
8946 SVI->getOperand(0), DestTy, CI);
8947 Value *RHS = InsertCastBefore(Instruction::BitCast,
8948 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008949 // Return a new shuffle vector. Use the same element ID's, as we
8950 // know the vector types match #elts.
8951 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008952 }
8953 }
8954 }
8955 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008956 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008957}
8958
Chris Lattnere576b912004-04-09 23:46:01 +00008959/// GetSelectFoldableOperands - We want to turn code that looks like this:
8960/// %C = or %A, %B
8961/// %D = select %cond, %C, %A
8962/// into:
8963/// %C = select %cond, %B, 0
8964/// %D = or %A, %C
8965///
8966/// Assuming that the specified instruction is an operand to the select, return
8967/// a bitmask indicating which operands of this instruction are foldable if they
8968/// equal the other incoming value of the select.
8969///
8970static unsigned GetSelectFoldableOperands(Instruction *I) {
8971 switch (I->getOpcode()) {
8972 case Instruction::Add:
8973 case Instruction::Mul:
8974 case Instruction::And:
8975 case Instruction::Or:
8976 case Instruction::Xor:
8977 return 3; // Can fold through either operand.
8978 case Instruction::Sub: // Can only fold on the amount subtracted.
8979 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008980 case Instruction::LShr:
8981 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008982 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008983 default:
8984 return 0; // Cannot fold
8985 }
8986}
8987
8988/// GetSelectFoldableConstant - For the same transformation as the previous
8989/// function, return the identity constant that goes into the select.
8990static Constant *GetSelectFoldableConstant(Instruction *I) {
8991 switch (I->getOpcode()) {
8992 default: assert(0 && "This cannot happen!"); abort();
8993 case Instruction::Add:
8994 case Instruction::Sub:
8995 case Instruction::Or:
8996 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008997 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008998 case Instruction::LShr:
8999 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00009000 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009001 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00009002 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009003 case Instruction::Mul:
9004 return ConstantInt::get(I->getType(), 1);
9005 }
9006}
9007
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009008/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9009/// have the same opcode and only one use each. Try to simplify this.
9010Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9011 Instruction *FI) {
9012 if (TI->getNumOperands() == 1) {
9013 // If this is a non-volatile load or a cast from the same type,
9014 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009015 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009016 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9017 return 0;
9018 } else {
9019 return 0; // unknown unary op.
9020 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009021
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009022 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009023 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9024 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009025 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009026 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009027 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009028 }
9029
Reid Spencer832254e2007-02-02 02:16:23 +00009030 // Only handle binary operators here.
9031 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009032 return 0;
9033
9034 // Figure out if the operations have any operands in common.
9035 Value *MatchOp, *OtherOpT, *OtherOpF;
9036 bool MatchIsOpZero;
9037 if (TI->getOperand(0) == FI->getOperand(0)) {
9038 MatchOp = TI->getOperand(0);
9039 OtherOpT = TI->getOperand(1);
9040 OtherOpF = FI->getOperand(1);
9041 MatchIsOpZero = true;
9042 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9043 MatchOp = TI->getOperand(1);
9044 OtherOpT = TI->getOperand(0);
9045 OtherOpF = FI->getOperand(0);
9046 MatchIsOpZero = false;
9047 } else if (!TI->isCommutative()) {
9048 return 0;
9049 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9050 MatchOp = TI->getOperand(0);
9051 OtherOpT = TI->getOperand(1);
9052 OtherOpF = FI->getOperand(0);
9053 MatchIsOpZero = true;
9054 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9055 MatchOp = TI->getOperand(1);
9056 OtherOpT = TI->getOperand(0);
9057 OtherOpF = FI->getOperand(1);
9058 MatchIsOpZero = true;
9059 } else {
9060 return 0;
9061 }
9062
9063 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009064 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9065 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009066 InsertNewInstBefore(NewSI, SI);
9067
9068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9069 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009070 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009071 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009072 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009073 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00009074 assert(0 && "Shouldn't get here");
9075 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009076}
9077
Evan Chengde621922009-03-31 20:42:45 +00009078static bool isSelect01(Constant *C1, Constant *C2) {
9079 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9080 if (!C1I)
9081 return false;
9082 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9083 if (!C2I)
9084 return false;
9085 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9086}
9087
9088/// FoldSelectIntoOp - Try fold the select into one of the operands to
9089/// facilitate further optimization.
9090Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9091 Value *FalseVal) {
9092 // See the comment above GetSelectFoldableOperands for a description of the
9093 // transformation we are doing here.
9094 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9095 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9096 !isa<Constant>(FalseVal)) {
9097 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9098 unsigned OpToFold = 0;
9099 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9100 OpToFold = 1;
9101 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9102 OpToFold = 2;
9103 }
9104
9105 if (OpToFold) {
9106 Constant *C = GetSelectFoldableConstant(TVI);
9107 Value *OOp = TVI->getOperand(2-OpToFold);
9108 // Avoid creating select between 2 constants unless it's selecting
9109 // between 0 and 1.
9110 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9111 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9112 InsertNewInstBefore(NewSel, SI);
9113 NewSel->takeName(TVI);
9114 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9115 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9116 assert(0 && "Unknown instruction!!");
9117 }
9118 }
9119 }
9120 }
9121 }
9122
9123 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9124 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9125 !isa<Constant>(TrueVal)) {
9126 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9127 unsigned OpToFold = 0;
9128 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9129 OpToFold = 1;
9130 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9131 OpToFold = 2;
9132 }
9133
9134 if (OpToFold) {
9135 Constant *C = GetSelectFoldableConstant(FVI);
9136 Value *OOp = FVI->getOperand(2-OpToFold);
9137 // Avoid creating select between 2 constants unless it's selecting
9138 // between 0 and 1.
9139 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9140 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9141 InsertNewInstBefore(NewSel, SI);
9142 NewSel->takeName(FVI);
9143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9144 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9145 assert(0 && "Unknown instruction!!");
9146 }
9147 }
9148 }
9149 }
9150 }
9151
9152 return 0;
9153}
9154
Dan Gohman81b28ce2008-09-16 18:46:06 +00009155/// visitSelectInstWithICmp - Visit a SelectInst that has an
9156/// ICmpInst as its first operand.
9157///
9158Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9159 ICmpInst *ICI) {
9160 bool Changed = false;
9161 ICmpInst::Predicate Pred = ICI->getPredicate();
9162 Value *CmpLHS = ICI->getOperand(0);
9163 Value *CmpRHS = ICI->getOperand(1);
9164 Value *TrueVal = SI.getTrueValue();
9165 Value *FalseVal = SI.getFalseValue();
9166
9167 // Check cases where the comparison is with a constant that
9168 // can be adjusted to fit the min/max idiom. We may edit ICI in
9169 // place here, so make sure the select is the only user.
9170 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009171 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009172 switch (Pred) {
9173 default: break;
9174 case ICmpInst::ICMP_ULT:
9175 case ICmpInst::ICMP_SLT: {
9176 // X < MIN ? T : F --> F
9177 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9178 return ReplaceInstUsesWith(SI, FalseVal);
9179 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9180 Constant *AdjustedRHS = SubOne(CI);
9181 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9182 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9183 Pred = ICmpInst::getSwappedPredicate(Pred);
9184 CmpRHS = AdjustedRHS;
9185 std::swap(FalseVal, TrueVal);
9186 ICI->setPredicate(Pred);
9187 ICI->setOperand(1, CmpRHS);
9188 SI.setOperand(1, TrueVal);
9189 SI.setOperand(2, FalseVal);
9190 Changed = true;
9191 }
9192 break;
9193 }
9194 case ICmpInst::ICMP_UGT:
9195 case ICmpInst::ICMP_SGT: {
9196 // X > MAX ? T : F --> F
9197 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9198 return ReplaceInstUsesWith(SI, FalseVal);
9199 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9200 Constant *AdjustedRHS = AddOne(CI);
9201 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9202 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9203 Pred = ICmpInst::getSwappedPredicate(Pred);
9204 CmpRHS = AdjustedRHS;
9205 std::swap(FalseVal, TrueVal);
9206 ICI->setPredicate(Pred);
9207 ICI->setOperand(1, CmpRHS);
9208 SI.setOperand(1, TrueVal);
9209 SI.setOperand(2, FalseVal);
9210 Changed = true;
9211 }
9212 break;
9213 }
9214 }
9215
Dan Gohman1975d032008-10-30 20:40:10 +00009216 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9217 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009218 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00009219 if (match(TrueVal, m_ConstantInt<-1>()) &&
9220 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009221 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00009222 else if (match(TrueVal, m_ConstantInt<0>()) &&
9223 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009224 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9225
Dan Gohman1975d032008-10-30 20:40:10 +00009226 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9227 // If we are just checking for a icmp eq of a single bit and zext'ing it
9228 // to an integer, then shift the bit to the appropriate place and then
9229 // cast to integer to avoid the comparison.
9230 const APInt &Op1CV = CI->getValue();
9231
9232 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9233 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9234 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009235 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009236 Value *In = ICI->getOperand(0);
9237 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009238 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009239 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9240 In->getName()+".lobit"),
9241 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009242 if (In->getType() != SI.getType())
9243 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009244 true/*SExt*/, "tmp", ICI);
9245
9246 if (Pred == ICmpInst::ICMP_SGT)
9247 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9248 In->getName()+".not"), *ICI);
9249
9250 return ReplaceInstUsesWith(SI, In);
9251 }
9252 }
9253 }
9254
Dan Gohman81b28ce2008-09-16 18:46:06 +00009255 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9256 // Transform (X == Y) ? X : Y -> Y
9257 if (Pred == ICmpInst::ICMP_EQ)
9258 return ReplaceInstUsesWith(SI, FalseVal);
9259 // Transform (X != Y) ? X : Y -> X
9260 if (Pred == ICmpInst::ICMP_NE)
9261 return ReplaceInstUsesWith(SI, TrueVal);
9262 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9263
9264 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9265 // Transform (X == Y) ? Y : X -> X
9266 if (Pred == ICmpInst::ICMP_EQ)
9267 return ReplaceInstUsesWith(SI, FalseVal);
9268 // Transform (X != Y) ? Y : X -> Y
9269 if (Pred == ICmpInst::ICMP_NE)
9270 return ReplaceInstUsesWith(SI, TrueVal);
9271 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9272 }
9273
9274 /// NOTE: if we wanted to, this is where to detect integer ABS
9275
9276 return Changed ? &SI : 0;
9277}
9278
Chris Lattner3d69f462004-03-12 05:52:32 +00009279Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009280 Value *CondVal = SI.getCondition();
9281 Value *TrueVal = SI.getTrueValue();
9282 Value *FalseVal = SI.getFalseValue();
9283
9284 // select true, X, Y -> X
9285 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009286 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009287 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009288
9289 // select C, X, X -> X
9290 if (TrueVal == FalseVal)
9291 return ReplaceInstUsesWith(SI, TrueVal);
9292
Chris Lattnere87597f2004-10-16 18:11:37 +00009293 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9294 return ReplaceInstUsesWith(SI, FalseVal);
9295 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9296 return ReplaceInstUsesWith(SI, TrueVal);
9297 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9298 if (isa<Constant>(TrueVal))
9299 return ReplaceInstUsesWith(SI, TrueVal);
9300 else
9301 return ReplaceInstUsesWith(SI, FalseVal);
9302 }
9303
Reid Spencer4fe16d62007-01-11 18:21:29 +00009304 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009305 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009306 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009307 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009308 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009309 } else {
9310 // Change: A = select B, false, C --> A = and !B, C
9311 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009312 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009313 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009314 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009315 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009316 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009317 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009318 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009319 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009320 } else {
9321 // Change: A = select B, C, true --> A = or !B, C
9322 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009323 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009324 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009325 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009326 }
9327 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009328
9329 // select a, b, a -> a&b
9330 // select a, a, b -> a|b
9331 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009332 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009333 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009334 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009335 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009336
Chris Lattner2eefe512004-04-09 19:05:30 +00009337 // Selecting between two integer constants?
9338 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9339 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009340 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009341 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009342 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009343 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009344 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009345 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009346 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009347 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009348 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009349 }
Chris Lattner457dd822004-06-09 07:59:58 +00009350
Reid Spencere4d87aa2006-12-23 06:05:41 +00009351 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009352
Reid Spencere4d87aa2006-12-23 06:05:41 +00009353 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00009354 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00009355 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00009356 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009357 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00009358 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00009359 Value *X = IC->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009360 uint32_t Bits = X->getType()->getScalarSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00009361 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009362 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009363 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009364 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009365
9366 // Then cast to the appropriate width.
9367 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009368 }
9369 }
9370
9371
9372 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009373 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009374 // non-constant value, eliminate this whole mess. This corresponds to
9375 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009376 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009377 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009378 cast<Constant>(IC->getOperand(1))->isNullValue())
9379 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9380 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009381 isa<ConstantInt>(ICA->getOperand(1)) &&
9382 (ICA->getOperand(1) == TrueValC ||
9383 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009384 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9385 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009386 // know whether we have a icmp_ne or icmp_eq and whether the
9387 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009388 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009389 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009390 Value *V = ICA;
9391 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009392 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009393 Instruction::Xor, V, ICA->getOperand(1)), SI);
9394 return ReplaceInstUsesWith(SI, V);
9395 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009396 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009397 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009398
9399 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009400 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9401 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009402 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009403 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9404 // This is not safe in general for floating point:
9405 // consider X== -0, Y== +0.
9406 // It becomes safe if either operand is a nonzero constant.
9407 ConstantFP *CFPt, *CFPf;
9408 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9409 !CFPt->getValueAPF().isZero()) ||
9410 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9411 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009412 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009413 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009414 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009415 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009416 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009417 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009418
Reid Spencere4d87aa2006-12-23 06:05:41 +00009419 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009420 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009421 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9422 // This is not safe in general for floating point:
9423 // consider X== -0, Y== +0.
9424 // It becomes safe if either operand is a nonzero constant.
9425 ConstantFP *CFPt, *CFPf;
9426 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9427 !CFPt->getValueAPF().isZero()) ||
9428 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9429 !CFPf->getValueAPF().isZero()))
9430 return ReplaceInstUsesWith(SI, FalseVal);
9431 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009432 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009433 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9434 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009435 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009436 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009437 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009438 }
9439
9440 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009441 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9442 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9443 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009444
Chris Lattner87875da2005-01-13 22:52:24 +00009445 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9446 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9447 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009448 Instruction *AddOp = 0, *SubOp = 0;
9449
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009450 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9451 if (TI->getOpcode() == FI->getOpcode())
9452 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9453 return IV;
9454
9455 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9456 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009457 if ((TI->getOpcode() == Instruction::Sub &&
9458 FI->getOpcode() == Instruction::Add) ||
9459 (TI->getOpcode() == Instruction::FSub &&
9460 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009461 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009462 } else if ((FI->getOpcode() == Instruction::Sub &&
9463 TI->getOpcode() == Instruction::Add) ||
9464 (FI->getOpcode() == Instruction::FSub &&
9465 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009466 AddOp = TI; SubOp = FI;
9467 }
9468
9469 if (AddOp) {
9470 Value *OtherAddOp = 0;
9471 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9472 OtherAddOp = AddOp->getOperand(1);
9473 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9474 OtherAddOp = AddOp->getOperand(0);
9475 }
9476
9477 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009478 // So at this point we know we have (Y -> OtherAddOp):
9479 // select C, (add X, Y), (sub X, Z)
9480 Value *NegVal; // Compute -Z
9481 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9482 NegVal = ConstantExpr::getNeg(C);
9483 } else {
9484 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009485 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009486 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009487
9488 Value *NewTrueOp = OtherAddOp;
9489 Value *NewFalseOp = NegVal;
9490 if (AddOp != TI)
9491 std::swap(NewTrueOp, NewFalseOp);
9492 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009493 SelectInst::Create(CondVal, NewTrueOp,
9494 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009495
9496 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009497 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009498 }
9499 }
9500 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009501
Chris Lattnere576b912004-04-09 23:46:01 +00009502 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009503 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009504 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9505 if (FoldI)
9506 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009507 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009508
9509 if (BinaryOperator::isNot(CondVal)) {
9510 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9511 SI.setOperand(1, FalseVal);
9512 SI.setOperand(2, TrueVal);
9513 return &SI;
9514 }
9515
Chris Lattner3d69f462004-03-12 05:52:32 +00009516 return 0;
9517}
9518
Dan Gohmaneee962e2008-04-10 18:43:06 +00009519/// EnforceKnownAlignment - If the specified pointer points to an object that
9520/// we control, modify the object's alignment to PrefAlign. This isn't
9521/// often possible though. If alignment is important, a more reliable approach
9522/// is to simply align all global variables and allocation instructions to
9523/// their preferred alignment from the beginning.
9524///
9525static unsigned EnforceKnownAlignment(Value *V,
9526 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009527
Dan Gohmaneee962e2008-04-10 18:43:06 +00009528 User *U = dyn_cast<User>(V);
9529 if (!U) return Align;
9530
9531 switch (getOpcode(U)) {
9532 default: break;
9533 case Instruction::BitCast:
9534 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9535 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009536 // If all indexes are zero, it is just the alignment of the base pointer.
9537 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009538 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009539 if (!isa<Constant>(*i) ||
9540 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009541 AllZeroOperands = false;
9542 break;
9543 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009544
9545 if (AllZeroOperands) {
9546 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009547 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009548 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009549 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009550 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009551 }
9552
9553 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9554 // If there is a large requested alignment and we can, bump up the alignment
9555 // of the global.
9556 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009557 if (GV->getAlignment() >= PrefAlign)
9558 Align = GV->getAlignment();
9559 else {
9560 GV->setAlignment(PrefAlign);
9561 Align = PrefAlign;
9562 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009563 }
9564 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9565 // If there is a requested alignment and if this is an alloca, round up. We
9566 // don't do this for malloc, because some systems can't respect the request.
9567 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009568 if (AI->getAlignment() >= PrefAlign)
9569 Align = AI->getAlignment();
9570 else {
9571 AI->setAlignment(PrefAlign);
9572 Align = PrefAlign;
9573 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009574 }
9575 }
9576
9577 return Align;
9578}
9579
9580/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9581/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9582/// and it is more than the alignment of the ultimate object, see if we can
9583/// increase the alignment of the ultimate object, making this check succeed.
9584unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9585 unsigned PrefAlign) {
9586 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9587 sizeof(PrefAlign) * CHAR_BIT;
9588 APInt Mask = APInt::getAllOnesValue(BitWidth);
9589 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9590 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9591 unsigned TrailZ = KnownZero.countTrailingOnes();
9592 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9593
9594 if (PrefAlign > Align)
9595 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9596
9597 // We don't need to make any adjustment.
9598 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009599}
9600
Chris Lattnerf497b022008-01-13 23:50:23 +00009601Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009602 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009603 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009604 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009605 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009606
9607 if (CopyAlign < MinAlign) {
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009608 MI->setAlignment(MinAlign);
Chris Lattnerf497b022008-01-13 23:50:23 +00009609 return MI;
9610 }
9611
9612 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9613 // load/store.
9614 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9615 if (MemOpLength == 0) return 0;
9616
Chris Lattner37ac6082008-01-14 00:28:35 +00009617 // Source and destination pointer types are always "i8*" for intrinsic. See
9618 // if the size is something we can handle with a single primitive load/store.
9619 // A single load+store correctly handles overlapping memory in the memmove
9620 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009621 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009622 if (Size == 0) return MI; // Delete this mem transfer.
9623
9624 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009625 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009626
Chris Lattner37ac6082008-01-14 00:28:35 +00009627 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009628 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009629
9630 // Memcpy forces the use of i8* for the source and destination. That means
9631 // that if you're using memcpy to move one double around, you'll get a cast
9632 // from double* to i8*. We'd much rather use a double load+store rather than
9633 // an i64 load+store, here because this improves the odds that the source or
9634 // dest address will be promotable. See if we can find a better type than the
9635 // integer datatype.
9636 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9637 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9638 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9639 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9640 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009641 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009642 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9643 if (STy->getNumElements() == 1)
9644 SrcETy = STy->getElementType(0);
9645 else
9646 break;
9647 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9648 if (ATy->getNumElements() == 1)
9649 SrcETy = ATy->getElementType();
9650 else
9651 break;
9652 } else
9653 break;
9654 }
9655
Dan Gohman8f8e2692008-05-23 01:52:21 +00009656 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009657 NewPtrTy = PointerType::getUnqual(SrcETy);
9658 }
9659 }
9660
9661
Chris Lattnerf497b022008-01-13 23:50:23 +00009662 // If the memcpy/memmove provides better alignment info than we can
9663 // infer, use it.
9664 SrcAlign = std::max(SrcAlign, CopyAlign);
9665 DstAlign = std::max(DstAlign, CopyAlign);
9666
9667 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9668 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009669 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9670 InsertNewInstBefore(L, *MI);
9671 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9672
9673 // Set the size of the copy to 0, it will be deleted on the next iteration.
9674 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9675 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009676}
Chris Lattner3d69f462004-03-12 05:52:32 +00009677
Chris Lattner69ea9d22008-04-30 06:39:11 +00009678Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9679 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009680 if (MI->getAlignment() < Alignment) {
9681 MI->setAlignment(Alignment);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009682 return MI;
9683 }
9684
9685 // Extract the length and alignment and fill if they are constant.
9686 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9687 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9688 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9689 return 0;
9690 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009691 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009692
9693 // If the length is zero, this is a no-op
9694 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9695
9696 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9697 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9698 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9699
9700 Value *Dest = MI->getDest();
9701 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9702
9703 // Alignment 0 is identity for alignment 1 for memset, but not store.
9704 if (Alignment == 0) Alignment = 1;
9705
9706 // Extract the fill value and store.
9707 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9708 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9709 Alignment), *MI);
9710
9711 // Set the size of the copy to 0, it will be deleted on the next iteration.
9712 MI->setLength(Constant::getNullValue(LenC->getType()));
9713 return MI;
9714 }
9715
9716 return 0;
9717}
9718
9719
Chris Lattner8b0ea312006-01-13 20:11:04 +00009720/// visitCallInst - CallInst simplification. This mostly only handles folding
9721/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9722/// the heavy lifting.
9723///
Chris Lattner9fe38862003-06-19 17:00:31 +00009724Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009725 // If the caller function is nounwind, mark the call as nounwind, even if the
9726 // callee isn't.
9727 if (CI.getParent()->getParent()->doesNotThrow() &&
9728 !CI.doesNotThrow()) {
9729 CI.setDoesNotThrow();
9730 return &CI;
9731 }
9732
9733
9734
Chris Lattner8b0ea312006-01-13 20:11:04 +00009735 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9736 if (!II) return visitCallSite(&CI);
9737
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009738 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9739 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009740 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009741 bool Changed = false;
9742
9743 // memmove/cpy/set of zero bytes is a noop.
9744 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9745 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9746
Chris Lattner35b9e482004-10-12 04:52:52 +00009747 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009748 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009749 // Replace the instruction with just byte operations. We would
9750 // transform other cases to loads/stores, but we don't know if
9751 // alignment is sufficient.
9752 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009753 }
9754
Chris Lattner35b9e482004-10-12 04:52:52 +00009755 // If we have a memmove and the source operation is a constant global,
9756 // then the source and dest pointers can't alias, so we can change this
9757 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009758 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009759 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9760 if (GVSrc->isConstant()) {
9761 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009762 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9763 const Type *Tys[1];
9764 Tys[0] = CI.getOperand(3)->getType();
9765 CI.setOperand(0,
9766 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009767 Changed = true;
9768 }
Chris Lattnera935db82008-05-28 05:30:41 +00009769
9770 // memmove(x,x,size) -> noop.
9771 if (MMI->getSource() == MMI->getDest())
9772 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009773 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009774
Chris Lattner95a959d2006-03-06 20:18:44 +00009775 // If we can determine a pointer alignment that is bigger than currently
9776 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009777 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009778 if (Instruction *I = SimplifyMemTransfer(MI))
9779 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009780 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9781 if (Instruction *I = SimplifyMemSet(MSI))
9782 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009783 }
9784
Chris Lattner8b0ea312006-01-13 20:11:04 +00009785 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009786 }
9787
9788 switch (II->getIntrinsicID()) {
9789 default: break;
9790 case Intrinsic::bswap:
9791 // bswap(bswap(x)) -> x
9792 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9793 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9794 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9795 break;
9796 case Intrinsic::ppc_altivec_lvx:
9797 case Intrinsic::ppc_altivec_lvxl:
9798 case Intrinsic::x86_sse_loadu_ps:
9799 case Intrinsic::x86_sse2_loadu_pd:
9800 case Intrinsic::x86_sse2_loadu_dq:
9801 // Turn PPC lvx -> load if the pointer is known aligned.
9802 // Turn X86 loadups -> load if the pointer is known aligned.
9803 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9804 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9805 PointerType::getUnqual(II->getType()),
9806 CI);
9807 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009808 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009809 break;
9810 case Intrinsic::ppc_altivec_stvx:
9811 case Intrinsic::ppc_altivec_stvxl:
9812 // Turn stvx -> store if the pointer is known aligned.
9813 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9814 const Type *OpPtrTy =
9815 PointerType::getUnqual(II->getOperand(1)->getType());
9816 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9817 return new StoreInst(II->getOperand(1), Ptr);
9818 }
9819 break;
9820 case Intrinsic::x86_sse_storeu_ps:
9821 case Intrinsic::x86_sse2_storeu_pd:
9822 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009823 // Turn X86 storeu -> store if the pointer is known aligned.
9824 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9825 const Type *OpPtrTy =
9826 PointerType::getUnqual(II->getOperand(2)->getType());
9827 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9828 return new StoreInst(II->getOperand(2), Ptr);
9829 }
9830 break;
9831
9832 case Intrinsic::x86_sse_cvttss2si: {
9833 // These intrinsics only demands the 0th element of its input vector. If
9834 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009835 unsigned VWidth =
9836 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9837 APInt DemandedElts(VWidth, 1);
9838 APInt UndefElts(VWidth, 0);
9839 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009840 UndefElts)) {
9841 II->setOperand(1, V);
9842 return II;
9843 }
9844 break;
9845 }
9846
9847 case Intrinsic::ppc_altivec_vperm:
9848 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9849 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9850 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009851
Chris Lattner0521e3c2008-06-18 04:33:20 +00009852 // Check that all of the elements are integer constants or undefs.
9853 bool AllEltsOk = true;
9854 for (unsigned i = 0; i != 16; ++i) {
9855 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9856 !isa<UndefValue>(Mask->getOperand(i))) {
9857 AllEltsOk = false;
9858 break;
9859 }
9860 }
9861
9862 if (AllEltsOk) {
9863 // Cast the input vectors to byte vectors.
9864 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9865 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9866 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009867
Chris Lattner0521e3c2008-06-18 04:33:20 +00009868 // Only extract each element once.
9869 Value *ExtractedElts[32];
9870 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9871
Chris Lattnere2ed0572006-04-06 19:19:17 +00009872 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009873 if (isa<UndefValue>(Mask->getOperand(i)))
9874 continue;
9875 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9876 Idx &= 31; // Match the hardware behavior.
9877
9878 if (ExtractedElts[Idx] == 0) {
9879 Instruction *Elt =
9880 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9881 InsertNewInstBefore(Elt, CI);
9882 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009883 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009884
Chris Lattner0521e3c2008-06-18 04:33:20 +00009885 // Insert this value into the result vector.
9886 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9887 i, "tmp");
9888 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009889 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009890 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009891 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009892 }
9893 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009894
Chris Lattner0521e3c2008-06-18 04:33:20 +00009895 case Intrinsic::stackrestore: {
9896 // If the save is right next to the restore, remove the restore. This can
9897 // happen when variable allocas are DCE'd.
9898 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9899 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9900 BasicBlock::iterator BI = SS;
9901 if (&*++BI == II)
9902 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009903 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009904 }
9905
9906 // Scan down this block to see if there is another stack restore in the
9907 // same block without an intervening call/alloca.
9908 BasicBlock::iterator BI = II;
9909 TerminatorInst *TI = II->getParent()->getTerminator();
9910 bool CannotRemove = false;
9911 for (++BI; &*BI != TI; ++BI) {
9912 if (isa<AllocaInst>(BI)) {
9913 CannotRemove = true;
9914 break;
9915 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009916 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9917 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9918 // If there is a stackrestore below this one, remove this one.
9919 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9920 return EraseInstFromFunction(CI);
9921 // Otherwise, ignore the intrinsic.
9922 } else {
9923 // If we found a non-intrinsic call, we can't remove the stack
9924 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009925 CannotRemove = true;
9926 break;
9927 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009928 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009929 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009930
9931 // If the stack restore is in a return/unwind block and if there are no
9932 // allocas or calls between the restore and the return, nuke the restore.
9933 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9934 return EraseInstFromFunction(CI);
9935 break;
9936 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009937 }
9938
Chris Lattner8b0ea312006-01-13 20:11:04 +00009939 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009940}
9941
9942// InvokeInst simplification
9943//
9944Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009945 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009946}
9947
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009948/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9949/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009950static bool isSafeToEliminateVarargsCast(const CallSite CS,
9951 const CastInst * const CI,
9952 const TargetData * const TD,
9953 const int ix) {
9954 if (!CI->isLosslessCast())
9955 return false;
9956
9957 // The size of ByVal arguments is derived from the type, so we
9958 // can't change to a type with a different size. If the size were
9959 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009960 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009961 return true;
9962
9963 const Type* SrcTy =
9964 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9965 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9966 if (!SrcTy->isSized() || !DstTy->isSized())
9967 return false;
Duncan Sands777d2302009-05-09 07:06:46 +00009968 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009969 return false;
9970 return true;
9971}
9972
Chris Lattnera44d8a22003-10-07 22:32:43 +00009973// visitCallSite - Improvements for call and invoke instructions.
9974//
9975Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009976 bool Changed = false;
9977
9978 // If the callee is a constexpr cast of a function, attempt to move the cast
9979 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009980 if (transformConstExprCastCall(CS)) return 0;
9981
Chris Lattner6c266db2003-10-07 22:54:13 +00009982 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009983
Chris Lattner08b22ec2005-05-13 07:09:09 +00009984 if (Function *CalleeF = dyn_cast<Function>(Callee))
9985 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9986 Instruction *OldCall = CS.getInstruction();
9987 // If the call and callee calling conventions don't match, this call must
9988 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009989 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009990 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9991 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009992 if (!OldCall->use_empty())
9993 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9994 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9995 return EraseInstFromFunction(*OldCall);
9996 return 0;
9997 }
9998
Chris Lattner17be6352004-10-18 02:59:09 +00009999 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10000 // This instruction is not reachable, just remove it. We insert a store to
10001 // undef so that we know that this code is not reachable, despite the fact
10002 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010003 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010004 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +000010005 CS.getInstruction());
10006
10007 if (!CS.getInstruction()->use_empty())
10008 CS.getInstruction()->
10009 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10010
10011 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10012 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010013 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10014 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010015 }
Chris Lattner17be6352004-10-18 02:59:09 +000010016 return EraseInstFromFunction(*CS.getInstruction());
10017 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010018
Duncan Sandscdb6d922007-09-17 10:26:40 +000010019 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10020 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10021 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10022 return transformCallThroughTrampoline(CS);
10023
Chris Lattner6c266db2003-10-07 22:54:13 +000010024 const PointerType *PTy = cast<PointerType>(Callee->getType());
10025 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10026 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010027 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010028 // See if we can optimize any arguments passed through the varargs area of
10029 // the call.
10030 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010031 E = CS.arg_end(); I != E; ++I, ++ix) {
10032 CastInst *CI = dyn_cast<CastInst>(*I);
10033 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10034 *I = CI->getOperand(0);
10035 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010036 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010037 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010038 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010039
Duncan Sandsf0c33542007-12-19 21:13:37 +000010040 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010041 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010042 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010043 Changed = true;
10044 }
10045
Chris Lattner6c266db2003-10-07 22:54:13 +000010046 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010047}
10048
Chris Lattner9fe38862003-06-19 17:00:31 +000010049// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10050// attempt to move the cast to the arguments of the call/invoke.
10051//
10052bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10053 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10054 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010055 if (CE->getOpcode() != Instruction::BitCast ||
10056 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010057 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010058 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010059 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010060 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010061
10062 // Okay, this is a cast from a function to a different type. Unless doing so
10063 // would cause a type conversion of one of our arguments, change this call to
10064 // be a direct call with arguments casted to the appropriate types.
10065 //
10066 const FunctionType *FT = Callee->getFunctionType();
10067 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010068 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010069
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010070 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010071 return false; // TODO: Handle multiple return values.
10072
Chris Lattnerf78616b2004-01-14 06:06:08 +000010073 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010074 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010075 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010076 // Conversion is ok if changing from one pointer type to another or from
10077 // a pointer to an integer of the same size.
10078 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +000010079 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +000010080 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010081
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010082 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010083 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010084 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010085 return false; // Cannot transform this return value.
10086
Chris Lattner58d74912008-03-12 17:45:29 +000010087 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010088 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010089 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010090 return false; // Attribute not compatible with transformed value.
10091 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010092
Chris Lattnerf78616b2004-01-14 06:06:08 +000010093 // If the callsite is an invoke instruction, and the return value is used by
10094 // a PHI node in a successor, we cannot change the return type of the call
10095 // because there is no place to put the cast instruction (without breaking
10096 // the critical edge). Bail out in this case.
10097 if (!Caller->use_empty())
10098 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10099 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10100 UI != E; ++UI)
10101 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10102 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010103 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010104 return false;
10105 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010106
10107 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10108 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010109
Chris Lattner9fe38862003-06-19 17:00:31 +000010110 CallSite::arg_iterator AI = CS.arg_begin();
10111 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10112 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010113 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010114
10115 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010116 return false; // Cannot transform this parameter value.
10117
Devang Patel19c87462008-09-26 22:53:05 +000010118 if (CallerPAL.getParamAttributes(i + 1)
10119 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010120 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010121
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010122 // Converting from one pointer type to another or between a pointer and an
10123 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010124 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010125 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10126 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010127 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010128 }
10129
10130 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010131 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010132 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010133
Chris Lattner58d74912008-03-12 17:45:29 +000010134 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10135 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010136 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010137 // won't be dropping them. Check that these extra arguments have attributes
10138 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010139 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10140 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010141 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010142 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010143 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010144 return false;
10145 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010146
Chris Lattner9fe38862003-06-19 17:00:31 +000010147 // Okay, we decided that this is a safe thing to do: go ahead and start
10148 // inserting cast instructions as necessary...
10149 std::vector<Value*> Args;
10150 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010151 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010152 attrVec.reserve(NumCommonArgs);
10153
10154 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010155 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010156
10157 // If the return value is not being used, the type may not be compatible
10158 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010159 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010160
10161 // Add the new return attributes.
10162 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010163 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010164
10165 AI = CS.arg_begin();
10166 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10167 const Type *ParamTy = FT->getParamType(i);
10168 if ((*AI)->getType() == ParamTy) {
10169 Args.push_back(*AI);
10170 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010171 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010172 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010173 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010174 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010175 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010176
10177 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010178 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010179 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010180 }
10181
10182 // If the function takes more arguments than the call was taking, add them
10183 // now...
10184 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10185 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10186
10187 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010188 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010189 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +000010190 cerr << "WARNING: While resolving call to function '"
10191 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010192 } else {
10193 // Add all of the arguments in their promoted form to the arg list...
10194 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10195 const Type *PTy = getPromotedType((*AI)->getType());
10196 if (PTy != (*AI)->getType()) {
10197 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010198 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10199 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010200 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010201 InsertNewInstBefore(Cast, *Caller);
10202 Args.push_back(Cast);
10203 } else {
10204 Args.push_back(*AI);
10205 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010206
Duncan Sandse1e520f2008-01-13 08:02:44 +000010207 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010208 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010209 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010210 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010211 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010212 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010213
Devang Patel19c87462008-09-26 22:53:05 +000010214 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10215 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10216
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010217 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +000010218 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010219
Devang Patel05988662008-09-25 21:00:45 +000010220 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010221
Chris Lattner9fe38862003-06-19 17:00:31 +000010222 Instruction *NC;
10223 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010224 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010225 Args.begin(), Args.end(),
10226 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010227 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010228 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010229 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010230 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10231 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010232 CallInst *CI = cast<CallInst>(Caller);
10233 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010234 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010235 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010236 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010237 }
10238
Chris Lattner6934a042007-02-11 01:23:03 +000010239 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010240 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010241 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010242 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010243 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010244 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010245 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010246
10247 // If this is an invoke instruction, we should insert it after the first
10248 // non-phi, instruction in the normal successor block.
10249 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010250 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010251 InsertNewInstBefore(NC, *I);
10252 } else {
10253 // Otherwise, it's a call, just insert cast right after the call instr
10254 InsertNewInstBefore(NC, *Caller);
10255 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010256 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010257 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +000010258 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010259 }
10260 }
10261
10262 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10263 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010264 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010265 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010266 return true;
10267}
10268
Duncan Sandscdb6d922007-09-17 10:26:40 +000010269// transformCallThroughTrampoline - Turn a call to a function created by the
10270// init_trampoline intrinsic into a direct call to the underlying function.
10271//
10272Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10273 Value *Callee = CS.getCalledValue();
10274 const PointerType *PTy = cast<PointerType>(Callee->getType());
10275 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010276 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010277
10278 // If the call already has the 'nest' attribute somewhere then give up -
10279 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010280 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010281 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010282
10283 IntrinsicInst *Tramp =
10284 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10285
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010286 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010287 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10288 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10289
Devang Patel05988662008-09-25 21:00:45 +000010290 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010291 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010292 unsigned NestIdx = 1;
10293 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010294 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010295
10296 // Look for a parameter marked with the 'nest' attribute.
10297 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10298 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010299 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010300 // Record the parameter type and any other attributes.
10301 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010302 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010303 break;
10304 }
10305
10306 if (NestTy) {
10307 Instruction *Caller = CS.getInstruction();
10308 std::vector<Value*> NewArgs;
10309 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10310
Devang Patel05988662008-09-25 21:00:45 +000010311 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010312 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010313
Duncan Sandscdb6d922007-09-17 10:26:40 +000010314 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010315 // mean appending it. Likewise for attributes.
10316
Devang Patel19c87462008-09-26 22:53:05 +000010317 // Add any result attributes.
10318 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010319 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010320
Duncan Sandscdb6d922007-09-17 10:26:40 +000010321 {
10322 unsigned Idx = 1;
10323 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10324 do {
10325 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010326 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010327 Value *NestVal = Tramp->getOperand(3);
10328 if (NestVal->getType() != NestTy)
10329 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10330 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010331 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010332 }
10333
10334 if (I == E)
10335 break;
10336
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010337 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010338 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010339 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010340 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010341 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010342
10343 ++Idx, ++I;
10344 } while (1);
10345 }
10346
Devang Patel19c87462008-09-26 22:53:05 +000010347 // Add any function attributes.
10348 if (Attributes Attr = Attrs.getFnAttributes())
10349 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10350
Duncan Sandscdb6d922007-09-17 10:26:40 +000010351 // The trampoline may have been bitcast to a bogus type (FTy).
10352 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010353 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010354
Duncan Sandscdb6d922007-09-17 10:26:40 +000010355 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010356 NewTypes.reserve(FTy->getNumParams()+1);
10357
Duncan Sandscdb6d922007-09-17 10:26:40 +000010358 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010359 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010360 {
10361 unsigned Idx = 1;
10362 FunctionType::param_iterator I = FTy->param_begin(),
10363 E = FTy->param_end();
10364
10365 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010366 if (Idx == NestIdx)
10367 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010368 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369
10370 if (I == E)
10371 break;
10372
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010373 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010374 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010375
10376 ++Idx, ++I;
10377 } while (1);
10378 }
10379
10380 // Replace the trampoline call with a direct call. Let the generic
10381 // code sort out any function type mismatches.
10382 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010383 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010384 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10385 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010386 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387
10388 Instruction *NewCaller;
10389 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010390 NewCaller = InvokeInst::Create(NewCallee,
10391 II->getNormalDest(), II->getUnwindDest(),
10392 NewArgs.begin(), NewArgs.end(),
10393 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010394 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010395 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010396 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010397 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10398 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399 if (cast<CallInst>(Caller)->isTailCall())
10400 cast<CallInst>(NewCaller)->setTailCall();
10401 cast<CallInst>(NewCaller)->
10402 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010403 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010404 }
10405 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10406 Caller->replaceAllUsesWith(NewCaller);
10407 Caller->eraseFromParent();
10408 RemoveFromWorkList(Caller);
10409 return 0;
10410 }
10411 }
10412
10413 // Replace the trampoline call with a direct call. Since there is no 'nest'
10414 // parameter, there is no need to adjust the argument list. Let the generic
10415 // code sort out any function type mismatches.
10416 Constant *NewCallee =
10417 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10418 CS.setCalledFunction(NewCallee);
10419 return CS.getInstruction();
10420}
10421
Chris Lattner7da52b22006-11-01 04:51:18 +000010422/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10423/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10424/// and a single binop.
10425Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10426 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010427 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010428 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010429 Value *LHSVal = FirstInst->getOperand(0);
10430 Value *RHSVal = FirstInst->getOperand(1);
10431
10432 const Type *LHSType = LHSVal->getType();
10433 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010434
10435 // Scan to see if all operands are the same opcode, all have one use, and all
10436 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010437 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010438 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010439 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010440 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010441 // types or GEP's with different index types.
10442 I->getOperand(0)->getType() != LHSType ||
10443 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010444 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010445
10446 // If they are CmpInst instructions, check their predicates
10447 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10448 if (cast<CmpInst>(I)->getPredicate() !=
10449 cast<CmpInst>(FirstInst)->getPredicate())
10450 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010451
10452 // Keep track of which operand needs a phi node.
10453 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10454 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010455 }
10456
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010457 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010458
Chris Lattner7da52b22006-11-01 04:51:18 +000010459 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010460 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010461 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010462 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010463 NewLHS = PHINode::Create(LHSType,
10464 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010465 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10466 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010467 InsertNewInstBefore(NewLHS, PN);
10468 LHSVal = NewLHS;
10469 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010470
10471 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010472 NewRHS = PHINode::Create(RHSType,
10473 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010474 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10475 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010476 InsertNewInstBefore(NewRHS, PN);
10477 RHSVal = NewRHS;
10478 }
10479
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010480 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010481 if (NewLHS || NewRHS) {
10482 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10483 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10484 if (NewLHS) {
10485 Value *NewInLHS = InInst->getOperand(0);
10486 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10487 }
10488 if (NewRHS) {
10489 Value *NewInRHS = InInst->getOperand(1);
10490 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10491 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010492 }
10493 }
10494
Chris Lattner7da52b22006-11-01 04:51:18 +000010495 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010496 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010497 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10498 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10499 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010500}
10501
Chris Lattner05f18922008-12-01 02:34:36 +000010502Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10503 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10504
10505 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10506 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010507 // This is true if all GEP bases are allocas and if all indices into them are
10508 // constants.
10509 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010510
10511 // Scan to see if all operands are the same opcode, all have one use, and all
10512 // kill their operands (i.e. the operands have one use).
10513 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10514 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10515 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10516 GEP->getNumOperands() != FirstInst->getNumOperands())
10517 return 0;
10518
Chris Lattner36d3e322009-02-21 00:46:50 +000010519 // Keep track of whether or not all GEPs are of alloca pointers.
10520 if (AllBasePointersAreAllocas &&
10521 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10522 !GEP->hasAllConstantIndices()))
10523 AllBasePointersAreAllocas = false;
10524
Chris Lattner05f18922008-12-01 02:34:36 +000010525 // Compare the operand lists.
10526 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10527 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10528 continue;
10529
10530 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10531 // if one of the PHIs has a constant for the index. The index may be
10532 // substantially cheaper to compute for the constants, so making it a
10533 // variable index could pessimize the path. This also handles the case
10534 // for struct indices, which must always be constant.
10535 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10536 isa<ConstantInt>(GEP->getOperand(op)))
10537 return 0;
10538
10539 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10540 return 0;
10541 FixedOperands[op] = 0; // Needs a PHI.
10542 }
10543 }
10544
Chris Lattner36d3e322009-02-21 00:46:50 +000010545 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010546 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010547 // offset calculation, but all the predecessors will have to materialize the
10548 // stack address into a register anyway. We'd actually rather *clone* the
10549 // load up into the predecessors so that we have a load of a gep of an alloca,
10550 // which can usually all be folded into the load.
10551 if (AllBasePointersAreAllocas)
10552 return 0;
10553
Chris Lattner05f18922008-12-01 02:34:36 +000010554 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10555 // that is variable.
10556 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10557
10558 bool HasAnyPHIs = false;
10559 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10560 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10561 Value *FirstOp = FirstInst->getOperand(i);
10562 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10563 FirstOp->getName()+".pn");
10564 InsertNewInstBefore(NewPN, PN);
10565
10566 NewPN->reserveOperandSpace(e);
10567 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10568 OperandPhis[i] = NewPN;
10569 FixedOperands[i] = NewPN;
10570 HasAnyPHIs = true;
10571 }
10572
10573
10574 // Add all operands to the new PHIs.
10575 if (HasAnyPHIs) {
10576 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10577 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10578 BasicBlock *InBB = PN.getIncomingBlock(i);
10579
10580 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10581 if (PHINode *OpPhi = OperandPhis[op])
10582 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10583 }
10584 }
10585
10586 Value *Base = FixedOperands[0];
10587 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10588 FixedOperands.end());
10589}
10590
10591
Chris Lattner21550882009-02-23 05:56:17 +000010592/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10593/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010594/// obvious the value of the load is not changed from the point of the load to
10595/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010596///
10597/// Finally, it is safe, but not profitable, to sink a load targetting a
10598/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10599/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010600static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010601 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10602
10603 for (++BBI; BBI != E; ++BBI)
10604 if (BBI->mayWriteToMemory())
10605 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010606
10607 // Check for non-address taken alloca. If not address-taken already, it isn't
10608 // profitable to do this xform.
10609 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10610 bool isAddressTaken = false;
10611 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10612 UI != E; ++UI) {
10613 if (isa<LoadInst>(UI)) continue;
10614 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10615 // If storing TO the alloca, then the address isn't taken.
10616 if (SI->getOperand(1) == AI) continue;
10617 }
10618 isAddressTaken = true;
10619 break;
10620 }
10621
Chris Lattner36d3e322009-02-21 00:46:50 +000010622 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010623 return false;
10624 }
10625
Chris Lattner36d3e322009-02-21 00:46:50 +000010626 // If this load is a load from a GEP with a constant offset from an alloca,
10627 // then we don't want to sink it. In its present form, it will be
10628 // load [constant stack offset]. Sinking it will cause us to have to
10629 // materialize the stack addresses in each predecessor in a register only to
10630 // do a shared load from register in the successor.
10631 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10632 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10633 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10634 return false;
10635
Chris Lattner76c73142006-11-01 07:13:54 +000010636 return true;
10637}
10638
Chris Lattner9fe38862003-06-19 17:00:31 +000010639
Chris Lattnerbac32862004-11-14 19:13:23 +000010640// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10641// operator and they all are only used by the PHI, PHI together their
10642// inputs, and do the operation once, to the result of the PHI.
10643Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10644 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10645
10646 // Scan the instruction, looking for input operations that can be folded away.
10647 // If all input operands to the phi are the same instruction (e.g. a cast from
10648 // the same type or "+42") we can pull the operation through the PHI, reducing
10649 // code size and simplifying code.
10650 Constant *ConstantOp = 0;
10651 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010652 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010653 if (isa<CastInst>(FirstInst)) {
10654 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010655 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010656 // Can fold binop, compare or shift here if the RHS is a constant,
10657 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010658 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010659 if (ConstantOp == 0)
10660 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010661 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10662 isVolatile = LI->isVolatile();
10663 // We can't sink the load if the loaded value could be modified between the
10664 // load and the PHI.
10665 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010666 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010667 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010668
10669 // If the PHI is of volatile loads and the load block has multiple
10670 // successors, sinking it would remove a load of the volatile value from
10671 // the path through the other successor.
10672 if (isVolatile &&
10673 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10674 return 0;
10675
Chris Lattner9c080502006-11-01 07:43:41 +000010676 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010677 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010678 } else {
10679 return 0; // Cannot fold this operation.
10680 }
10681
10682 // Check to see if all arguments are the same operation.
10683 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10684 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10685 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010686 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010687 return 0;
10688 if (CastSrcTy) {
10689 if (I->getOperand(0)->getType() != CastSrcTy)
10690 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010691 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010692 // We can't sink the load if the loaded value could be modified between
10693 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010694 if (LI->isVolatile() != isVolatile ||
10695 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010696 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010697 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010698
Chris Lattner71042962008-07-08 17:18:32 +000010699 // If the PHI is of volatile loads and the load block has multiple
10700 // successors, sinking it would remove a load of the volatile value from
10701 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010702 if (isVolatile &&
10703 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10704 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010705
Chris Lattnerbac32862004-11-14 19:13:23 +000010706 } else if (I->getOperand(1) != ConstantOp) {
10707 return 0;
10708 }
10709 }
10710
10711 // Okay, they are all the same operation. Create a new PHI node of the
10712 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010713 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10714 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010715 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010716
10717 Value *InVal = FirstInst->getOperand(0);
10718 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010719
10720 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010721 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10722 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10723 if (NewInVal != InVal)
10724 InVal = 0;
10725 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10726 }
10727
10728 Value *PhiVal;
10729 if (InVal) {
10730 // The new PHI unions all of the same values together. This is really
10731 // common, so we handle it intelligently here for compile-time speed.
10732 PhiVal = InVal;
10733 delete NewPN;
10734 } else {
10735 InsertNewInstBefore(NewPN, PN);
10736 PhiVal = NewPN;
10737 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010738
Chris Lattnerbac32862004-11-14 19:13:23 +000010739 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010740 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010741 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010742 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010743 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010744 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010745 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010746 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010747 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10748
10749 // If this was a volatile load that we are merging, make sure to loop through
10750 // and mark all the input loads as non-volatile. If we don't do this, we will
10751 // insert a new volatile load and the old ones will not be deletable.
10752 if (isVolatile)
10753 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10754 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10755
10756 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010757}
Chris Lattnera1be5662002-05-02 17:06:02 +000010758
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010759/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10760/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010761static bool DeadPHICycle(PHINode *PN,
10762 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010763 if (PN->use_empty()) return true;
10764 if (!PN->hasOneUse()) return false;
10765
10766 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010767 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010768 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010769
10770 // Don't scan crazily complex things.
10771 if (PotentiallyDeadPHIs.size() == 16)
10772 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010773
10774 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10775 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010776
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010777 return false;
10778}
10779
Chris Lattnercf5008a2007-11-06 21:52:06 +000010780/// PHIsEqualValue - Return true if this phi node is always equal to
10781/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10782/// z = some value; x = phi (y, z); y = phi (x, z)
10783static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10784 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10785 // See if we already saw this PHI node.
10786 if (!ValueEqualPHIs.insert(PN))
10787 return true;
10788
10789 // Don't scan crazily complex things.
10790 if (ValueEqualPHIs.size() == 16)
10791 return false;
10792
10793 // Scan the operands to see if they are either phi nodes or are equal to
10794 // the value.
10795 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10796 Value *Op = PN->getIncomingValue(i);
10797 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10798 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10799 return false;
10800 } else if (Op != NonPhiInVal)
10801 return false;
10802 }
10803
10804 return true;
10805}
10806
10807
Chris Lattner473945d2002-05-06 18:06:38 +000010808// PHINode simplification
10809//
Chris Lattner7e708292002-06-25 16:13:24 +000010810Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010811 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010812 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010813
Owen Anderson7e057142006-07-10 22:03:18 +000010814 if (Value *V = PN.hasConstantValue())
10815 return ReplaceInstUsesWith(PN, V);
10816
Owen Anderson7e057142006-07-10 22:03:18 +000010817 // If all PHI operands are the same operation, pull them through the PHI,
10818 // reducing code size.
10819 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010820 isa<Instruction>(PN.getIncomingValue(1)) &&
10821 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10822 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10823 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10824 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010825 PN.getIncomingValue(0)->hasOneUse())
10826 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10827 return Result;
10828
10829 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10830 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10831 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010832 if (PN.hasOneUse()) {
10833 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10834 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010835 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010836 PotentiallyDeadPHIs.insert(&PN);
10837 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10838 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10839 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010840
10841 // If this phi has a single use, and if that use just computes a value for
10842 // the next iteration of a loop, delete the phi. This occurs with unused
10843 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10844 // common case here is good because the only other things that catch this
10845 // are induction variable analysis (sometimes) and ADCE, which is only run
10846 // late.
10847 if (PHIUser->hasOneUse() &&
10848 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10849 PHIUser->use_back() == &PN) {
10850 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10851 }
10852 }
Owen Anderson7e057142006-07-10 22:03:18 +000010853
Chris Lattnercf5008a2007-11-06 21:52:06 +000010854 // We sometimes end up with phi cycles that non-obviously end up being the
10855 // same value, for example:
10856 // z = some value; x = phi (y, z); y = phi (x, z)
10857 // where the phi nodes don't necessarily need to be in the same block. Do a
10858 // quick check to see if the PHI node only contains a single non-phi value, if
10859 // so, scan to see if the phi cycle is actually equal to that value.
10860 {
10861 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10862 // Scan for the first non-phi operand.
10863 while (InValNo != NumOperandVals &&
10864 isa<PHINode>(PN.getIncomingValue(InValNo)))
10865 ++InValNo;
10866
10867 if (InValNo != NumOperandVals) {
10868 Value *NonPhiInVal = PN.getOperand(InValNo);
10869
10870 // Scan the rest of the operands to see if there are any conflicts, if so
10871 // there is no need to recursively scan other phis.
10872 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10873 Value *OpVal = PN.getIncomingValue(InValNo);
10874 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10875 break;
10876 }
10877
10878 // If we scanned over all operands, then we have one unique value plus
10879 // phi values. Scan PHI nodes to see if they all merge in each other or
10880 // the value.
10881 if (InValNo == NumOperandVals) {
10882 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10883 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10884 return ReplaceInstUsesWith(PN, NonPhiInVal);
10885 }
10886 }
10887 }
Chris Lattner60921c92003-12-19 05:58:40 +000010888 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010889}
10890
Reid Spencer17212df2006-12-12 09:18:51 +000010891static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10892 Instruction *InsertPoint,
10893 InstCombiner *IC) {
Dan Gohman6de29f82009-06-15 22:12:54 +000010894 unsigned PtrSize = DTy->getScalarSizeInBits();
10895 unsigned VTySize = V->getType()->getScalarSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010896 // We must cast correctly to the pointer type. Ensure that we
10897 // sign extend the integer value if it is smaller as this is
10898 // used for address computation.
10899 Instruction::CastOps opcode =
10900 (VTySize < PtrSize ? Instruction::SExt :
10901 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10902 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010903}
10904
Chris Lattnera1be5662002-05-02 17:06:02 +000010905
Chris Lattner7e708292002-06-25 16:13:24 +000010906Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010907 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010908 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010909 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010910 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010911 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010912
Chris Lattnere87597f2004-10-16 18:11:37 +000010913 if (isa<UndefValue>(GEP.getOperand(0)))
10914 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10915
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010916 bool HasZeroPointerIndex = false;
10917 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10918 HasZeroPointerIndex = C->isNullValue();
10919
10920 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010921 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010922
Chris Lattner28977af2004-04-05 01:30:19 +000010923 // Eliminate unneeded casts for indices.
10924 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010925
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010926 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010927 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10928 i != e; ++i, ++GTI) {
Sanjiv Gupta7787d4a2009-04-24 02:37:54 +000010929 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010930 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010931 if (CI->getOpcode() == Instruction::ZExt ||
10932 CI->getOpcode() == Instruction::SExt) {
10933 const Type *SrcTy = CI->getOperand(0)->getType();
10934 // We can eliminate a cast from i32 to i64 iff the target
10935 // is a 32-bit pointer target.
Dan Gohman6de29f82009-06-15 22:12:54 +000010936 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010937 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010938 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010939 }
10940 }
10941 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010942 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010943 // to what we need. If narrower, sign-extend it to what we need.
10944 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010945 // insert it. This explicit cast can make subsequent optimizations more
10946 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010947 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010948 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010949 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010950 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010951 MadeChange = true;
10952 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010953 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10954 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010955 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010956 MadeChange = true;
10957 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010958 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10959 if (Constant *C = dyn_cast<Constant>(Op)) {
10960 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10961 MadeChange = true;
10962 } else {
10963 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10964 GEP);
10965 *i = Op;
10966 MadeChange = true;
10967 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010968 }
Chris Lattner28977af2004-04-05 01:30:19 +000010969 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010970 }
Chris Lattner28977af2004-04-05 01:30:19 +000010971 if (MadeChange) return &GEP;
10972
Chris Lattner90ac28c2002-08-02 19:29:35 +000010973 // Combine Indices - If the source pointer to this getelementptr instruction
10974 // is a getelementptr instruction, combine the indices of the two
10975 // getelementptr instructions into a single instruction.
10976 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010977 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010978 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010979 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010980
10981 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010982 // Note that if our source is a gep chain itself that we wait for that
10983 // chain to be resolved before we perform this transformation. This
10984 // avoids us creating a TON of code in some cases.
10985 //
10986 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10987 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10988 return 0; // Wait until our source is folded to completion.
10989
Chris Lattner72588fc2007-02-15 22:48:32 +000010990 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010991
10992 // Find out whether the last index in the source GEP is a sequential idx.
10993 bool EndsWithSequential = false;
10994 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10995 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010996 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010997
Chris Lattner90ac28c2002-08-02 19:29:35 +000010998 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010999 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011000 // Replace: gep (gep %P, long B), long A, ...
11001 // With: T = long A+B; gep %P, T, ...
11002 //
Chris Lattner620ce142004-05-07 22:09:22 +000011003 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000011004 if (SO1 == Constant::getNullValue(SO1->getType())) {
11005 Sum = GO1;
11006 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11007 Sum = SO1;
11008 } else {
11009 // If they aren't the same type, convert both to an integer of the
11010 // target's pointer size.
11011 if (SO1->getType() != GO1->getType()) {
11012 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000011013 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011014 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000011015 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000011016 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000011017 unsigned PS = TD->getPointerSizeInBits();
11018 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011019 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011020 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011021
Duncan Sands514ab342007-11-01 20:53:16 +000011022 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000011023 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000011024 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011025 } else {
11026 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000011027 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11028 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000011029 }
11030 }
11031 }
Chris Lattner620ce142004-05-07 22:09:22 +000011032 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11033 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11034 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011035 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000011036 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000011037 }
Chris Lattner28977af2004-04-05 01:30:19 +000011038 }
Chris Lattner620ce142004-05-07 22:09:22 +000011039
11040 // Recycle the GEP we already have if possible.
11041 if (SrcGEPOperands.size() == 2) {
11042 GEP.setOperand(0, SrcGEPOperands[0]);
11043 GEP.setOperand(1, Sum);
11044 return &GEP;
11045 } else {
11046 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11047 SrcGEPOperands.end()-1);
11048 Indices.push_back(Sum);
11049 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11050 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011051 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011052 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000011053 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011054 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000011055 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11056 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011057 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11058 }
11059
11060 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000011061 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11062 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000011063
Chris Lattner620ce142004-05-07 22:09:22 +000011064 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000011065 // GEP of global variable. If all of the indices for this GEP are
11066 // constants, we can promote this to a constexpr instead of an instruction.
11067
11068 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011069 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000011070 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11071 for (; I != E && isa<Constant>(*I); ++I)
11072 Indices.push_back(cast<Constant>(*I));
11073
11074 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000011075 Constant *CE = ConstantExpr::getGetElementPtr(GV,
11076 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000011077
11078 // Replace all uses of the GEP with the new constexpr...
11079 return ReplaceInstUsesWith(GEP, CE);
11080 }
Reid Spencer3da59db2006-11-27 01:05:10 +000011081 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000011082 if (!isa<PointerType>(X->getType())) {
11083 // Not interesting. Source pointer must be a cast from pointer.
11084 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011085 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11086 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011087 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011088 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11089 // into : GEP i8* X, ...
11090 //
Chris Lattnereed48272005-09-13 00:40:14 +000011091 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000011092 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11093 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011094 if (const ArrayType *CATy =
11095 dyn_cast<ArrayType>(CPTy->getElementType())) {
11096 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11097 if (CATy->getElementType() == XTy->getElementType()) {
11098 // -> GEP i8* X, ...
11099 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11100 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11101 GEP.getName());
11102 } else if (const ArrayType *XATy =
11103 dyn_cast<ArrayType>(XTy->getElementType())) {
11104 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011105 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011106 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011107 // At this point, we know that the cast source type is a pointer
11108 // to an array of the same type as the destination pointer
11109 // array. Because the array type is never stepped over (there
11110 // is a leading zero) we can fold the cast into this GEP.
11111 GEP.setOperand(0, X);
11112 return &GEP;
11113 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011114 }
11115 }
Chris Lattnereed48272005-09-13 00:40:14 +000011116 } else if (GEP.getNumOperands() == 2) {
11117 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011118 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11119 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011120 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11121 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11122 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011123 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11124 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011125 Value *Idx[2];
11126 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11127 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000011128 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000011129 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011130 // V and GEP are both pointer types --> BitCast
11131 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011132 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011133
11134 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011135 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011136 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011137 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011138
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011139 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011140 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011141 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011142
11143 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11144 // allow either a mul, shift, or constant here.
11145 Value *NewIdx = 0;
11146 ConstantInt *Scale = 0;
11147 if (ArrayEltSize == 1) {
11148 NewIdx = GEP.getOperand(1);
Dan Gohman6de29f82009-06-15 22:12:54 +000011149 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011150 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000011151 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011152 Scale = CI;
11153 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11154 if (Inst->getOpcode() == Instruction::Shl &&
11155 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011156 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11157 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Dan Gohman6de29f82009-06-15 22:12:54 +000011158 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11159 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011160 NewIdx = Inst->getOperand(0);
11161 } else if (Inst->getOpcode() == Instruction::Mul &&
11162 isa<ConstantInt>(Inst->getOperand(1))) {
11163 Scale = cast<ConstantInt>(Inst->getOperand(1));
11164 NewIdx = Inst->getOperand(0);
11165 }
11166 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011167
Chris Lattner7835cdd2005-09-13 18:36:04 +000011168 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011169 // out, perform the transformation. Note, we don't know whether Scale is
11170 // signed or not. We'll use unsigned version of division/modulo
11171 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011172 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011173 Scale->getZExtValue() % ArrayEltSize == 0) {
11174 Scale = ConstantInt::get(Scale->getType(),
11175 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011176 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000011177 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011178 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011179 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011180 NewIdx = InsertNewInstBefore(Sc, GEP);
11181 }
11182
11183 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011184 Value *Idx[2];
11185 Idx[0] = Constant::getNullValue(Type::Int32Ty);
11186 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011187 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011188 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011189 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11190 // The NewGEP must be pointer typed, so must the old one -> BitCast
11191 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011192 }
11193 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011194 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011195 }
Chris Lattner58407792009-01-09 04:53:57 +000011196
Chris Lattner46cd5a12009-01-09 05:44:56 +000011197 /// See if we can simplify:
11198 /// X = bitcast A to B*
11199 /// Y = gep X, <...constant indices...>
11200 /// into a gep of the original struct. This is important for SROA and alias
11201 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011202 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011203 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11204 // Determine how much the GEP moves the pointer. We are guaranteed to get
11205 // a constant back from EmitGEPOffset.
11206 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11207 int64_t Offset = OffsetV->getSExtValue();
11208
11209 // If this GEP instruction doesn't move the pointer, just replace the GEP
11210 // with a bitcast of the real input to the dest type.
11211 if (Offset == 0) {
11212 // If the bitcast is of an allocation, and the allocation will be
11213 // converted to match the type of the cast, don't touch this.
11214 if (isa<AllocationInst>(BCI->getOperand(0))) {
11215 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11216 if (Instruction *I = visitBitCast(*BCI)) {
11217 if (I != BCI) {
11218 I->takeName(BCI);
11219 BCI->getParent()->getInstList().insert(BCI, I);
11220 ReplaceInstUsesWith(*BCI, I);
11221 }
11222 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011223 }
Chris Lattner58407792009-01-09 04:53:57 +000011224 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011225 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011226 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011227
11228 // Otherwise, if the offset is non-zero, we need to find out if there is a
11229 // field at Offset in 'A's type. If so, we can pull the cast through the
11230 // GEP.
11231 SmallVector<Value*, 8> NewIndices;
11232 const Type *InTy =
11233 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11234 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11235 Instruction *NGEP =
11236 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11237 NewIndices.end());
11238 if (NGEP->getType() == GEP.getType()) return NGEP;
11239 InsertNewInstBefore(NGEP, GEP);
11240 NGEP->takeName(&GEP);
11241 return new BitCastInst(NGEP, GEP.getType());
11242 }
Chris Lattner58407792009-01-09 04:53:57 +000011243 }
11244 }
11245
Chris Lattner8a2a3112001-12-14 16:52:21 +000011246 return 0;
11247}
11248
Chris Lattner0864acf2002-11-04 16:18:53 +000011249Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11250 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011251 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011252 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11253 const Type *NewTy =
11254 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011255 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011256
11257 // Create and insert the replacement instruction...
11258 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000011259 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011260 else {
11261 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000011262 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011263 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011264
11265 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011266
Chris Lattner0864acf2002-11-04 16:18:53 +000011267 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011268 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011269 //
11270 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011271 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011272
11273 // Now that I is pointing to the first non-allocation-inst in the block,
11274 // insert our getelementptr instruction...
11275 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000011276 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000011277 Value *Idx[2];
11278 Idx[0] = NullIdx;
11279 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011280 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11281 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011282
11283 // Now make everything use the getelementptr instead of the original
11284 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011285 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011286 } else if (isa<UndefValue>(AI.getArraySize())) {
11287 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011288 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011289 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011290
Dan Gohman6893cd72009-01-13 20:18:38 +000011291 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11292 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011293 // Note that we only do this for alloca's, because malloc should allocate
11294 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011295 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Dan Gohman6893cd72009-01-13 20:18:38 +000011296 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11297
11298 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11299 if (AI.getAlignment() == 0)
11300 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11301 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011302
Chris Lattner0864acf2002-11-04 16:18:53 +000011303 return 0;
11304}
11305
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011306Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11307 Value *Op = FI.getOperand(0);
11308
Chris Lattner17be6352004-10-18 02:59:09 +000011309 // free undef -> unreachable.
11310 if (isa<UndefValue>(Op)) {
11311 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000011312 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011313 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011314 return EraseInstFromFunction(FI);
11315 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011316
Chris Lattner6160e852004-02-28 04:57:37 +000011317 // If we have 'free null' delete the instruction. This can happen in stl code
11318 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011319 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011320 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011321
11322 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11323 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11324 FI.setOperand(0, CI->getOperand(0));
11325 return &FI;
11326 }
11327
11328 // Change free (gep X, 0,0,0,0) into free(X)
11329 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11330 if (GEPI->hasAllZeroIndices()) {
11331 AddToWorkList(GEPI);
11332 FI.setOperand(0, GEPI->getOperand(0));
11333 return &FI;
11334 }
11335 }
11336
11337 // Change free(malloc) into nothing, if the malloc has a single use.
11338 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11339 if (MI->hasOneUse()) {
11340 EraseInstFromFunction(FI);
11341 return EraseInstFromFunction(*MI);
11342 }
Chris Lattner6160e852004-02-28 04:57:37 +000011343
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011344 return 0;
11345}
11346
11347
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011348/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011349static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011350 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011351 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011352 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000011353
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011354 if (TD) {
11355 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11356 // Instead of loading constant c string, use corresponding integer value
11357 // directly if string length is small enough.
11358 std::string Str;
11359 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11360 unsigned len = Str.length();
11361 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11362 unsigned numBits = Ty->getPrimitiveSizeInBits();
11363 // Replace LI with immediate integer store.
11364 if ((numBits >> 3) == len + 1) {
11365 APInt StrVal(numBits, 0);
11366 APInt SingleChar(numBits, 0);
11367 if (TD->isLittleEndian()) {
11368 for (signed i = len-1; i >= 0; i--) {
11369 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11370 StrVal = (StrVal << 8) | SingleChar;
11371 }
11372 } else {
11373 for (unsigned i = 0; i < len; i++) {
11374 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11375 StrVal = (StrVal << 8) | SingleChar;
11376 }
11377 // Append NULL at the end.
11378 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011379 StrVal = (StrVal << 8) | SingleChar;
11380 }
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011381 Value *NL = ConstantInt::get(StrVal);
11382 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011383 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011384 }
11385 }
11386 }
11387
Mon P Wang6753f952009-02-07 22:19:29 +000011388 const PointerType *DestTy = cast<PointerType>(CI->getType());
11389 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011390 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011391
11392 // If the address spaces don't match, don't eliminate the cast.
11393 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11394 return 0;
11395
Chris Lattnerb89e0712004-07-13 01:49:43 +000011396 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011397
Reid Spencer42230162007-01-22 05:51:25 +000011398 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011399 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011400 // If the source is an array, the code below will not succeed. Check to
11401 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11402 // constants.
11403 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11404 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11405 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011406 Value *Idxs[2];
11407 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11408 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011409 SrcTy = cast<PointerType>(CastOp->getType());
11410 SrcPTy = SrcTy->getElementType();
11411 }
11412
Reid Spencer42230162007-01-22 05:51:25 +000011413 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011414 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011415 // Do not allow turning this into a load of an integer, which is then
11416 // casted to a pointer, this pessimizes pointer analysis a lot.
11417 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011418 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11419 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011420
Chris Lattnerf9527852005-01-31 04:50:46 +000011421 // Okay, we are casting from one integer or pointer type to another of
11422 // the same size. Instead of casting the pointer before the load, cast
11423 // the result of the loaded value.
11424 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11425 CI->getName(),
11426 LI.isVolatile()),LI);
11427 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011428 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011429 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011430 }
11431 }
11432 return 0;
11433}
11434
Chris Lattner833b8a42003-06-26 05:06:25 +000011435Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11436 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011437
Dan Gohman9941f742007-07-20 16:34:21 +000011438 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011439 unsigned KnownAlign =
11440 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011441 if (KnownAlign >
11442 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11443 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011444 LI.setAlignment(KnownAlign);
11445
Chris Lattner37366c12005-05-01 04:24:53 +000011446 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011447 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011448 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011449 return Res;
11450
11451 // None of the following transforms are legal for volatile loads.
11452 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011453
Dan Gohman2276a7b2008-10-15 23:19:35 +000011454 // Do really simple store-to-load forwarding and load CSE, to catch cases
11455 // where there are several consequtive memory accesses to the same location,
11456 // separated by a few arithmetic operations.
11457 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011458 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11459 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011460
Christopher Lambb15147e2007-12-29 07:56:53 +000011461 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11462 const Value *GEPI0 = GEPI->getOperand(0);
11463 // TODO: Consider a target hook for valid address spaces for this xform.
11464 if (isa<ConstantPointerNull>(GEPI0) &&
11465 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011466 // Insert a new store to null instruction before the load to indicate
11467 // that this code is not reachable. We do this instead of inserting
11468 // an unreachable instruction directly because we cannot modify the
11469 // CFG.
11470 new StoreInst(UndefValue::get(LI.getType()),
11471 Constant::getNullValue(Op->getType()), &LI);
11472 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11473 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011474 }
Chris Lattner37366c12005-05-01 04:24:53 +000011475
Chris Lattnere87597f2004-10-16 18:11:37 +000011476 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011477 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011478 // TODO: Consider a target hook for valid address spaces for this xform.
11479 if (isa<UndefValue>(C) || (C->isNullValue() &&
11480 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011481 // Insert a new store to null instruction before the load to indicate that
11482 // this code is not reachable. We do this instead of inserting an
11483 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011484 new StoreInst(UndefValue::get(LI.getType()),
11485 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011486 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011487 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011488
Chris Lattnere87597f2004-10-16 18:11:37 +000011489 // Instcombine load (constant global) into the value loaded.
11490 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011491 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011492 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011493
Chris Lattnere87597f2004-10-16 18:11:37 +000011494 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011495 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011496 if (CE->getOpcode() == Instruction::GetElementPtr) {
11497 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011498 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011499 if (Constant *V =
11500 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011501 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011502 if (CE->getOperand(0)->isNullValue()) {
11503 // Insert a new store to null instruction before the load to indicate
11504 // that this code is not reachable. We do this instead of inserting
11505 // an unreachable instruction directly because we cannot modify the
11506 // CFG.
11507 new StoreInst(UndefValue::get(LI.getType()),
11508 Constant::getNullValue(Op->getType()), &LI);
11509 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11510 }
11511
Reid Spencer3da59db2006-11-27 01:05:10 +000011512 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011513 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011514 return Res;
11515 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011516 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011517 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011518
11519 // If this load comes from anywhere in a constant global, and if the global
11520 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011521 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011522 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011523 if (GV->getInitializer()->isNullValue())
11524 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11525 else if (isa<UndefValue>(GV->getInitializer()))
11526 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11527 }
11528 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011529
Chris Lattner37366c12005-05-01 04:24:53 +000011530 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011531 // Change select and PHI nodes to select values instead of addresses: this
11532 // helps alias analysis out a lot, allows many others simplifications, and
11533 // exposes redundancy in the code.
11534 //
11535 // Note that we cannot do the transformation unless we know that the
11536 // introduced loads cannot trap! Something like this is valid as long as
11537 // the condition is always false: load (select bool %C, int* null, int* %G),
11538 // but it would not be valid if we transformed it to load from null
11539 // unconditionally.
11540 //
11541 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11542 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011543 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11544 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011545 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011546 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011547 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011548 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011549 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011550 }
11551
Chris Lattner684fe212004-09-23 15:46:00 +000011552 // load (select (cond, null, P)) -> load P
11553 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11554 if (C->isNullValue()) {
11555 LI.setOperand(0, SI->getOperand(2));
11556 return &LI;
11557 }
11558
11559 // load (select (cond, P, null)) -> load P
11560 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11561 if (C->isNullValue()) {
11562 LI.setOperand(0, SI->getOperand(1));
11563 return &LI;
11564 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011565 }
11566 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011567 return 0;
11568}
11569
Reid Spencer55af2b52007-01-19 21:20:31 +000011570/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011571/// when possible. This makes it generally easy to do alias analysis and/or
11572/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011573static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11574 User *CI = cast<User>(SI.getOperand(1));
11575 Value *CastOp = CI->getOperand(0);
11576
11577 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011578 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11579 if (SrcTy == 0) return 0;
11580
11581 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011582
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011583 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11584 return 0;
11585
Chris Lattner3914f722009-01-24 01:00:13 +000011586 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11587 /// to its first element. This allows us to handle things like:
11588 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11589 /// on 32-bit hosts.
11590 SmallVector<Value*, 4> NewGEPIndices;
11591
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011592 // If the source is an array, the code below will not succeed. Check to
11593 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11594 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011595 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11596 // Index through pointer.
11597 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11598 NewGEPIndices.push_back(Zero);
11599
11600 while (1) {
11601 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011602 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011603 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011604 NewGEPIndices.push_back(Zero);
11605 SrcPTy = STy->getElementType(0);
11606 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11607 NewGEPIndices.push_back(Zero);
11608 SrcPTy = ATy->getElementType();
11609 } else {
11610 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011611 }
Chris Lattner3914f722009-01-24 01:00:13 +000011612 }
11613
11614 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11615 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011616
11617 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11618 return 0;
11619
Chris Lattner71759c42009-01-16 20:12:52 +000011620 // If the pointers point into different address spaces or if they point to
11621 // values with different sizes, we can't do the transformation.
11622 if (SrcTy->getAddressSpace() !=
11623 cast<PointerType>(CI->getType())->getAddressSpace() ||
11624 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011625 IC.getTargetData().getTypeSizeInBits(DestPTy))
11626 return 0;
11627
11628 // Okay, we are casting from one integer or pointer type to another of
11629 // the same size. Instead of casting the pointer before
11630 // the store, cast the value to be stored.
11631 Value *NewCast;
11632 Value *SIOp0 = SI.getOperand(0);
11633 Instruction::CastOps opcode = Instruction::BitCast;
11634 const Type* CastSrcTy = SIOp0->getType();
11635 const Type* CastDstTy = SrcPTy;
11636 if (isa<PointerType>(CastDstTy)) {
11637 if (CastSrcTy->isInteger())
11638 opcode = Instruction::IntToPtr;
11639 } else if (isa<IntegerType>(CastDstTy)) {
11640 if (isa<PointerType>(SIOp0->getType()))
11641 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011642 }
Chris Lattner3914f722009-01-24 01:00:13 +000011643
11644 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11645 // emit a GEP to index into its first field.
11646 if (!NewGEPIndices.empty()) {
11647 if (Constant *C = dyn_cast<Constant>(CastOp))
11648 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11649 NewGEPIndices.size());
11650 else
11651 CastOp = IC.InsertNewInstBefore(
11652 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11653 NewGEPIndices.end()), SI);
11654 }
11655
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011656 if (Constant *C = dyn_cast<Constant>(SIOp0))
11657 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11658 else
11659 NewCast = IC.InsertNewInstBefore(
11660 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11661 SI);
11662 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011663}
11664
Chris Lattner4aebaee2008-11-27 08:56:30 +000011665/// equivalentAddressValues - Test if A and B will obviously have the same
11666/// value. This includes recognizing that %t0 and %t1 will have the same
11667/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011668/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011669/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011670/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011671/// %t2 = load i32* %t1
11672///
11673static bool equivalentAddressValues(Value *A, Value *B) {
11674 // Test if the values are trivially equivalent.
11675 if (A == B) return true;
11676
11677 // Test if the values come form identical arithmetic instructions.
11678 if (isa<BinaryOperator>(A) ||
11679 isa<CastInst>(A) ||
11680 isa<PHINode>(A) ||
11681 isa<GetElementPtrInst>(A))
11682 if (Instruction *BI = dyn_cast<Instruction>(B))
11683 if (cast<Instruction>(A)->isIdenticalTo(BI))
11684 return true;
11685
11686 // Otherwise they may not be equivalent.
11687 return false;
11688}
11689
Dale Johannesen4945c652009-03-03 21:26:39 +000011690// If this instruction has two uses, one of which is a llvm.dbg.declare,
11691// return the llvm.dbg.declare.
11692DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11693 if (!V->hasNUses(2))
11694 return 0;
11695 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11696 UI != E; ++UI) {
11697 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11698 return DI;
11699 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11700 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11701 return DI;
11702 }
11703 }
11704 return 0;
11705}
11706
Chris Lattner2f503e62005-01-31 05:36:43 +000011707Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11708 Value *Val = SI.getOperand(0);
11709 Value *Ptr = SI.getOperand(1);
11710
11711 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011712 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011713 ++NumCombined;
11714 return 0;
11715 }
Chris Lattner836692d2007-01-15 06:51:56 +000011716
11717 // If the RHS is an alloca with a single use, zapify the store, making the
11718 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011719 // If the RHS is an alloca with a two uses, the other one being a
11720 // llvm.dbg.declare, zapify the store and the declare, making the
11721 // alloca dead. We must do this to prevent declare's from affecting
11722 // codegen.
11723 if (!SI.isVolatile()) {
11724 if (Ptr->hasOneUse()) {
11725 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011726 EraseInstFromFunction(SI);
11727 ++NumCombined;
11728 return 0;
11729 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011730 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11731 if (isa<AllocaInst>(GEP->getOperand(0))) {
11732 if (GEP->getOperand(0)->hasOneUse()) {
11733 EraseInstFromFunction(SI);
11734 ++NumCombined;
11735 return 0;
11736 }
11737 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11738 EraseInstFromFunction(*DI);
11739 EraseInstFromFunction(SI);
11740 ++NumCombined;
11741 return 0;
11742 }
11743 }
11744 }
11745 }
11746 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11747 EraseInstFromFunction(*DI);
11748 EraseInstFromFunction(SI);
11749 ++NumCombined;
11750 return 0;
11751 }
Chris Lattner836692d2007-01-15 06:51:56 +000011752 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011753
Dan Gohman9941f742007-07-20 16:34:21 +000011754 // Attempt to improve the alignment.
Dan Gohman926b0a22009-02-16 00:44:23 +000011755 unsigned KnownAlign =
11756 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohmaneee962e2008-04-10 18:43:06 +000011757 if (KnownAlign >
11758 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11759 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011760 SI.setAlignment(KnownAlign);
11761
Dale Johannesenacb51a32009-03-03 01:43:03 +000011762 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011763 // stores to the same location, separated by a few arithmetic operations. This
11764 // situation often occurs with bitfield accesses.
11765 BasicBlock::iterator BBI = &SI;
11766 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11767 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011768 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011769 // Don't count debug info directives, lest they affect codegen,
11770 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11771 // It is necessary for correctness to skip those that feed into a
11772 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011773 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011774 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011775 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011776 continue;
11777 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011778
11779 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11780 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011781 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11782 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011783 ++NumDeadStore;
11784 ++BBI;
11785 EraseInstFromFunction(*PrevSI);
11786 continue;
11787 }
11788 break;
11789 }
11790
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011791 // If this is a load, we have to stop. However, if the loaded value is from
11792 // the pointer we're loading and is producing the pointer we're storing,
11793 // then *this* store is dead (X = load P; store X -> P).
11794 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011795 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11796 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011797 EraseInstFromFunction(SI);
11798 ++NumCombined;
11799 return 0;
11800 }
11801 // Otherwise, this is a load from some other location. Stores before it
11802 // may not be dead.
11803 break;
11804 }
11805
Chris Lattner9ca96412006-02-08 03:25:32 +000011806 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011807 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011808 break;
11809 }
11810
11811
11812 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011813
11814 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011815 if (isa<ConstantPointerNull>(Ptr) &&
11816 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011817 if (!isa<UndefValue>(Val)) {
11818 SI.setOperand(0, UndefValue::get(Val->getType()));
11819 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011820 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011821 ++NumCombined;
11822 }
11823 return 0; // Do not modify these!
11824 }
11825
11826 // store undef, Ptr -> noop
11827 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011828 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011829 ++NumCombined;
11830 return 0;
11831 }
11832
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011833 // If the pointer destination is a cast, see if we can fold the cast into the
11834 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011835 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011836 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11837 return Res;
11838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011839 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011840 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11841 return Res;
11842
Chris Lattner408902b2005-09-12 23:23:25 +000011843
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011844 // If this store is the last instruction in the basic block (possibly
11845 // excepting debug info instructions and the pointer bitcasts that feed
11846 // into them), and if the block ends with an unconditional branch, try
11847 // to move it to the successor block.
11848 BBI = &SI;
11849 do {
11850 ++BBI;
11851 } while (isa<DbgInfoIntrinsic>(BBI) ||
11852 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011853 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011854 if (BI->isUnconditional())
11855 if (SimplifyStoreAtEndOfBlock(SI))
11856 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011857
Chris Lattner2f503e62005-01-31 05:36:43 +000011858 return 0;
11859}
11860
Chris Lattner3284d1f2007-04-15 00:07:55 +000011861/// SimplifyStoreAtEndOfBlock - Turn things like:
11862/// if () { *P = v1; } else { *P = v2 }
11863/// into a phi node with a store in the successor.
11864///
Chris Lattner31755a02007-04-15 01:02:18 +000011865/// Simplify things like:
11866/// *P = v1; if () { *P = v2; }
11867/// into a phi node with a store in the successor.
11868///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011869bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11870 BasicBlock *StoreBB = SI.getParent();
11871
11872 // Check to see if the successor block has exactly two incoming edges. If
11873 // so, see if the other predecessor contains a store to the same location.
11874 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011875 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011876
11877 // Determine whether Dest has exactly two predecessors and, if so, compute
11878 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011879 pred_iterator PI = pred_begin(DestBB);
11880 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011881 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011882 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011883 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011884 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011885 return false;
11886
11887 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011888 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011889 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011890 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011891 }
Chris Lattner31755a02007-04-15 01:02:18 +000011892 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011893 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011894
11895 // Bail out if all the relevant blocks aren't distinct (this can happen,
11896 // for example, if SI is in an infinite loop)
11897 if (StoreBB == DestBB || OtherBB == DestBB)
11898 return false;
11899
Chris Lattner31755a02007-04-15 01:02:18 +000011900 // Verify that the other block ends in a branch and is not otherwise empty.
11901 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011902 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011903 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011904 return false;
11905
Chris Lattner31755a02007-04-15 01:02:18 +000011906 // If the other block ends in an unconditional branch, check for the 'if then
11907 // else' case. there is an instruction before the branch.
11908 StoreInst *OtherStore = 0;
11909 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011910 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011911 // Skip over debugging info.
11912 while (isa<DbgInfoIntrinsic>(BBI) ||
11913 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11914 if (BBI==OtherBB->begin())
11915 return false;
11916 --BBI;
11917 }
11918 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011919 OtherStore = dyn_cast<StoreInst>(BBI);
11920 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11921 return false;
11922 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011923 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011924 // destinations is StoreBB, then we have the if/then case.
11925 if (OtherBr->getSuccessor(0) != StoreBB &&
11926 OtherBr->getSuccessor(1) != StoreBB)
11927 return false;
11928
11929 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011930 // if/then triangle. See if there is a store to the same ptr as SI that
11931 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011932 for (;; --BBI) {
11933 // Check to see if we find the matching store.
11934 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11935 if (OtherStore->getOperand(1) != SI.getOperand(1))
11936 return false;
11937 break;
11938 }
Eli Friedman6903a242008-06-13 22:02:12 +000011939 // If we find something that may be using or overwriting the stored
11940 // value, or if we run out of instructions, we can't do the xform.
11941 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011942 BBI == OtherBB->begin())
11943 return false;
11944 }
11945
11946 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011947 // make sure nothing reads or overwrites the stored value in
11948 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011949 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11950 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011951 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011952 return false;
11953 }
11954 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011955
Chris Lattner31755a02007-04-15 01:02:18 +000011956 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011957 Value *MergedVal = OtherStore->getOperand(0);
11958 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011959 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011960 PN->reserveOperandSpace(2);
11961 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011962 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11963 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011964 }
11965
11966 // Advance to a place where it is safe to insert the new store and
11967 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011968 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011969 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11970 OtherStore->isVolatile()), *BBI);
11971
11972 // Nuke the old stores.
11973 EraseInstFromFunction(SI);
11974 EraseInstFromFunction(*OtherStore);
11975 ++NumCombined;
11976 return true;
11977}
11978
Chris Lattner2f503e62005-01-31 05:36:43 +000011979
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011980Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11981 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011982 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011983 BasicBlock *TrueDest;
11984 BasicBlock *FalseDest;
11985 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11986 !isa<Constant>(X)) {
11987 // Swap Destinations and condition...
11988 BI.setCondition(X);
11989 BI.setSuccessor(0, FalseDest);
11990 BI.setSuccessor(1, TrueDest);
11991 return &BI;
11992 }
11993
Reid Spencere4d87aa2006-12-23 06:05:41 +000011994 // Cannonicalize fcmp_one -> fcmp_oeq
11995 FCmpInst::Predicate FPred; Value *Y;
11996 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11997 TrueDest, FalseDest)))
11998 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11999 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12000 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012001 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000012002 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12003 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012004 // Swap Destinations and condition...
12005 BI.setCondition(NewSCC);
12006 BI.setSuccessor(0, FalseDest);
12007 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012008 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012009 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012010 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012011 return &BI;
12012 }
12013
12014 // Cannonicalize icmp_ne -> icmp_eq
12015 ICmpInst::Predicate IPred;
12016 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12017 TrueDest, FalseDest)))
12018 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12019 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12020 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12021 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000012022 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000012023 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12024 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000012025 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012026 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012027 BI.setSuccessor(0, FalseDest);
12028 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000012029 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000012030 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012031 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000012032 return &BI;
12033 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012034
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012035 return 0;
12036}
Chris Lattner0864acf2002-11-04 16:18:53 +000012037
Chris Lattner46238a62004-07-03 00:26:11 +000012038Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12039 Value *Cond = SI.getCondition();
12040 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12041 if (I->getOpcode() == Instruction::Add)
12042 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12043 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12044 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000012045 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012046 AddRHS));
12047 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000012048 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012049 return &SI;
12050 }
12051 }
12052 return 0;
12053}
12054
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012055Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012056 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012057
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012058 if (!EV.hasIndices())
12059 return ReplaceInstUsesWith(EV, Agg);
12060
12061 if (Constant *C = dyn_cast<Constant>(Agg)) {
12062 if (isa<UndefValue>(C))
12063 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12064
12065 if (isa<ConstantAggregateZero>(C))
12066 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12067
12068 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12069 // Extract the element indexed by the first index out of the constant
12070 Value *V = C->getOperand(*EV.idx_begin());
12071 if (EV.getNumIndices() > 1)
12072 // Extract the remaining indices out of the constant indexed by the
12073 // first index
12074 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12075 else
12076 return ReplaceInstUsesWith(EV, V);
12077 }
12078 return 0; // Can't handle other constants
12079 }
12080 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12081 // We're extracting from an insertvalue instruction, compare the indices
12082 const unsigned *exti, *exte, *insi, *inse;
12083 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12084 exte = EV.idx_end(), inse = IV->idx_end();
12085 exti != exte && insi != inse;
12086 ++exti, ++insi) {
12087 if (*insi != *exti)
12088 // The insert and extract both reference distinctly different elements.
12089 // This means the extract is not influenced by the insert, and we can
12090 // replace the aggregate operand of the extract with the aggregate
12091 // operand of the insert. i.e., replace
12092 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12093 // %E = extractvalue { i32, { i32 } } %I, 0
12094 // with
12095 // %E = extractvalue { i32, { i32 } } %A, 0
12096 return ExtractValueInst::Create(IV->getAggregateOperand(),
12097 EV.idx_begin(), EV.idx_end());
12098 }
12099 if (exti == exte && insi == inse)
12100 // Both iterators are at the end: Index lists are identical. Replace
12101 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12102 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12103 // with "i32 42"
12104 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12105 if (exti == exte) {
12106 // The extract list is a prefix of the insert list. i.e. replace
12107 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12108 // %E = extractvalue { i32, { i32 } } %I, 1
12109 // with
12110 // %X = extractvalue { i32, { i32 } } %A, 1
12111 // %E = insertvalue { i32 } %X, i32 42, 0
12112 // by switching the order of the insert and extract (though the
12113 // insertvalue should be left in, since it may have other uses).
12114 Value *NewEV = InsertNewInstBefore(
12115 ExtractValueInst::Create(IV->getAggregateOperand(),
12116 EV.idx_begin(), EV.idx_end()),
12117 EV);
12118 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12119 insi, inse);
12120 }
12121 if (insi == inse)
12122 // The insert list is a prefix of the extract list
12123 // We can simply remove the common indices from the extract and make it
12124 // operate on the inserted value instead of the insertvalue result.
12125 // i.e., replace
12126 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12127 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12128 // with
12129 // %E extractvalue { i32 } { i32 42 }, 0
12130 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12131 exti, exte);
12132 }
12133 // Can't simplify extracts from other values. Note that nested extracts are
12134 // already simplified implicitely by the above (extract ( extract (insert) )
12135 // will be translated into extract ( insert ( extract ) ) first and then just
12136 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012137 return 0;
12138}
12139
Chris Lattner220b0cf2006-03-05 00:22:33 +000012140/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12141/// is to leave as a vector operation.
12142static bool CheapToScalarize(Value *V, bool isConstant) {
12143 if (isa<ConstantAggregateZero>(V))
12144 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012145 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012146 if (isConstant) return true;
12147 // If all elts are the same, we can extract.
12148 Constant *Op0 = C->getOperand(0);
12149 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12150 if (C->getOperand(i) != Op0)
12151 return false;
12152 return true;
12153 }
12154 Instruction *I = dyn_cast<Instruction>(V);
12155 if (!I) return false;
12156
12157 // Insert element gets simplified to the inserted element or is deleted if
12158 // this is constant idx extract element and its a constant idx insertelt.
12159 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12160 isa<ConstantInt>(I->getOperand(2)))
12161 return true;
12162 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12163 return true;
12164 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12165 if (BO->hasOneUse() &&
12166 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12167 CheapToScalarize(BO->getOperand(1), isConstant)))
12168 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012169 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12170 if (CI->hasOneUse() &&
12171 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12172 CheapToScalarize(CI->getOperand(1), isConstant)))
12173 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012174
12175 return false;
12176}
12177
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012178/// Read and decode a shufflevector mask.
12179///
12180/// It turns undef elements into values that are larger than the number of
12181/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012182static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12183 unsigned NElts = SVI->getType()->getNumElements();
12184 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12185 return std::vector<unsigned>(NElts, 0);
12186 if (isa<UndefValue>(SVI->getOperand(2)))
12187 return std::vector<unsigned>(NElts, 2*NElts);
12188
12189 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012190 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012191 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12192 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012193 Result.push_back(NElts*2); // undef -> 8
12194 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012195 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012196 return Result;
12197}
12198
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012199/// FindScalarElement - Given a vector and an element number, see if the scalar
12200/// value is already around as a register, for example if it were inserted then
12201/// extracted from the vector.
12202static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012203 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12204 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012205 unsigned Width = PTy->getNumElements();
12206 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012207 return UndefValue::get(PTy->getElementType());
12208
12209 if (isa<UndefValue>(V))
12210 return UndefValue::get(PTy->getElementType());
12211 else if (isa<ConstantAggregateZero>(V))
12212 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012213 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012214 return CP->getOperand(EltNo);
12215 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12216 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012217 if (!isa<ConstantInt>(III->getOperand(2)))
12218 return 0;
12219 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012220
12221 // If this is an insert to the element we are looking for, return the
12222 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012223 if (EltNo == IIElt)
12224 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012225
12226 // Otherwise, the insertelement doesn't modify the value, recurse on its
12227 // vector input.
12228 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000012229 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012230 unsigned LHSWidth =
12231 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012232 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012233 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012234 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012235 else if (InEl < LHSWidth*2)
12236 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000012237 else
12238 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012239 }
12240
12241 // Otherwise, we don't know.
12242 return 0;
12243}
12244
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012245Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012246 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012247 if (isa<UndefValue>(EI.getOperand(0)))
12248 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12249
Dan Gohman07a96762007-07-16 14:29:03 +000012250 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012251 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12252 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12253
Reid Spencer9d6565a2007-02-15 02:26:10 +000012254 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012255 // If vector val is constant with all elements the same, replace EI with
12256 // that element. When the elements are not identical, we cannot replace yet
12257 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012258 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012259 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012260 if (C->getOperand(i) != op0) {
12261 op0 = 0;
12262 break;
12263 }
12264 if (op0)
12265 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012266 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000012267
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012268 // If extracting a specified index from the vector, see if we can recursively
12269 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012270 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012271 unsigned IndexVal = IdxC->getZExtValue();
12272 unsigned VectorWidth =
12273 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12274
12275 // If this is extracting an invalid index, turn this into undef, to avoid
12276 // crashing the code below.
12277 if (IndexVal >= VectorWidth)
12278 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12279
Chris Lattner867b99f2006-10-05 06:55:50 +000012280 // This instruction only demands the single element from the input vector.
12281 // If the input vector has a single use, simplify it based on this use
12282 // property.
Chris Lattner85464092007-04-09 01:37:55 +000012283 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012284 APInt UndefElts(VectorWidth, 0);
12285 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012286 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012287 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012288 EI.setOperand(0, V);
12289 return &EI;
12290 }
12291 }
12292
Reid Spencerb83eb642006-10-20 07:07:24 +000012293 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012294 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012295
12296 // If the this extractelement is directly using a bitcast from a vector of
12297 // the same number of elements, see if we can find the source element from
12298 // it. In this case, we will end up needing to bitcast the scalars.
12299 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12300 if (const VectorType *VT =
12301 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12302 if (VT->getNumElements() == VectorWidth)
12303 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12304 return new BitCastInst(Elt, EI.getType());
12305 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012306 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012307
Chris Lattner73fa49d2006-05-25 22:53:38 +000012308 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012309 if (I->hasOneUse()) {
12310 // Push extractelement into predecessor operation if legal and
12311 // profitable to do so
12312 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012313 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12314 if (CheapToScalarize(BO, isConstantElt)) {
12315 ExtractElementInst *newEI0 =
12316 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12317 EI.getName()+".lhs");
12318 ExtractElementInst *newEI1 =
12319 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12320 EI.getName()+".rhs");
12321 InsertNewInstBefore(newEI0, EI);
12322 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012323 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012324 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012325 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012326 unsigned AS =
12327 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012328 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12329 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012330 GetElementPtrInst *GEP =
12331 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012332 InsertNewInstBefore(GEP, EI);
12333 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012334 }
12335 }
12336 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12337 // Extracting the inserted element?
12338 if (IE->getOperand(2) == EI.getOperand(1))
12339 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12340 // If the inserted and extracted elements are constants, they must not
12341 // be the same value, extract from the pre-inserted value instead.
12342 if (isa<Constant>(IE->getOperand(2)) &&
12343 isa<Constant>(EI.getOperand(1))) {
12344 AddUsesToWorkList(EI);
12345 EI.setOperand(0, IE->getOperand(0));
12346 return &EI;
12347 }
12348 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12349 // If this is extracting an element from a shufflevector, figure out where
12350 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012351 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12352 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012353 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012354 unsigned LHSWidth =
12355 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12356
12357 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012358 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012359 else if (SrcIdx < LHSWidth*2) {
12360 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012361 Src = SVI->getOperand(1);
12362 } else {
12363 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012364 }
Chris Lattner867b99f2006-10-05 06:55:50 +000012365 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012366 }
12367 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000012368 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012369 return 0;
12370}
12371
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012372/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12373/// elements from either LHS or RHS, return the shuffle mask and true.
12374/// Otherwise, return false.
12375static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12376 std::vector<Constant*> &Mask) {
12377 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12378 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012379 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012380
12381 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012382 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012383 return true;
12384 } else if (V == LHS) {
12385 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012386 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012387 return true;
12388 } else if (V == RHS) {
12389 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012390 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012391 return true;
12392 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12393 // If this is an insert of an extract from some other vector, include it.
12394 Value *VecOp = IEI->getOperand(0);
12395 Value *ScalarOp = IEI->getOperand(1);
12396 Value *IdxOp = IEI->getOperand(2);
12397
Chris Lattnerd929f062006-04-27 21:14:21 +000012398 if (!isa<ConstantInt>(IdxOp))
12399 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012400 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012401
12402 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12403 // Okay, we can handle this if the vector we are insertinting into is
12404 // transitively ok.
12405 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12406 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012407 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012408 return true;
12409 }
12410 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12411 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012412 EI->getOperand(0)->getType() == V->getType()) {
12413 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012414 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012415
12416 // This must be extracting from either LHS or RHS.
12417 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12418 // Okay, we can handle this if the vector we are insertinting into is
12419 // transitively ok.
12420 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12421 // If so, update the mask to reflect the inserted value.
12422 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012423 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012424 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012425 } else {
12426 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012427 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012428 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012429
12430 }
12431 return true;
12432 }
12433 }
12434 }
12435 }
12436 }
12437 // TODO: Handle shufflevector here!
12438
12439 return false;
12440}
12441
12442/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12443/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12444/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012445static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012446 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012447 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012448 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012449 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012450 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012451
12452 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012453 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012454 return V;
12455 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012456 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012457 return V;
12458 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12459 // If this is an insert of an extract from some other vector, include it.
12460 Value *VecOp = IEI->getOperand(0);
12461 Value *ScalarOp = IEI->getOperand(1);
12462 Value *IdxOp = IEI->getOperand(2);
12463
12464 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12465 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12466 EI->getOperand(0)->getType() == V->getType()) {
12467 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012468 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12469 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012470
12471 // Either the extracted from or inserted into vector must be RHSVec,
12472 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012473 if (EI->getOperand(0) == RHS || RHS == 0) {
12474 RHS = EI->getOperand(0);
12475 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012476 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012477 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012478 return V;
12479 }
12480
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012481 if (VecOp == RHS) {
12482 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012483 // Everything but the extracted element is replaced with the RHS.
12484 for (unsigned i = 0; i != NumElts; ++i) {
12485 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012486 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012487 }
12488 return V;
12489 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012490
12491 // If this insertelement is a chain that comes from exactly these two
12492 // vectors, return the vector and the effective shuffle.
12493 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12494 return EI->getOperand(0);
12495
Chris Lattnerefb47352006-04-15 01:39:45 +000012496 }
12497 }
12498 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012499 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012500
12501 // Otherwise, can't do anything fancy. Return an identity vector.
12502 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012503 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012504 return V;
12505}
12506
12507Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12508 Value *VecOp = IE.getOperand(0);
12509 Value *ScalarOp = IE.getOperand(1);
12510 Value *IdxOp = IE.getOperand(2);
12511
Chris Lattner599ded12007-04-09 01:11:16 +000012512 // Inserting an undef or into an undefined place, remove this.
12513 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12514 ReplaceInstUsesWith(IE, VecOp);
12515
Chris Lattnerefb47352006-04-15 01:39:45 +000012516 // If the inserted element was extracted from some other vector, and if the
12517 // indexes are constant, try to turn this into a shufflevector operation.
12518 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12519 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12520 EI->getOperand(0)->getType() == IE.getType()) {
12521 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012522 unsigned ExtractedIdx =
12523 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012524 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012525
12526 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12527 return ReplaceInstUsesWith(IE, VecOp);
12528
12529 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12530 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12531
12532 // If we are extracting a value from a vector, then inserting it right
12533 // back into the same place, just use the input vector.
12534 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12535 return ReplaceInstUsesWith(IE, VecOp);
12536
12537 // We could theoretically do this for ANY input. However, doing so could
12538 // turn chains of insertelement instructions into a chain of shufflevector
12539 // instructions, and right now we do not merge shufflevectors. As such,
12540 // only do this in a situation where it is clear that there is benefit.
12541 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12542 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12543 // the values of VecOp, except then one read from EIOp0.
12544 // Build a new shuffle mask.
12545 std::vector<Constant*> Mask;
12546 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012547 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012548 else {
12549 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012550 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012551 NumVectorElts));
12552 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012553 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012554 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012555 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012556 }
12557
12558 // If this insertelement isn't used by some other insertelement, turn it
12559 // (and any insertelements it points to), into one big shuffle.
12560 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12561 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012562 Value *RHS = 0;
12563 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12564 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12565 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012566 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012567 }
12568 }
12569 }
12570
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012571 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12572 APInt UndefElts(VWidth, 0);
12573 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12574 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12575 return &IE;
12576
Chris Lattnerefb47352006-04-15 01:39:45 +000012577 return 0;
12578}
12579
12580
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012581Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12582 Value *LHS = SVI.getOperand(0);
12583 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012584 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012585
12586 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012587
Chris Lattner867b99f2006-10-05 06:55:50 +000012588 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012589 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012590 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012591
Dan Gohman488fbfc2008-09-09 18:11:14 +000012592 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012593
12594 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12595 return 0;
12596
Evan Cheng388df622009-02-03 10:05:09 +000012597 APInt UndefElts(VWidth, 0);
12598 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12599 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012600 LHS = SVI.getOperand(0);
12601 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012602 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012603 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012604
Chris Lattner863bcff2006-05-25 23:48:38 +000012605 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12606 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12607 if (LHS == RHS || isa<UndefValue>(LHS)) {
12608 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012609 // shuffle(undef,undef,mask) -> undef.
12610 return ReplaceInstUsesWith(SVI, LHS);
12611 }
12612
Chris Lattner863bcff2006-05-25 23:48:38 +000012613 // Remap any references to RHS to use LHS.
12614 std::vector<Constant*> Elts;
12615 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012616 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012617 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012618 else {
12619 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012620 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012621 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012622 Elts.push_back(UndefValue::get(Type::Int32Ty));
12623 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012624 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012625 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12626 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012627 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012628 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012629 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012630 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012631 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012632 LHS = SVI.getOperand(0);
12633 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012634 MadeChange = true;
12635 }
12636
Chris Lattner7b2e27922006-05-26 00:29:06 +000012637 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012638 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012639
Chris Lattner863bcff2006-05-25 23:48:38 +000012640 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12641 if (Mask[i] >= e*2) continue; // Ignore undef values.
12642 // Is this an identity shuffle of the LHS value?
12643 isLHSID &= (Mask[i] == i);
12644
12645 // Is this an identity shuffle of the RHS value?
12646 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012647 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012648
Chris Lattner863bcff2006-05-25 23:48:38 +000012649 // Eliminate identity shuffles.
12650 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12651 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012652
Chris Lattner7b2e27922006-05-26 00:29:06 +000012653 // If the LHS is a shufflevector itself, see if we can combine it with this
12654 // one without producing an unusual shuffle. Here we are really conservative:
12655 // we are absolutely afraid of producing a shuffle mask not in the input
12656 // program, because the code gen may not be smart enough to turn a merged
12657 // shuffle into two specific shuffles: it may produce worse code. As such,
12658 // we only merge two shuffles if the result is one of the two input shuffle
12659 // masks. In this case, merging the shuffles just removes one instruction,
12660 // which we know is safe. This is good for things like turning:
12661 // (splat(splat)) -> splat.
12662 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12663 if (isa<UndefValue>(RHS)) {
12664 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12665
12666 std::vector<unsigned> NewMask;
12667 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12668 if (Mask[i] >= 2*e)
12669 NewMask.push_back(2*e);
12670 else
12671 NewMask.push_back(LHSMask[Mask[i]]);
12672
12673 // If the result mask is equal to the src shuffle or this shuffle mask, do
12674 // the replacement.
12675 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012676 unsigned LHSInNElts =
12677 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012678 std::vector<Constant*> Elts;
12679 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012680 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012681 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012682 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012683 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012684 }
12685 }
12686 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12687 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012688 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012689 }
12690 }
12691 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012692
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012693 return MadeChange ? &SVI : 0;
12694}
12695
12696
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012697
Chris Lattnerea1c4542004-12-08 23:43:58 +000012698
12699/// TryToSinkInstruction - Try to move the specified instruction from its
12700/// current block into the beginning of DestBlock, which can only happen if it's
12701/// safe to move the instruction past all of the instructions between it and the
12702/// end of its block.
12703static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12704 assert(I->hasOneUse() && "Invariants didn't hold!");
12705
Chris Lattner108e9022005-10-27 17:13:11 +000012706 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012707 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012708 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012709
Chris Lattnerea1c4542004-12-08 23:43:58 +000012710 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012711 if (isa<AllocaInst>(I) && I->getParent() ==
12712 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012713 return false;
12714
Chris Lattner96a52a62004-12-09 07:14:34 +000012715 // We can only sink load instructions if there is nothing between the load and
12716 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012717 if (I->mayReadFromMemory()) {
12718 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012719 Scan != E; ++Scan)
12720 if (Scan->mayWriteToMemory())
12721 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012722 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012723
Dan Gohman02dea8b2008-05-23 21:05:58 +000012724 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012725
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012726 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012727 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012728 ++NumSunkInst;
12729 return true;
12730}
12731
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012732
12733/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12734/// all reachable code to the worklist.
12735///
12736/// This has a couple of tricks to make the code faster and more powerful. In
12737/// particular, we constant fold and DCE instructions as we go, to avoid adding
12738/// them to the worklist (this significantly speeds up instcombine on code where
12739/// many instructions are dead or constant). Additionally, if we find a branch
12740/// whose condition is a known constant, we only visit the reachable successors.
12741///
12742static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012743 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012744 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012745 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012746 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012747 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012748
Chris Lattner2c7718a2007-03-23 19:17:18 +000012749 while (!Worklist.empty()) {
12750 BB = Worklist.back();
12751 Worklist.pop_back();
12752
12753 // We have now visited this block! If we've already been here, ignore it.
12754 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012755
12756 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012757 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12758 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012759
Chris Lattner2c7718a2007-03-23 19:17:18 +000012760 // DCE instruction if trivially dead.
12761 if (isInstructionTriviallyDead(Inst)) {
12762 ++NumDeadInst;
12763 DOUT << "IC: DCE: " << *Inst;
12764 Inst->eraseFromParent();
12765 continue;
12766 }
12767
12768 // ConstantProp instruction if trivially constant.
12769 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12770 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12771 Inst->replaceAllUsesWith(C);
12772 ++NumConstProp;
12773 Inst->eraseFromParent();
12774 continue;
12775 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012776
Devang Patel7fe1dec2008-11-19 18:56:50 +000012777 // If there are two consecutive llvm.dbg.stoppoint calls then
12778 // it is likely that the optimizer deleted code in between these
12779 // two intrinsics.
12780 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12781 if (DBI_Next) {
12782 if (DBI_Prev
12783 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12784 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12785 IC.RemoveFromWorkList(DBI_Prev);
12786 DBI_Prev->eraseFromParent();
12787 }
12788 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012789 } else {
12790 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012791 }
12792
Chris Lattner2c7718a2007-03-23 19:17:18 +000012793 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012794 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012795
12796 // Recursively visit successors. If this is a branch or switch on a
12797 // constant, only visit the reachable successor.
12798 TerminatorInst *TI = BB->getTerminator();
12799 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12800 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12801 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012802 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012803 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012804 continue;
12805 }
12806 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12807 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12808 // See if this is an explicit destination.
12809 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12810 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012811 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012812 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012813 continue;
12814 }
12815
12816 // Otherwise it is the default destination.
12817 Worklist.push_back(SI->getSuccessor(0));
12818 continue;
12819 }
12820 }
12821
12822 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12823 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012824 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012825}
12826
Chris Lattnerec9c3582007-03-03 02:04:50 +000012827bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012828 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012829 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012830
12831 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12832 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012833
Chris Lattnerb3d59702005-07-07 20:40:38 +000012834 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012835 // Do a depth-first traversal of the function, populate the worklist with
12836 // the reachable instructions. Ignore blocks that are not reachable. Keep
12837 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012838 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012839 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012840
Chris Lattnerb3d59702005-07-07 20:40:38 +000012841 // Do a quick scan over the function. If we find any blocks that are
12842 // unreachable, remove any instructions inside of them. This prevents
12843 // the instcombine code from having to deal with some bad special cases.
12844 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12845 if (!Visited.count(BB)) {
12846 Instruction *Term = BB->getTerminator();
12847 while (Term != BB->begin()) { // Remove instrs bottom-up
12848 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012849
Bill Wendlingb7427032006-11-26 09:46:52 +000012850 DOUT << "IC: DCE: " << *I;
Dale Johannesenff278b12009-03-10 21:19:49 +000012851 // A debug intrinsic shouldn't force another iteration if we weren't
12852 // going to do one without it.
12853 if (!isa<DbgInfoIntrinsic>(I)) {
12854 ++NumDeadInst;
12855 Changed = true;
12856 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012857 if (!I->use_empty())
12858 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12859 I->eraseFromParent();
12860 }
12861 }
12862 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012863
Chris Lattnerdbab3862007-03-02 21:28:56 +000012864 while (!Worklist.empty()) {
12865 Instruction *I = RemoveOneFromWorkList();
12866 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012867
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012868 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012869 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012870 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012871 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012872 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012873 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012874
Bill Wendlingb7427032006-11-26 09:46:52 +000012875 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012876
12877 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012878 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012879 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012880 continue;
12881 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012882
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012883 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012884 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012885 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012886
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012887 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012888 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012889 ReplaceInstUsesWith(*I, C);
12890
Chris Lattner62b14df2002-09-02 04:59:56 +000012891 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012892 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012893 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012894 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012895 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012896 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012897
Dan Gohman31e4c772009-05-07 19:43:39 +000012898 if (TD &&
12899 (I->getType()->getTypeID() == Type::VoidTyID ||
12900 I->isTrapping())) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012901 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012902 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12903 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012904 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012905 if (NewC != CE) {
12906 i->set(NewC);
12907 Changed = true;
12908 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012909 }
12910
Chris Lattnerea1c4542004-12-08 23:43:58 +000012911 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012912 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012913 BasicBlock *BB = I->getParent();
12914 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12915 if (UserParent != BB) {
12916 bool UserIsSuccessor = false;
12917 // See if the user is one of our successors.
12918 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12919 if (*SI == UserParent) {
12920 UserIsSuccessor = true;
12921 break;
12922 }
12923
12924 // If the user is one of our immediate successors, and if that successor
12925 // only has us as a predecessors (we'd have to split the critical edge
12926 // otherwise), we can keep going.
12927 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12928 next(pred_begin(UserParent)) == pred_end(UserParent))
12929 // Okay, the CFG is simple enough, try to sink this instruction.
12930 Changed |= TryToSinkInstruction(I, UserParent);
12931 }
12932 }
12933
Chris Lattner8a2a3112001-12-14 16:52:21 +000012934 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012935#ifndef NDEBUG
12936 std::string OrigI;
12937#endif
12938 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012939 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012940 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012941 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012942 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012943 DOUT << "IC: Old = " << *I
12944 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012945
Chris Lattnerf523d062004-06-09 05:08:07 +000012946 // Everything uses the new instruction now.
12947 I->replaceAllUsesWith(Result);
12948
12949 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012950 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012951 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012952
Chris Lattner6934a042007-02-11 01:23:03 +000012953 // Move the name to the new instruction first.
12954 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012955
12956 // Insert the new instruction into the basic block...
12957 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012958 BasicBlock::iterator InsertPos = I;
12959
12960 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12961 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12962 ++InsertPos;
12963
12964 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012965
Chris Lattner00d51312004-05-01 23:27:23 +000012966 // Make sure that we reprocess all operands now that we reduced their
12967 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012968 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012969
Chris Lattnerf523d062004-06-09 05:08:07 +000012970 // Instructions can end up on the worklist more than once. Make sure
12971 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012972 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012973
12974 // Erase the old instruction.
12975 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012976 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012977#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012978 DOUT << "IC: Mod = " << OrigI
12979 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012980#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012981
Chris Lattner90ac28c2002-08-02 19:29:35 +000012982 // If the instruction was modified, it's possible that it is now dead.
12983 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012984 if (isInstructionTriviallyDead(I)) {
12985 // Make sure we process all operands now that we are reducing their
12986 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012987 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012988
Chris Lattner00d51312004-05-01 23:27:23 +000012989 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012990 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012991 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012992 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012993 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012994 AddToWorkList(I);
12995 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012996 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012997 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012998 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012999 }
13000 }
13001
Chris Lattnerec9c3582007-03-03 02:04:50 +000013002 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000013003
13004 // Do an explicit clear, this shrinks the map if needed.
13005 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013006 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013007}
13008
Chris Lattnerec9c3582007-03-03 02:04:50 +000013009
13010bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013011 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13012
Chris Lattnerec9c3582007-03-03 02:04:50 +000013013 bool EverMadeChange = false;
13014
13015 // Iterate while there is work to do.
13016 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013017 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013018 EverMadeChange = true;
13019 return EverMadeChange;
13020}
13021
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013022FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013023 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013024}