blob: 7f7592840a4de6f08723aa5c566662143ba5218c [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);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000187 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200 Instruction *LHS,
201 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000204
Reid Spencere4d87aa2006-12-23 06:05:41 +0000205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000208 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000211 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000215 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000216 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000222 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000223 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225 Instruction *FI);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000232 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000233 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000234 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000235 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000236 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000237 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000238 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000242
243 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000245
Chris Lattner9fe38862003-06-19 17:00:31 +0000246 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000247 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000248 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000249 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000253
Chris Lattner28977af2004-04-05 01:30:19 +0000254 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000255 // InsertNewInstBefore - insert an instruction New before instruction Old
256 // in the program. Add the new instruction to the worklist.
257 //
Chris Lattner955f3312004-09-28 21:48:02 +0000258 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000259 assert(New && New->getParent() == 0 &&
260 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000261 BasicBlock *BB = Old.getParent();
262 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000263 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000264 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000265 }
266
Chris Lattner0c967662004-09-24 15:21:34 +0000267 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268 /// This also adds the cast to the worklist. Finally, this returns the
269 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000270 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000272 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000273
Chris Lattnere2ed0572006-04-06 19:19:17 +0000274 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000275 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000276
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000277 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000278 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000279 return C;
280 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000281
282 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284 }
285
Chris Lattner0c967662004-09-24 15:21:34 +0000286
Chris Lattner8b170942002-08-09 23:47:40 +0000287 // ReplaceInstUsesWith - This method is to be used when an instruction is
288 // found to be dead, replacable with another preexisting expression. Here
289 // we add all uses of I to the worklist, replace all uses of I with the new
290 // value, then return I, so that the inst combiner will know that I was
291 // modified.
292 //
293 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000294 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000295 if (&I != V) {
296 I.replaceAllUsesWith(V);
297 return &I;
298 } else {
299 // If we are replacing the instruction with itself, this must be in a
300 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000301 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000302 return &I;
303 }
Chris Lattner8b170942002-08-09 23:47:40 +0000304 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000305
Chris Lattner6dce1a72006-02-07 06:56:34 +0000306 // UpdateValueUsesWith - This method is to be used when an value is
307 // found to be replacable with another preexisting expression or was
308 // updated. Here we add all uses of I to the worklist, replace all uses of
309 // I with the new value (unless the instruction was just updated), then
310 // return true, so that the inst combiner will know that I was modified.
311 //
312 bool UpdateValueUsesWith(Value *Old, Value *New) {
313 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
314 if (Old != New)
315 Old->replaceAllUsesWith(New);
316 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000317 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000318 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000319 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000320 return true;
321 }
322
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000323 // EraseInstFromFunction - When dealing with an instruction that has side
324 // effects or produces a void value, we can't rely on DCE to delete the
325 // instruction. Instead, visit methods should return the value returned by
326 // this function.
327 Instruction *EraseInstFromFunction(Instruction &I) {
328 assert(I.use_empty() && "Cannot erase instruction that is used!");
329 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000330 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000331 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000332 return 0; // Don't do anything with FI
333 }
Chris Lattner173234a2008-06-02 01:18:21 +0000334
335 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
336 APInt &KnownOne, unsigned Depth = 0) const {
337 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
338 }
339
340 bool MaskedValueIsZero(Value *V, const APInt &Mask,
341 unsigned Depth = 0) const {
342 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
343 }
344 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
345 return llvm::ComputeNumSignBits(Op, TD, Depth);
346 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000347
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000348 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000349
Reid Spencere4d87aa2006-12-23 06:05:41 +0000350 /// SimplifyCommutative - This performs a few simplifications for
351 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000352 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000353
Reid Spencere4d87aa2006-12-23 06:05:41 +0000354 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355 /// most-complex to least-complex order.
356 bool SimplifyCompare(CmpInst &I);
357
Reid Spencer2ec619a2007-03-23 21:24:59 +0000358 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000360 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
361 APInt& KnownZero, APInt& KnownOne,
362 unsigned Depth = 0);
363
Chris Lattner867b99f2006-10-05 06:55:50 +0000364 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365 uint64_t &UndefElts, unsigned Depth = 0);
366
Chris Lattner4e998b22004-09-29 05:07:12 +0000367 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368 // PHI node as operand #0, see if we can fold the instruction into the PHI
369 // (which is only possible if all operands to the PHI are constants).
370 Instruction *FoldOpIntoPhi(Instruction &I);
371
Chris Lattnerbac32862004-11-14 19:13:23 +0000372 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373 // operator and they all are only used by the PHI, PHI together their
374 // inputs, and do the operation once, to the result of the PHI.
375 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000376 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000377 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
378
Chris Lattner7da52b22006-11-01 04:51:18 +0000379
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000382
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000384 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000386 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000388 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000391 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000392
Chris Lattnerafe91a52006-06-15 19:07:26 +0000393
Reid Spencerc55b2432006-12-13 18:21:21 +0000394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000395
Dan Gohmaneee962e2008-04-10 18:43:06 +0000396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000397 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000398 unsigned GetOrEnforceKnownAlignment(Value *V,
399 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000400
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000401 };
402}
403
Dan Gohman844731a2008-05-13 00:00:25 +0000404char InstCombiner::ID = 0;
405static RegisterPass<InstCombiner>
406X("instcombine", "Combine redundant instructions");
407
Chris Lattner4f98c562003-03-10 21:43:22 +0000408// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000409// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000410static unsigned getComplexity(Value *V) {
411 if (isa<Instruction>(V)) {
412 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000413 return 3;
414 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000415 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000416 if (isa<Argument>(V)) return 3;
417 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000418}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000419
Chris Lattnerc8802d22003-03-11 00:12:48 +0000420// isOnlyUse - Return true if this instruction will be deleted if we stop using
421// it.
422static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000423 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000424}
425
Chris Lattner4cb170c2004-02-23 06:38:22 +0000426// getPromotedType - Return the specified type promoted as it would be to pass
427// though a va_arg area...
428static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000429 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
430 if (ITy->getBitWidth() < 32)
431 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000432 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000433 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000434}
435
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000436/// getBitCastOperand - If the specified operand is a CastInst, a constant
437/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
438/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000439static Value *getBitCastOperand(Value *V) {
440 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000441 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000442 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
444 // GetElementPtrInst?
445 if (GEP->hasAllZeroIndices())
446 return GEP->getOperand(0);
447 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000448 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000449 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000450 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000451 else if (CE->getOpcode() == Instruction::GetElementPtr) {
452 // GetElementPtr ConstantExp?
453 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
454 I != E; ++I) {
455 ConstantInt *CI = dyn_cast<ConstantInt>(I);
456 if (!CI || !CI->isZero())
457 // Any non-zero indices? Not cast-like.
458 return 0;
459 }
460 // All-zero indices? This is just like casting.
461 return CE->getOperand(0);
462 }
463 }
Chris Lattnereed48272005-09-13 00:40:14 +0000464 return 0;
465}
466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467/// This function is a wrapper around CastInst::isEliminableCastPair. It
468/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000469static Instruction::CastOps
470isEliminableCastPair(
471 const CastInst *CI, ///< The first cast instruction
472 unsigned opcode, ///< The opcode of the second cast instruction
473 const Type *DstTy, ///< The target type for the second cast instruction
474 TargetData *TD ///< The target data for pointer size
475) {
476
477 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
478 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000479
Reid Spencer3da59db2006-11-27 01:05:10 +0000480 // Get the opcodes of the two Cast instructions
481 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
482 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000483
Reid Spencer3da59db2006-11-27 01:05:10 +0000484 return Instruction::CastOps(
485 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000487}
488
489/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490/// in any code being generated. It does not require codegen if V is simple
491/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000492static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
493 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000494 if (V->getType() == Ty || isa<Constant>(V)) return false;
495
Chris Lattner01575b72006-05-25 23:24:33 +0000496 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000497 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000498 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000499 return false;
500 return true;
501}
502
Chris Lattner4f98c562003-03-10 21:43:22 +0000503// SimplifyCommutative - This performs a few simplifications for commutative
504// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000505//
Chris Lattner4f98c562003-03-10 21:43:22 +0000506// 1. Order operands such that they are listed from right (least complex) to
507// left (most complex). This puts constants before unary operators before
508// binary operators.
509//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000510// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000512//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000513bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000514 bool Changed = false;
515 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
516 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000517
Chris Lattner4f98c562003-03-10 21:43:22 +0000518 if (!I.isAssociative()) return Changed;
519 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000523 Constant *Folded = ConstantExpr::get(I.getOpcode(),
524 cast<Constant>(I.getOperand(1)),
525 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000526 I.setOperand(0, Op->getOperand(0));
527 I.setOperand(1, Folded);
528 return true;
529 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531 isOnlyUse(Op) && isOnlyUse(Op1)) {
532 Constant *C1 = cast<Constant>(Op->getOperand(1));
533 Constant *C2 = cast<Constant>(Op1->getOperand(1));
534
535 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000536 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000537 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538 Op1->getOperand(0),
539 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000540 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541 I.setOperand(0, New);
542 I.setOperand(1, Folded);
543 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000544 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000545 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000546 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000547}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000548
Reid Spencere4d87aa2006-12-23 06:05:41 +0000549/// SimplifyCompare - For a CmpInst this function just orders the operands
550/// so that theyare listed from right (least complex) to left (most complex).
551/// This puts constants before unary operators before binary operators.
552bool InstCombiner::SimplifyCompare(CmpInst &I) {
553 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
Chris Lattner8d969642003-03-10 23:06:50 +0000560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000562//
Chris Lattner8d969642003-03-10 23:06:50 +0000563static inline Value *dyn_castNegVal(Value *V) {
564 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000565 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000566
Chris Lattner0ce85802004-12-14 20:08:06 +0000567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
573 return ConstantExpr::getNeg(C);
574
Chris Lattner8d969642003-03-10 23:06:50 +0000575 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000576}
577
Chris Lattner8d969642003-03-10 23:06:50 +0000578static inline Value *dyn_castNotVal(Value *V) {
579 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000580 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000581
582 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000583 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000584 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000585 return 0;
586}
587
Chris Lattnerc8802d22003-03-11 00:12:48 +0000588// dyn_castFoldableMul - If this value is a multiply that can be folded into
589// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000590// non-constant operand of the multiply, and set CST to point to the multiplier.
591// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000592//
Chris Lattner50af16a2004-11-13 19:50:12 +0000593static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000594 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000595 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000596 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000597 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000598 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000599 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000600 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000601 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000602 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000603 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000604 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000605 return I->getOperand(0);
606 }
607 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000608 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000609}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000610
Chris Lattner574da9b2005-01-13 20:14:25 +0000611/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
612/// expression, return it.
613static User *dyn_castGetElementPtr(Value *V) {
614 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
615 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
616 if (CE->getOpcode() == Instruction::GetElementPtr)
617 return cast<User>(V);
618 return false;
619}
620
Dan Gohmaneee962e2008-04-10 18:43:06 +0000621/// getOpcode - If this is an Instruction or a ConstantExpr, return the
622/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000623static unsigned getOpcode(const Value *V) {
624 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000625 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000626 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000627 return CE->getOpcode();
628 // Use UserOp1 to mean there's no opcode.
629 return Instruction::UserOp1;
630}
631
Reid Spencer7177c3a2007-03-25 05:33:51 +0000632/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000633static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000634 APInt Val(C->getValue());
635 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000636}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000637/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000638static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000639 APInt Val(C->getValue());
640 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000641}
642/// Add - Add two ConstantInts together
643static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() + C2->getValue());
645}
646/// And - Bitwise AND two ConstantInts together
647static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() & C2->getValue());
649}
650/// Subtract - Subtract one ConstantInt from another
651static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() - C2->getValue());
653}
654/// Multiply - Multiply two ConstantInts together
655static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
656 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000657}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000658/// MultiplyOverflows - True if the multiply can not be expressed in an int
659/// this size.
660static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
661 uint32_t W = C1->getBitWidth();
662 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
663 if (sign) {
664 LHSExt.sext(W * 2);
665 RHSExt.sext(W * 2);
666 } else {
667 LHSExt.zext(W * 2);
668 RHSExt.zext(W * 2);
669 }
670
671 APInt MulExt = LHSExt * RHSExt;
672
673 if (sign) {
674 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
675 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
676 return MulExt.slt(Min) || MulExt.sgt(Max);
677 } else
678 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
679}
Chris Lattner955f3312004-09-28 21:48:02 +0000680
Reid Spencere7816b52007-03-08 01:52:58 +0000681
Chris Lattner255d8912006-02-11 09:31:47 +0000682/// ShrinkDemandedConstant - Check to see if the specified operand of the
683/// specified instruction is a constant integer. If so, check to see if there
684/// are any bits set in the constant that are not demanded. If so, shrink the
685/// constant and return true.
686static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000687 APInt Demanded) {
688 assert(I && "No instruction?");
689 assert(OpNo < I->getNumOperands() && "Operand index too large");
690
691 // If the operand is not a constant integer, nothing to do.
692 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
693 if (!OpC) return false;
694
695 // If there are no bits set that aren't demanded, nothing to do.
696 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
697 if ((~Demanded & OpC->getValue()) == 0)
698 return false;
699
700 // This instruction is producing bits that are not demanded. Shrink the RHS.
701 Demanded &= OpC->getValue();
702 I->setOperand(OpNo, ConstantInt::get(Demanded));
703 return true;
704}
705
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000706// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
707// set of known zero and one bits, compute the maximum and minimum values that
708// could have the specified known zero and known one bits, returning them in
709// min/max.
710static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000711 const APInt& KnownZero,
712 const APInt& KnownOne,
713 APInt& Min, APInt& Max) {
714 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
715 assert(KnownZero.getBitWidth() == BitWidth &&
716 KnownOne.getBitWidth() == BitWidth &&
717 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
718 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000719 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
722 // bit if it is unknown.
723 Min = KnownOne;
724 Max = KnownOne|UnknownBits;
725
Zhou Sheng4acf1552007-03-28 05:15:57 +0000726 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000727 Min.set(BitWidth-1);
728 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000729 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000730}
731
732// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
733// a set of known zero and one bits, compute the maximum and minimum values that
734// could have the specified known zero and known one bits, returning them in
735// min/max.
736static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000737 const APInt &KnownZero,
738 const APInt &KnownOne,
739 APInt &Min, APInt &Max) {
740 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000741 assert(KnownZero.getBitWidth() == BitWidth &&
742 KnownOne.getBitWidth() == BitWidth &&
743 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
744 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000745 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000746
747 // The minimum value is when the unknown bits are all zeros.
748 Min = KnownOne;
749 // The maximum value is when the unknown bits are all ones.
750 Max = KnownOne|UnknownBits;
751}
Chris Lattner255d8912006-02-11 09:31:47 +0000752
Reid Spencer8cb68342007-03-12 17:25:59 +0000753/// SimplifyDemandedBits - This function attempts to replace V with a simpler
754/// value based on the demanded bits. When this function is called, it is known
755/// that only the bits set in DemandedMask of the result of V are ever used
756/// downstream. Consequently, depending on the mask and V, it may be possible
757/// to replace V with a constant or one of its operands. In such cases, this
758/// function does the replacement and returns true. In all other cases, it
759/// returns false after analyzing the expression and setting KnownOne and known
760/// to be one in the expression. KnownZero contains all the bits that are known
761/// to be zero in the expression. These are provided to potentially allow the
762/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
763/// the expression. KnownOne and KnownZero always follow the invariant that
764/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
765/// the bits in KnownOne and KnownZero may only be accurate for those bits set
766/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
767/// and KnownOne must all be the same.
768bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
769 APInt& KnownZero, APInt& KnownOne,
770 unsigned Depth) {
771 assert(V != 0 && "Null pointer of Value???");
772 assert(Depth <= 6 && "Limit Search Depth");
773 uint32_t BitWidth = DemandedMask.getBitWidth();
774 const IntegerType *VTy = cast<IntegerType>(V->getType());
775 assert(VTy->getBitWidth() == BitWidth &&
776 KnownZero.getBitWidth() == BitWidth &&
777 KnownOne.getBitWidth() == BitWidth &&
778 "Value *V, DemandedMask, KnownZero and KnownOne \
779 must have same BitWidth");
780 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
781 // We know all of the bits for a constant!
782 KnownOne = CI->getValue() & DemandedMask;
783 KnownZero = ~KnownOne & DemandedMask;
784 return false;
785 }
786
Zhou Sheng96704452007-03-14 03:21:24 +0000787 KnownZero.clear();
788 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000789 if (!V->hasOneUse()) { // Other users may use these bits.
790 if (Depth != 0) { // Not at the root.
791 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
792 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
793 return false;
794 }
795 // If this is the root being simplified, allow it to have multiple uses,
796 // just set the DemandedMask to all bits.
797 DemandedMask = APInt::getAllOnesValue(BitWidth);
798 } else if (DemandedMask == 0) { // Not demanding any bits from V.
799 if (V != UndefValue::get(VTy))
800 return UpdateValueUsesWith(V, UndefValue::get(VTy));
801 return false;
802 } else if (Depth == 6) { // Limit search depth.
803 return false;
804 }
805
806 Instruction *I = dyn_cast<Instruction>(V);
807 if (!I) return false; // Only analyze instructions.
808
Reid Spencer8cb68342007-03-12 17:25:59 +0000809 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
810 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
811 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000812 default:
813 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
814 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000815 case Instruction::And:
816 // If either the LHS or the RHS are Zero, the result is zero.
817 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
818 RHSKnownZero, RHSKnownOne, Depth+1))
819 return true;
820 assert((RHSKnownZero & RHSKnownOne) == 0 &&
821 "Bits known to be one AND zero?");
822
823 // If something is known zero on the RHS, the bits aren't demanded on the
824 // LHS.
825 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
826 LHSKnownZero, LHSKnownOne, Depth+1))
827 return true;
828 assert((LHSKnownZero & LHSKnownOne) == 0 &&
829 "Bits known to be one AND zero?");
830
831 // If all of the demanded bits are known 1 on one side, return the other.
832 // These bits cannot contribute to the result of the 'and'.
833 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
834 (DemandedMask & ~LHSKnownZero))
835 return UpdateValueUsesWith(I, I->getOperand(0));
836 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
837 (DemandedMask & ~RHSKnownZero))
838 return UpdateValueUsesWith(I, I->getOperand(1));
839
840 // If all of the demanded bits in the inputs are known zeros, return zero.
841 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
842 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
843
844 // If the RHS is a constant, see if we can simplify it.
845 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
846 return UpdateValueUsesWith(I, I);
847
848 // Output known-1 bits are only known if set in both the LHS & RHS.
849 RHSKnownOne &= LHSKnownOne;
850 // Output known-0 are known to be clear if zero in either the LHS | RHS.
851 RHSKnownZero |= LHSKnownZero;
852 break;
853 case Instruction::Or:
854 // If either the LHS or the RHS are One, the result is One.
855 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856 RHSKnownZero, RHSKnownOne, Depth+1))
857 return true;
858 assert((RHSKnownZero & RHSKnownOne) == 0 &&
859 "Bits known to be one AND zero?");
860 // If something is known one on the RHS, the bits aren't demanded on the
861 // LHS.
862 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
863 LHSKnownZero, LHSKnownOne, Depth+1))
864 return true;
865 assert((LHSKnownZero & LHSKnownOne) == 0 &&
866 "Bits known to be one AND zero?");
867
868 // If all of the demanded bits are known zero on one side, return the other.
869 // These bits cannot contribute to the result of the 'or'.
870 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
871 (DemandedMask & ~LHSKnownOne))
872 return UpdateValueUsesWith(I, I->getOperand(0));
873 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
874 (DemandedMask & ~RHSKnownOne))
875 return UpdateValueUsesWith(I, I->getOperand(1));
876
877 // If all of the potentially set bits on one side are known to be set on
878 // the other side, just use the 'other' side.
879 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
880 (DemandedMask & (~RHSKnownZero)))
881 return UpdateValueUsesWith(I, I->getOperand(0));
882 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
883 (DemandedMask & (~LHSKnownZero)))
884 return UpdateValueUsesWith(I, I->getOperand(1));
885
886 // If the RHS is a constant, see if we can simplify it.
887 if (ShrinkDemandedConstant(I, 1, DemandedMask))
888 return UpdateValueUsesWith(I, I);
889
890 // Output known-0 bits are only known if clear in both the LHS & RHS.
891 RHSKnownZero &= LHSKnownZero;
892 // Output known-1 are known to be set if set in either the LHS | RHS.
893 RHSKnownOne |= LHSKnownOne;
894 break;
895 case Instruction::Xor: {
896 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
897 RHSKnownZero, RHSKnownOne, Depth+1))
898 return true;
899 assert((RHSKnownZero & RHSKnownOne) == 0 &&
900 "Bits known to be one AND zero?");
901 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
902 LHSKnownZero, LHSKnownOne, Depth+1))
903 return true;
904 assert((LHSKnownZero & LHSKnownOne) == 0 &&
905 "Bits known to be one AND zero?");
906
907 // If all of the demanded bits are known zero on one side, return the other.
908 // These bits cannot contribute to the result of the 'xor'.
909 if ((DemandedMask & RHSKnownZero) == DemandedMask)
910 return UpdateValueUsesWith(I, I->getOperand(0));
911 if ((DemandedMask & LHSKnownZero) == DemandedMask)
912 return UpdateValueUsesWith(I, I->getOperand(1));
913
914 // Output known-0 bits are known if clear or set in both the LHS & RHS.
915 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
916 (RHSKnownOne & LHSKnownOne);
917 // Output known-1 are known to be set if set in only one of the LHS, RHS.
918 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
919 (RHSKnownOne & LHSKnownZero);
920
921 // If all of the demanded bits are known to be zero on one side or the
922 // other, turn this into an *inclusive* or.
923 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
924 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
925 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000926 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +0000927 I->getName());
928 InsertNewInstBefore(Or, *I);
929 return UpdateValueUsesWith(I, Or);
930 }
931
932 // If all of the demanded bits on one side are known, and all of the set
933 // bits on that side are also known to be set on the other side, turn this
934 // into an AND, as we know the bits will be cleared.
935 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
936 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
937 // all known
938 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
939 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
940 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000941 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 InsertNewInstBefore(And, *I);
943 return UpdateValueUsesWith(I, And);
944 }
945 }
946
947 // If the RHS is a constant, see if we can simplify it.
948 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
949 if (ShrinkDemandedConstant(I, 1, DemandedMask))
950 return UpdateValueUsesWith(I, I);
951
952 RHSKnownZero = KnownZeroOut;
953 RHSKnownOne = KnownOneOut;
954 break;
955 }
956 case Instruction::Select:
957 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
958 RHSKnownZero, RHSKnownOne, Depth+1))
959 return true;
960 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
961 LHSKnownZero, LHSKnownOne, Depth+1))
962 return true;
963 assert((RHSKnownZero & RHSKnownOne) == 0 &&
964 "Bits known to be one AND zero?");
965 assert((LHSKnownZero & LHSKnownOne) == 0 &&
966 "Bits known to be one AND zero?");
967
968 // If the operands are constants, see if we can simplify them.
969 if (ShrinkDemandedConstant(I, 1, DemandedMask))
970 return UpdateValueUsesWith(I, I);
971 if (ShrinkDemandedConstant(I, 2, DemandedMask))
972 return UpdateValueUsesWith(I, I);
973
974 // Only known if known in both the LHS and RHS.
975 RHSKnownOne &= LHSKnownOne;
976 RHSKnownZero &= LHSKnownZero;
977 break;
978 case Instruction::Trunc: {
979 uint32_t truncBf =
980 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +0000981 DemandedMask.zext(truncBf);
982 RHSKnownZero.zext(truncBf);
983 RHSKnownOne.zext(truncBf);
984 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
985 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +0000986 return true;
987 DemandedMask.trunc(BitWidth);
988 RHSKnownZero.trunc(BitWidth);
989 RHSKnownOne.trunc(BitWidth);
990 assert((RHSKnownZero & RHSKnownOne) == 0 &&
991 "Bits known to be one AND zero?");
992 break;
993 }
994 case Instruction::BitCast:
995 if (!I->getOperand(0)->getType()->isInteger())
996 return false;
997
998 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999 RHSKnownZero, RHSKnownOne, Depth+1))
1000 return true;
1001 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1002 "Bits known to be one AND zero?");
1003 break;
1004 case Instruction::ZExt: {
1005 // Compute the bits in the result that are not present in the input.
1006 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001007 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001008
Zhou Shengd48653a2007-03-29 04:45:55 +00001009 DemandedMask.trunc(SrcBitWidth);
1010 RHSKnownZero.trunc(SrcBitWidth);
1011 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001012 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1013 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 return true;
1015 DemandedMask.zext(BitWidth);
1016 RHSKnownZero.zext(BitWidth);
1017 RHSKnownOne.zext(BitWidth);
1018 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1019 "Bits known to be one AND zero?");
1020 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001021 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001022 break;
1023 }
1024 case Instruction::SExt: {
1025 // Compute the bits in the result that are not present in the input.
1026 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001027 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
Reid Spencer8cb68342007-03-12 17:25:59 +00001029 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001030 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001031
Zhou Sheng01542f32007-03-29 02:26:30 +00001032 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001033 // If any of the sign extended bits are demanded, we know that the sign
1034 // bit is demanded.
1035 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001036 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001037
Zhou Shengd48653a2007-03-29 04:45:55 +00001038 InputDemandedBits.trunc(SrcBitWidth);
1039 RHSKnownZero.trunc(SrcBitWidth);
1040 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001041 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1042 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001043 return true;
1044 InputDemandedBits.zext(BitWidth);
1045 RHSKnownZero.zext(BitWidth);
1046 RHSKnownOne.zext(BitWidth);
1047 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1048 "Bits known to be one AND zero?");
1049
1050 // If the sign bit of the input is known set or clear, then we know the
1051 // top bits of the result.
1052
1053 // If the input sign bit is known zero, or if the NewBits are not demanded
1054 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001055 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001056 {
1057 // Convert to ZExt cast
1058 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1059 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001060 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001061 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001062 }
1063 break;
1064 }
1065 case Instruction::Add: {
1066 // Figure out what the input bits are. If the top bits of the and result
1067 // are not demanded, then the add doesn't demand them from its input
1068 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001069 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001070
1071 // If there is a constant on the RHS, there are a variety of xformations
1072 // we can do.
1073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1074 // If null, this should be simplified elsewhere. Some of the xforms here
1075 // won't work if the RHS is zero.
1076 if (RHS->isZero())
1077 break;
1078
1079 // If the top bit of the output is demanded, demand everything from the
1080 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001081 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001082
1083 // Find information about known zero/one bits in the input.
1084 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1085 LHSKnownZero, LHSKnownOne, Depth+1))
1086 return true;
1087
1088 // If the RHS of the add has bits set that can't affect the input, reduce
1089 // the constant.
1090 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1091 return UpdateValueUsesWith(I, I);
1092
1093 // Avoid excess work.
1094 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1095 break;
1096
1097 // Turn it into OR if input bits are zero.
1098 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1099 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001100 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001101 I->getName());
1102 InsertNewInstBefore(Or, *I);
1103 return UpdateValueUsesWith(I, Or);
1104 }
1105
1106 // We can say something about the output known-zero and known-one bits,
1107 // depending on potential carries from the input constant and the
1108 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1109 // bits set and the RHS constant is 0x01001, then we know we have a known
1110 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1111
1112 // To compute this, we first compute the potential carry bits. These are
1113 // the bits which may be modified. I'm not aware of a better way to do
1114 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001115 const APInt& RHSVal = RHS->getValue();
1116 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001117
1118 // Now that we know which bits have carries, compute the known-1/0 sets.
1119
1120 // Bits are known one if they are known zero in one operand and one in the
1121 // other, and there is no input carry.
1122 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1123 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1124
1125 // Bits are known zero if they are known zero in both operands and there
1126 // is no input carry.
1127 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1128 } else {
1129 // If the high-bits of this ADD are not demanded, then it does not demand
1130 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001131 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001132 // Right fill the mask of bits for this ADD to demand the most
1133 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001134 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1136 LHSKnownZero, LHSKnownOne, Depth+1))
1137 return true;
1138 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1139 LHSKnownZero, LHSKnownOne, Depth+1))
1140 return true;
1141 }
1142 }
1143 break;
1144 }
1145 case Instruction::Sub:
1146 // If the high-bits of this SUB are not demanded, then it does not demand
1147 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001148 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001149 // Right fill the mask of bits for this SUB to demand the most
1150 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001151 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001152 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001153 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1154 LHSKnownZero, LHSKnownOne, Depth+1))
1155 return true;
1156 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1157 LHSKnownZero, LHSKnownOne, Depth+1))
1158 return true;
1159 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001160 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1161 // the known zeros and ones.
1162 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 break;
1164 case Instruction::Shl:
1165 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001166 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001167 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1168 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001169 RHSKnownZero, RHSKnownOne, Depth+1))
1170 return true;
1171 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1172 "Bits known to be one AND zero?");
1173 RHSKnownZero <<= ShiftAmt;
1174 RHSKnownOne <<= ShiftAmt;
1175 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001176 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001177 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001178 }
1179 break;
1180 case Instruction::LShr:
1181 // For a logical shift right
1182 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001183 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001184
Reid Spencer8cb68342007-03-12 17:25:59 +00001185 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001186 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1187 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 RHSKnownZero, RHSKnownOne, Depth+1))
1189 return true;
1190 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1191 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1193 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001194 if (ShiftAmt) {
1195 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001196 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001197 RHSKnownZero |= HighBits; // high bits known zero.
1198 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 }
1200 break;
1201 case Instruction::AShr:
1202 // If this is an arithmetic shift right and only the low-bit is set, we can
1203 // always convert this into a logical shr, even if the shift amount is
1204 // variable. The low bit of the shift cannot be an input sign bit unless
1205 // the shift amount is >= the size of the datatype, which is undefined.
1206 if (DemandedMask == 1) {
1207 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001208 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 I->getOperand(0), I->getOperand(1), I->getName());
1210 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1211 return UpdateValueUsesWith(I, NewVal);
1212 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001213
1214 // If the sign bit is the only bit demanded by this ashr, then there is no
1215 // need to do it, the shift doesn't change the high bit.
1216 if (DemandedMask.isSignBit())
1217 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001218
1219 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001220 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001221
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001223 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001224 // If any of the "high bits" are demanded, we should set the sign bit as
1225 // demanded.
1226 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1227 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001229 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001230 RHSKnownZero, RHSKnownOne, Depth+1))
1231 return true;
1232 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1233 "Bits known to be one AND zero?");
1234 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001235 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1237 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1238
1239 // Handle the sign bits.
1240 APInt SignBit(APInt::getSignBit(BitWidth));
1241 // Adjust to where it is now in the mask.
1242 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1243
1244 // If the input sign bit is known to be zero, or if none of the top bits
1245 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001246 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001247 (HighBits & ~DemandedMask) == HighBits) {
1248 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001249 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 I->getOperand(0), SA, I->getName());
1251 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1252 return UpdateValueUsesWith(I, NewVal);
1253 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1254 RHSKnownOne |= HighBits;
1255 }
1256 }
1257 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001258 case Instruction::SRem:
1259 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001260 APInt RA = Rem->getValue().abs();
1261 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001262 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1263 return UpdateValueUsesWith(I, I->getOperand(0));
1264
Nick Lewycky8e394322008-11-02 02:41:50 +00001265 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001266 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1267 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1268 LHSKnownZero, LHSKnownOne, Depth+1))
1269 return true;
1270
1271 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1272 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001273
1274 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001275
1276 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1277 }
1278 }
1279 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001280 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001281 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1282 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001283 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1284 KnownZero2, KnownOne2, Depth+1))
1285 return true;
1286
Chris Lattner455e9ab2009-01-21 18:09:24 +00001287 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001288 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001289 KnownZero2, KnownOne2, Depth+1))
1290 return true;
1291
1292 Leaders = std::max(Leaders,
1293 KnownZero2.countLeadingOnes());
1294 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001295 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001296 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001297 case Instruction::Call:
1298 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1299 switch (II->getIntrinsicID()) {
1300 default: break;
1301 case Intrinsic::bswap: {
1302 // If the only bits demanded come from one byte of the bswap result,
1303 // just shift the input byte into position to eliminate the bswap.
1304 unsigned NLZ = DemandedMask.countLeadingZeros();
1305 unsigned NTZ = DemandedMask.countTrailingZeros();
1306
1307 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1308 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1309 // have 14 leading zeros, round to 8.
1310 NLZ &= ~7;
1311 NTZ &= ~7;
1312 // If we need exactly one byte, we can do this transformation.
1313 if (BitWidth-NLZ-NTZ == 8) {
1314 unsigned ResultBit = NTZ;
1315 unsigned InputBit = BitWidth-NTZ-8;
1316
1317 // Replace this with either a left or right shift to get the byte into
1318 // the right place.
1319 Instruction *NewVal;
1320 if (InputBit > ResultBit)
1321 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1322 ConstantInt::get(I->getType(), InputBit-ResultBit));
1323 else
1324 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1325 ConstantInt::get(I->getType(), ResultBit-InputBit));
1326 NewVal->takeName(I);
1327 InsertNewInstBefore(NewVal, *I);
1328 return UpdateValueUsesWith(I, NewVal);
1329 }
1330
1331 // TODO: Could compute known zero/one bits based on the input.
1332 break;
1333 }
1334 }
1335 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001336 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001337 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001338 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001339
1340 // If the client is only demanding bits that we know, return the known
1341 // constant.
1342 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1343 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1344 return false;
1345}
1346
Chris Lattner867b99f2006-10-05 06:55:50 +00001347
Mon P Wangaeb06d22008-11-10 04:46:22 +00001348/// SimplifyDemandedVectorElts - The specified value produces a vector with
Chris Lattner867b99f2006-10-05 06:55:50 +00001349/// 64 or fewer elements. DemandedElts contains the set of elements that are
1350/// actually used by the caller. This method analyzes which elements of the
1351/// operand are undef and returns that information in UndefElts.
1352///
1353/// If the information about demanded elements can be used to simplify the
1354/// operation, the operation is simplified, then the resultant value is
1355/// returned. This returns null if no change was made.
1356Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1357 uint64_t &UndefElts,
1358 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001359 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001360 assert(VWidth <= 64 && "Vector too wide to analyze!");
1361 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001362 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001363
1364 if (isa<UndefValue>(V)) {
1365 // If the entire vector is undefined, just return this info.
1366 UndefElts = EltMask;
1367 return 0;
1368 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1369 UndefElts = EltMask;
1370 return UndefValue::get(V->getType());
1371 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001372
Chris Lattner867b99f2006-10-05 06:55:50 +00001373 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001374 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1375 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001376 Constant *Undef = UndefValue::get(EltTy);
1377
1378 std::vector<Constant*> Elts;
1379 for (unsigned i = 0; i != VWidth; ++i)
1380 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1384 Elts.push_back(Undef);
1385 UndefElts |= (1ULL << i);
1386 } else { // Otherwise, defined.
1387 Elts.push_back(CP->getOperand(i));
1388 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001389
Chris Lattner867b99f2006-10-05 06:55:50 +00001390 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001391 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001392 return NewCP != CP ? NewCP : 0;
1393 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001394 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001395 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001396
1397 // Check if this is identity. If so, return 0 since we are not simplifying
1398 // anything.
1399 if (DemandedElts == ((1ULL << VWidth) -1))
1400 return 0;
1401
Reid Spencer9d6565a2007-02-15 02:26:10 +00001402 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001403 Constant *Zero = Constant::getNullValue(EltTy);
1404 Constant *Undef = UndefValue::get(EltTy);
1405 std::vector<Constant*> Elts;
1406 for (unsigned i = 0; i != VWidth; ++i)
1407 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1408 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001409 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001410 }
1411
Dan Gohman488fbfc2008-09-09 18:11:14 +00001412 // Limit search depth.
1413 if (Depth == 10)
1414 return false;
1415
1416 // If multiple users are using the root value, procede with
1417 // simplification conservatively assuming that all elements
1418 // are needed.
1419 if (!V->hasOneUse()) {
1420 // Quit if we find multiple users of a non-root value though.
1421 // They'll be handled when it's their turn to be visited by
1422 // the main instcombine process.
1423 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001424 // TODO: Just compute the UndefElts information recursively.
1425 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001426
1427 // Conservatively assume that all elements are needed.
1428 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001429 }
1430
1431 Instruction *I = dyn_cast<Instruction>(V);
1432 if (!I) return false; // Only analyze instructions.
1433
1434 bool MadeChange = false;
1435 uint64_t UndefElts2;
1436 Value *TmpV;
1437 switch (I->getOpcode()) {
1438 default: break;
1439
1440 case Instruction::InsertElement: {
1441 // If this is a variable index, we don't know which element it overwrites.
1442 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001443 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001444 if (Idx == 0) {
1445 // Note that we can't propagate undef elt info, because we don't know
1446 // which elt is getting updated.
1447 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1448 UndefElts2, Depth+1);
1449 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1450 break;
1451 }
1452
1453 // If this is inserting an element that isn't demanded, remove this
1454 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001455 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001456 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1457 return AddSoonDeadInstToWorklist(*I, 0);
1458
1459 // Otherwise, the element inserted overwrites whatever was there, so the
1460 // input demanded set is simpler than the output set.
1461 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1462 DemandedElts & ~(1ULL << IdxNo),
1463 UndefElts, Depth+1);
1464 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1465
1466 // The inserted element is defined.
Dan Gohman488fbfc2008-09-09 18:11:14 +00001467 UndefElts &= ~(1ULL << IdxNo);
1468 break;
1469 }
1470 case Instruction::ShuffleVector: {
1471 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001472 uint64_t LHSVWidth =
1473 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Dan Gohman488fbfc2008-09-09 18:11:14 +00001474 uint64_t LeftDemanded = 0, RightDemanded = 0;
1475 for (unsigned i = 0; i < VWidth; i++) {
1476 if (DemandedElts & (1ULL << i)) {
1477 unsigned MaskVal = Shuffle->getMaskValue(i);
1478 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001479 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001480 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001481 if (MaskVal < LHSVWidth)
Dan Gohman488fbfc2008-09-09 18:11:14 +00001482 LeftDemanded |= 1ULL << MaskVal;
1483 else
Mon P Wangaeb06d22008-11-10 04:46:22 +00001484 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001485 }
1486 }
1487 }
1488
1489 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1490 UndefElts2, Depth+1);
1491 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1492
1493 uint64_t UndefElts3;
1494 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1495 UndefElts3, Depth+1);
1496 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1497
1498 bool NewUndefElts = false;
1499 for (unsigned i = 0; i < VWidth; i++) {
1500 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001501 if (MaskVal == -1u) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001502 uint64_t NewBit = 1ULL << i;
1503 UndefElts |= NewBit;
Mon P Wangaeb06d22008-11-10 04:46:22 +00001504 } else if (MaskVal < LHSVWidth) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001505 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1506 NewUndefElts |= NewBit;
1507 UndefElts |= NewBit;
1508 } else {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001509 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001510 NewUndefElts |= NewBit;
1511 UndefElts |= NewBit;
1512 }
1513 }
1514
1515 if (NewUndefElts) {
1516 // Add additional discovered undefs.
1517 std::vector<Constant*> Elts;
1518 for (unsigned i = 0; i < VWidth; ++i) {
1519 if (UndefElts & (1ULL << i))
1520 Elts.push_back(UndefValue::get(Type::Int32Ty));
1521 else
1522 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1523 Shuffle->getMaskValue(i)));
1524 }
1525 I->setOperand(2, ConstantVector::get(Elts));
1526 MadeChange = true;
1527 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001528 break;
1529 }
Chris Lattner69878332007-04-14 22:29:23 +00001530 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001531 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001532 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1533 if (!VTy) break;
1534 unsigned InVWidth = VTy->getNumElements();
1535 uint64_t InputDemandedElts = 0;
1536 unsigned Ratio;
1537
1538 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001539 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001540 // elements as are demanded of us.
1541 Ratio = 1;
1542 InputDemandedElts = DemandedElts;
1543 } else if (VWidth > InVWidth) {
1544 // Untested so far.
1545 break;
1546
1547 // If there are more elements in the result than there are in the source,
1548 // then an input element is live if any of the corresponding output
1549 // elements are live.
1550 Ratio = VWidth/InVWidth;
1551 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1552 if (DemandedElts & (1ULL << OutIdx))
1553 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1554 }
1555 } else {
1556 // Untested so far.
1557 break;
1558
1559 // If there are more elements in the source than there are in the result,
1560 // then an input element is live if the corresponding output element is
1561 // live.
1562 Ratio = InVWidth/VWidth;
1563 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1564 if (DemandedElts & (1ULL << InIdx/Ratio))
1565 InputDemandedElts |= 1ULL << InIdx;
1566 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001567
Chris Lattner69878332007-04-14 22:29:23 +00001568 // div/rem demand all inputs, because they don't want divide by zero.
1569 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1570 UndefElts2, Depth+1);
1571 if (TmpV) {
1572 I->setOperand(0, TmpV);
1573 MadeChange = true;
1574 }
1575
1576 UndefElts = UndefElts2;
1577 if (VWidth > InVWidth) {
1578 assert(0 && "Unimp");
1579 // If there are more elements in the result than there are in the source,
1580 // then an output element is undef if the corresponding input element is
1581 // undef.
1582 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1583 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1584 UndefElts |= 1ULL << OutIdx;
1585 } else if (VWidth < InVWidth) {
1586 assert(0 && "Unimp");
1587 // If there are more elements in the source than there are in the result,
1588 // then a result element is undef if all of the corresponding input
1589 // elements are undef.
1590 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1591 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1592 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1593 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1594 }
1595 break;
1596 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 case Instruction::And:
1598 case Instruction::Or:
1599 case Instruction::Xor:
1600 case Instruction::Add:
1601 case Instruction::Sub:
1602 case Instruction::Mul:
1603 // div/rem demand all inputs, because they don't want divide by zero.
1604 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1605 UndefElts, Depth+1);
1606 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1607 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1608 UndefElts2, Depth+1);
1609 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1610
1611 // Output elements are undefined if both are undefined. Consider things
1612 // like undef&0. The result is known zero, not undef.
1613 UndefElts &= UndefElts2;
1614 break;
1615
1616 case Instruction::Call: {
1617 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1618 if (!II) break;
1619 switch (II->getIntrinsicID()) {
1620 default: break;
1621
1622 // Binary vector operations that work column-wise. A dest element is a
1623 // function of the corresponding input elements from the two inputs.
1624 case Intrinsic::x86_sse_sub_ss:
1625 case Intrinsic::x86_sse_mul_ss:
1626 case Intrinsic::x86_sse_min_ss:
1627 case Intrinsic::x86_sse_max_ss:
1628 case Intrinsic::x86_sse2_sub_sd:
1629 case Intrinsic::x86_sse2_mul_sd:
1630 case Intrinsic::x86_sse2_min_sd:
1631 case Intrinsic::x86_sse2_max_sd:
1632 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1633 UndefElts, Depth+1);
1634 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1635 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1636 UndefElts2, Depth+1);
1637 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1638
1639 // If only the low elt is demanded and this is a scalarizable intrinsic,
1640 // scalarize it now.
1641 if (DemandedElts == 1) {
1642 switch (II->getIntrinsicID()) {
1643 default: break;
1644 case Intrinsic::x86_sse_sub_ss:
1645 case Intrinsic::x86_sse_mul_ss:
1646 case Intrinsic::x86_sse2_sub_sd:
1647 case Intrinsic::x86_sse2_mul_sd:
1648 // TODO: Lower MIN/MAX/ABS/etc
1649 Value *LHS = II->getOperand(1);
1650 Value *RHS = II->getOperand(2);
1651 // Extract the element as scalars.
1652 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1653 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1654
1655 switch (II->getIntrinsicID()) {
1656 default: assert(0 && "Case stmts out of sync!");
1657 case Intrinsic::x86_sse_sub_ss:
1658 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001659 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001660 II->getName()), *II);
1661 break;
1662 case Intrinsic::x86_sse_mul_ss:
1663 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001664 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001665 II->getName()), *II);
1666 break;
1667 }
1668
1669 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001670 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1671 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001672 InsertNewInstBefore(New, *II);
1673 AddSoonDeadInstToWorklist(*II, 0);
1674 return New;
1675 }
1676 }
1677
1678 // Output elements are undefined if both are undefined. Consider things
1679 // like undef&0. The result is known zero, not undef.
1680 UndefElts &= UndefElts2;
1681 break;
1682 }
1683 break;
1684 }
1685 }
1686 return MadeChange ? I : 0;
1687}
1688
Dan Gohman45b4e482008-05-19 22:14:15 +00001689
Chris Lattner564a7272003-08-13 19:01:45 +00001690/// AssociativeOpt - Perform an optimization on an associative operator. This
1691/// function is designed to check a chain of associative operators for a
1692/// potential to apply a certain optimization. Since the optimization may be
1693/// applicable if the expression was reassociated, this checks the chain, then
1694/// reassociates the expression as necessary to expose the optimization
1695/// opportunity. This makes use of a special Functor, which must define
1696/// 'shouldApply' and 'apply' methods.
1697///
1698template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001699static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001700 unsigned Opcode = Root.getOpcode();
1701 Value *LHS = Root.getOperand(0);
1702
1703 // Quick check, see if the immediate LHS matches...
1704 if (F.shouldApply(LHS))
1705 return F.apply(Root);
1706
1707 // Otherwise, if the LHS is not of the same opcode as the root, return.
1708 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001709 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001710 // Should we apply this transform to the RHS?
1711 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1712
1713 // If not to the RHS, check to see if we should apply to the LHS...
1714 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1715 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1716 ShouldApply = true;
1717 }
1718
1719 // If the functor wants to apply the optimization to the RHS of LHSI,
1720 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1721 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001722 // Now all of the instructions are in the current basic block, go ahead
1723 // and perform the reassociation.
1724 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1725
1726 // First move the selected RHS to the LHS of the root...
1727 Root.setOperand(0, LHSI->getOperand(1));
1728
1729 // Make what used to be the LHS of the root be the user of the root...
1730 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001731 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001732 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1733 return 0;
1734 }
Chris Lattner65725312004-04-16 18:08:07 +00001735 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001736 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001737 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001738 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001739 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001740
1741 // Now propagate the ExtraOperand down the chain of instructions until we
1742 // get to LHSI.
1743 while (TmpLHSI != LHSI) {
1744 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001745 // Move the instruction to immediately before the chain we are
1746 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001747 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001748 ARI = NextLHSI;
1749
Chris Lattner564a7272003-08-13 19:01:45 +00001750 Value *NextOp = NextLHSI->getOperand(1);
1751 NextLHSI->setOperand(1, ExtraOperand);
1752 TmpLHSI = NextLHSI;
1753 ExtraOperand = NextOp;
1754 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001755
Chris Lattner564a7272003-08-13 19:01:45 +00001756 // Now that the instructions are reassociated, have the functor perform
1757 // the transformation...
1758 return F.apply(Root);
1759 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001760
Chris Lattner564a7272003-08-13 19:01:45 +00001761 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1762 }
1763 return 0;
1764}
1765
Dan Gohman844731a2008-05-13 00:00:25 +00001766namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001767
Nick Lewycky02d639f2008-05-23 04:34:58 +00001768// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001769struct AddRHS {
1770 Value *RHS;
1771 AddRHS(Value *rhs) : RHS(rhs) {}
1772 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1773 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001774 return BinaryOperator::CreateShl(Add.getOperand(0),
1775 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001776 }
1777};
1778
1779// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1780// iff C1&C2 == 0
1781struct AddMaskingAnd {
1782 Constant *C2;
1783 AddMaskingAnd(Constant *c) : C2(c) {}
1784 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001785 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001786 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001787 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001788 }
1789 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001790 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001791 }
1792};
1793
Dan Gohman844731a2008-05-13 00:00:25 +00001794}
1795
Chris Lattner6e7ba452005-01-01 16:22:27 +00001796static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001797 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001798 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001799 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001800 }
1801
Chris Lattner2eefe512004-04-09 19:05:30 +00001802 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001803 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1804 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001805
Chris Lattner2eefe512004-04-09 19:05:30 +00001806 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1807 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001808 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1809 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001810 }
1811
1812 Value *Op0 = SO, *Op1 = ConstOperand;
1813 if (!ConstIsRHS)
1814 std::swap(Op0, Op1);
1815 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001816 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001817 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001818 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001819 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001820 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001821 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001822 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001823 abort();
1824 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001825 return IC->InsertNewInstBefore(New, I);
1826}
1827
1828// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1829// constant as the other operand, try to fold the binary operator into the
1830// select arguments. This also works for Cast instructions, which obviously do
1831// not have a second operand.
1832static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1833 InstCombiner *IC) {
1834 // Don't modify shared select instructions
1835 if (!SI->hasOneUse()) return 0;
1836 Value *TV = SI->getOperand(1);
1837 Value *FV = SI->getOperand(2);
1838
1839 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001840 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001841 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001842
Chris Lattner6e7ba452005-01-01 16:22:27 +00001843 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1844 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1845
Gabor Greif051a9502008-04-06 20:25:17 +00001846 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1847 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001848 }
1849 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001850}
1851
Chris Lattner4e998b22004-09-29 05:07:12 +00001852
1853/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1854/// node as operand #0, see if we can fold the instruction into the PHI (which
1855/// is only possible if all operands to the PHI are constants).
1856Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1857 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001858 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001859 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001860
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001861 // Check to see if all of the operands of the PHI are constants. If there is
1862 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001863 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001864 BasicBlock *NonConstBB = 0;
1865 for (unsigned i = 0; i != NumPHIValues; ++i)
1866 if (!isa<Constant>(PN->getIncomingValue(i))) {
1867 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001868 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001869 NonConstBB = PN->getIncomingBlock(i);
1870
1871 // If the incoming non-constant value is in I's block, we have an infinite
1872 // loop.
1873 if (NonConstBB == I.getParent())
1874 return 0;
1875 }
1876
1877 // If there is exactly one non-constant value, we can insert a copy of the
1878 // operation in that block. However, if this is a critical edge, we would be
1879 // inserting the computation one some other paths (e.g. inside a loop). Only
1880 // do this if the pred block is unconditionally branching into the phi block.
1881 if (NonConstBB) {
1882 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1883 if (!BI || !BI->isUnconditional()) return 0;
1884 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001885
1886 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001887 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001888 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001889 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001890 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001891
1892 // Next, add all of the operands to the PHI.
1893 if (I.getNumOperands() == 2) {
1894 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001895 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001896 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001897 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001898 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1899 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1900 else
1901 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001902 } else {
1903 assert(PN->getIncomingBlock(i) == NonConstBB);
1904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001905 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001906 PN->getIncomingValue(i), C, "phitmp",
1907 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001908 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001909 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001910 CI->getPredicate(),
1911 PN->getIncomingValue(i), C, "phitmp",
1912 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001913 else
1914 assert(0 && "Unknown binop!");
1915
Chris Lattnerdbab3862007-03-02 21:28:56 +00001916 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001917 }
1918 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001919 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001920 } else {
1921 CastInst *CI = cast<CastInst>(&I);
1922 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001923 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001924 Value *InV;
1925 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001926 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001927 } else {
1928 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001929 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001930 I.getType(), "phitmp",
1931 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001932 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001933 }
1934 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001935 }
1936 }
1937 return ReplaceInstUsesWith(I, NewPN);
1938}
1939
Chris Lattner2454a2e2008-01-29 06:52:45 +00001940
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001941/// WillNotOverflowSignedAdd - Return true if we can prove that:
1942/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1943/// This basically requires proving that the add in the original type would not
1944/// overflow to change the sign bit or have a carry out.
1945bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1946 // There are different heuristics we can use for this. Here are some simple
1947 // ones.
1948
1949 // Add has the property that adding any two 2's complement numbers can only
1950 // have one carry bit which can change a sign. As such, if LHS and RHS each
1951 // have at least two sign bits, we know that the addition of the two values will
1952 // sign extend fine.
1953 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1954 return true;
1955
1956
1957 // If one of the operands only has one non-zero bit, and if the other operand
1958 // has a known-zero bit in a more significant place than it (not including the
1959 // sign bit) the ripple may go up to and fill the zero, but won't change the
1960 // sign. For example, (X & ~4) + 1.
1961
1962 // TODO: Implement.
1963
1964 return false;
1965}
1966
Chris Lattner2454a2e2008-01-29 06:52:45 +00001967
Chris Lattner7e708292002-06-25 16:13:24 +00001968Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001969 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001970 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001971
Chris Lattner66331a42004-04-10 22:01:55 +00001972 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001973 // X + undef -> undef
1974 if (isa<UndefValue>(RHS))
1975 return ReplaceInstUsesWith(I, RHS);
1976
Chris Lattner66331a42004-04-10 22:01:55 +00001977 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001978 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00001979 if (RHSC->isNullValue())
1980 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001981 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00001982 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1983 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00001984 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001985 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001986
Chris Lattner66331a42004-04-10 22:01:55 +00001987 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001988 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00001989 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00001990 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00001991 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001992 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001993
1994 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1995 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00001996 if (!isa<VectorType>(I.getType())) {
1997 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1998 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1999 KnownZero, KnownOne))
2000 return &I;
2001 }
Dan Gohman1975d032008-10-30 20:40:10 +00002002
2003 // zext(i1) - 1 -> select i1, 0, -1
2004 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2005 if (CI->isAllOnesValue() &&
2006 ZI->getOperand(0)->getType() == Type::Int1Ty)
2007 return SelectInst::Create(ZI->getOperand(0),
2008 Constant::getNullValue(I.getType()),
2009 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002010 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002011
2012 if (isa<PHINode>(LHS))
2013 if (Instruction *NV = FoldOpIntoPhi(I))
2014 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002015
Chris Lattner4f637d42006-01-06 17:59:59 +00002016 ConstantInt *XorRHS = 0;
2017 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002018 if (isa<ConstantInt>(RHSC) &&
2019 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002020 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002021 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002022
Zhou Sheng4351c642007-04-02 08:20:41 +00002023 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002024 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2025 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002026 do {
2027 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002028 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2029 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002030 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2031 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002032 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002033 if (!MaskedValueIsZero(XorLHS,
2034 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002035 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002036 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002037 }
2038 }
2039 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002040 C0080Val = APIntOps::lshr(C0080Val, Size);
2041 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2042 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002043
Reid Spencer35c38852007-03-28 01:36:16 +00002044 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002045 // with funny bit widths then this switch statement should be removed. It
2046 // is just here to get the size of the "middle" type back up to something
2047 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002048 const Type *MiddleType = 0;
2049 switch (Size) {
2050 default: break;
2051 case 32: MiddleType = Type::Int32Ty; break;
2052 case 16: MiddleType = Type::Int16Ty; break;
2053 case 8: MiddleType = Type::Int8Ty; break;
2054 }
2055 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002056 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002057 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002058 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002059 }
2060 }
Chris Lattner66331a42004-04-10 22:01:55 +00002061 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002062
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002063 if (I.getType() == Type::Int1Ty)
2064 return BinaryOperator::CreateXor(LHS, RHS);
2065
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002066 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002067 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002068 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002069
2070 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2071 if (RHSI->getOpcode() == Instruction::Sub)
2072 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2073 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2074 }
2075 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2076 if (LHSI->getOpcode() == Instruction::Sub)
2077 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2078 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2079 }
Robert Bocchino71698282004-07-27 21:02:21 +00002080 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002081
Chris Lattner5c4afb92002-05-08 22:46:53 +00002082 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002083 // -A + -B --> -(A + B)
2084 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002085 if (LHS->getType()->isIntOrIntVector()) {
2086 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002087 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002088 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002089 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002090 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002091 }
2092
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002093 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002094 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002095
2096 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002097 if (!isa<Constant>(RHS))
2098 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002099 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002100
Misha Brukmanfd939082005-04-21 23:48:37 +00002101
Chris Lattner50af16a2004-11-13 19:50:12 +00002102 ConstantInt *C2;
2103 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2104 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002105 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002106
2107 // X*C1 + X*C2 --> X * (C1+C2)
2108 ConstantInt *C1;
2109 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002110 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002111 }
2112
2113 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002114 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002115 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002116
Chris Lattnere617c9e2007-01-05 02:17:46 +00002117 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002118 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2119 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002120
Chris Lattnerad3448c2003-02-18 19:57:07 +00002121
Chris Lattner564a7272003-08-13 19:01:45 +00002122 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002123 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002124 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2125 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002126
2127 // A+B --> A|B iff A and B have no bits set in common.
2128 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2129 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2130 APInt LHSKnownOne(IT->getBitWidth(), 0);
2131 APInt LHSKnownZero(IT->getBitWidth(), 0);
2132 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2133 if (LHSKnownZero != 0) {
2134 APInt RHSKnownOne(IT->getBitWidth(), 0);
2135 APInt RHSKnownZero(IT->getBitWidth(), 0);
2136 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2137
2138 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002139 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002140 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002141 }
2142 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002143
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002144 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002145 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002146 Value *W, *X, *Y, *Z;
2147 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2148 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2149 if (W != Y) {
2150 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002151 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002152 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002153 std::swap(W, X);
2154 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002155 std::swap(Y, Z);
2156 std::swap(W, X);
2157 }
2158 }
2159
2160 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002161 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002162 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002164 }
2165 }
2166 }
2167
Chris Lattner6b032052003-10-02 15:11:26 +00002168 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002169 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002170 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002171 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002172
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002173 // (X & FF00) + xx00 -> (X+xx00) & FF00
2174 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002175 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002176 if (Anded == CRHS) {
2177 // See if all bits from the first bit set in the Add RHS up are included
2178 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002179 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002180
2181 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002182 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002183
2184 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002185 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002186
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002187 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2188 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002189 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002190 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002191 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002192 }
2193 }
2194 }
2195
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002196 // Try to fold constant add into select arguments.
2197 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002198 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002199 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002200 }
2201
Reid Spencer1628cec2006-10-26 06:15:43 +00002202 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002203 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002204 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002205 CastInst *CI = dyn_cast<CastInst>(LHS);
2206 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002207 if (!CI) {
2208 CI = dyn_cast<CastInst>(RHS);
2209 Other = LHS;
2210 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002211 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002212 (CI->getType()->getPrimitiveSizeInBits() ==
2213 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002214 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002215 unsigned AS =
2216 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002217 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2218 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002219 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002220 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002221 }
2222 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002223
Chris Lattner42790482007-12-20 01:56:58 +00002224 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002225 {
2226 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002227 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002228 if (!SI) {
2229 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002230 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002231 }
Chris Lattner42790482007-12-20 01:56:58 +00002232 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002233 Value *TV = SI->getTrueValue();
2234 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002235 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002236
2237 // Can we fold the add into the argument of the select?
2238 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002239 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2240 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002241 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002242 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2243 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002244 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002245 }
2246 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002247
2248 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2249 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2250 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2251 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002252
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002253 // Check for (add (sext x), y), see if we can merge this into an
2254 // integer add followed by a sext.
2255 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2256 // (add (sext x), cst) --> (sext (add x, cst'))
2257 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2258 Constant *CI =
2259 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2260 if (LHSConv->hasOneUse() &&
2261 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2262 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2263 // Insert the new, smaller add.
2264 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2265 CI, "addconv");
2266 InsertNewInstBefore(NewAdd, I);
2267 return new SExtInst(NewAdd, I.getType());
2268 }
2269 }
2270
2271 // (add (sext x), (sext y)) --> (sext (add int x, y))
2272 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2273 // Only do this if x/y have the same type, if at last one of them has a
2274 // single use (so we don't increase the number of sexts), and if the
2275 // integer add will not overflow.
2276 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2277 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2278 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2279 RHSConv->getOperand(0))) {
2280 // Insert the new integer add.
2281 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2282 RHSConv->getOperand(0),
2283 "addconv");
2284 InsertNewInstBefore(NewAdd, I);
2285 return new SExtInst(NewAdd, I.getType());
2286 }
2287 }
2288 }
2289
2290 // Check for (add double (sitofp x), y), see if we can merge this into an
2291 // integer add followed by a promotion.
2292 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2293 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2294 // ... if the constant fits in the integer value. This is useful for things
2295 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2296 // requires a constant pool load, and generally allows the add to be better
2297 // instcombined.
2298 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2299 Constant *CI =
2300 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2301 if (LHSConv->hasOneUse() &&
2302 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2303 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304 // Insert the new integer add.
2305 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2306 CI, "addconv");
2307 InsertNewInstBefore(NewAdd, I);
2308 return new SIToFPInst(NewAdd, I.getType());
2309 }
2310 }
2311
2312 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2313 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2314 // Only do this if x/y have the same type, if at last one of them has a
2315 // single use (so we don't increase the number of int->fp conversions),
2316 // and if the integer add will not overflow.
2317 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2318 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2319 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2320 RHSConv->getOperand(0))) {
2321 // Insert the new integer add.
2322 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2323 RHSConv->getOperand(0),
2324 "addconv");
2325 InsertNewInstBefore(NewAdd, I);
2326 return new SIToFPInst(NewAdd, I.getType());
2327 }
2328 }
2329 }
2330
Chris Lattner7e708292002-06-25 16:13:24 +00002331 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002332}
2333
Chris Lattner7e708292002-06-25 16:13:24 +00002334Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002336
Chris Lattnerd137ab42008-07-17 06:07:20 +00002337 if (Op0 == Op1 && // sub X, X -> 0
2338 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002339 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002340
Chris Lattner233f7dc2002-08-12 21:17:25 +00002341 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002342 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002343 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002344
Chris Lattnere87597f2004-10-16 18:11:37 +00002345 if (isa<UndefValue>(Op0))
2346 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2347 if (isa<UndefValue>(Op1))
2348 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2349
Chris Lattnerd65460f2003-11-05 01:06:05 +00002350 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2351 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002352 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002353 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002354
Chris Lattnerd65460f2003-11-05 01:06:05 +00002355 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002356 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002357 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002358 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002359
Chris Lattner76b7a062007-01-15 07:02:54 +00002360 // -(X >>u 31) -> (X >>s 31)
2361 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002362 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002363 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002364 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002365 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002366 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002367 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002368 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002369 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002370 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002371 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002372 }
2373 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002374 }
2375 else if (SI->getOpcode() == Instruction::AShr) {
2376 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2377 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002378 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002379 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002380 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002381 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002382 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002383 }
2384 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002385 }
2386 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002387 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002388
2389 // Try to fold constant sub into select arguments.
2390 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002391 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002392 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002393 }
2394
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002395 if (I.getType() == Type::Int1Ty)
2396 return BinaryOperator::CreateXor(Op0, Op1);
2397
Chris Lattner43d84d62005-04-07 16:15:25 +00002398 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2399 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002400 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002401 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002402 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002403 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002404 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002405 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2406 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2407 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002408 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002409 Op1I->getOperand(0));
2410 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002411 }
2412
Chris Lattnerfd059242003-10-15 16:48:29 +00002413 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002414 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2415 // is not used by anyone else...
2416 //
Chris Lattner0517e722004-02-02 20:09:56 +00002417 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002418 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002419 // Swap the two operands of the subexpr...
2420 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2421 Op1I->setOperand(0, IIOp1);
2422 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002423
Chris Lattnera2881962003-02-18 19:28:33 +00002424 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002425 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002426 }
2427
2428 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2429 //
2430 if (Op1I->getOpcode() == Instruction::And &&
2431 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2432 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2433
Chris Lattnerf523d062004-06-09 05:08:07 +00002434 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002435 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2436 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002437 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002438
Reid Spencerac5209e2006-10-16 23:08:08 +00002439 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002440 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002441 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002442 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002443 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002444 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002445 ConstantExpr::getNeg(DivRHS));
2446
Chris Lattnerad3448c2003-02-18 19:57:07 +00002447 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002448 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002449 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002450 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002451 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002452 }
Chris Lattner40371712002-05-09 01:29:19 +00002453 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002454 }
Chris Lattnera2881962003-02-18 19:28:33 +00002455
Chris Lattner9919e3d2006-12-02 00:13:08 +00002456 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002457 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002458 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002459 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2460 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2461 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2462 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002463 } else if (Op0I->getOpcode() == Instruction::Sub) {
2464 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002465 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002466 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002467 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002468
Chris Lattner50af16a2004-11-13 19:50:12 +00002469 ConstantInt *C1;
2470 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002471 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002473
Chris Lattner50af16a2004-11-13 19:50:12 +00002474 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2475 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002476 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002477 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002478 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002479}
2480
Chris Lattnera0141b92007-07-15 20:42:37 +00002481/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2482/// comparison only checks the sign bit. If it only checks the sign bit, set
2483/// TrueIfSigned if the result of the comparison is true when the input value is
2484/// signed.
2485static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2486 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002487 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002488 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2489 TrueIfSigned = true;
2490 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002491 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2492 TrueIfSigned = true;
2493 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002494 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2495 TrueIfSigned = false;
2496 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002497 case ICmpInst::ICMP_UGT:
2498 // True if LHS u> RHS and RHS == high-bit-mask - 1
2499 TrueIfSigned = true;
2500 return RHS->getValue() ==
2501 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2502 case ICmpInst::ICMP_UGE:
2503 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2504 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002505 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002506 default:
2507 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002508 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002509}
2510
Chris Lattner7e708292002-06-25 16:13:24 +00002511Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002512 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002513 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002514
Chris Lattnere87597f2004-10-16 18:11:37 +00002515 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2516 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2517
Chris Lattner233f7dc2002-08-12 21:17:25 +00002518 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002519 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002521
2522 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002523 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002524 if (SI->getOpcode() == Instruction::Shl)
2525 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002526 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002527 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002528
Zhou Sheng843f07672007-04-19 05:39:12 +00002529 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002530 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2531 if (CI->equalsInt(1)) // X * 1 == X
2532 return ReplaceInstUsesWith(I, Op0);
2533 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002534 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002535
Zhou Sheng97b52c22007-03-29 01:57:21 +00002536 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002537 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002539 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002540 }
Robert Bocchino71698282004-07-27 21:02:21 +00002541 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002542 if (Op1F->isNullValue())
2543 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002544
Chris Lattnera2881962003-02-18 19:28:33 +00002545 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2546 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002547 if (Op1F->isExactlyValue(1.0))
2548 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2549 } else if (isa<VectorType>(Op1->getType())) {
2550 if (isa<ConstantAggregateZero>(Op1))
2551 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002552
2553 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2554 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2555 return BinaryOperator::CreateNeg(Op0, I.getName());
2556
2557 // As above, vector X*splat(1.0) -> X in all defined cases.
2558 if (Constant *Splat = Op1V->getSplatValue()) {
2559 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2560 if (F->isExactlyValue(1.0))
2561 return ReplaceInstUsesWith(I, Op0);
2562 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2563 if (CI->equalsInt(1))
2564 return ReplaceInstUsesWith(I, Op0);
2565 }
2566 }
Chris Lattnera2881962003-02-18 19:28:33 +00002567 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002568
2569 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2570 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002571 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002572 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002573 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002574 Op1, "tmp");
2575 InsertNewInstBefore(Add, I);
2576 Value *C1C2 = ConstantExpr::getMul(Op1,
2577 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002578 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002579
2580 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002581
2582 // Try to fold constant mul into select arguments.
2583 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002584 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002585 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002586
2587 if (isa<PHINode>(Op0))
2588 if (Instruction *NV = FoldOpIntoPhi(I))
2589 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002590 }
2591
Chris Lattnera4f445b2003-03-10 23:23:04 +00002592 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2593 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002594 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002595
Nick Lewycky0c730792008-11-21 07:33:58 +00002596 // (X / Y) * Y = X - (X % Y)
2597 // (X / Y) * -Y = (X % Y) - X
2598 {
2599 Value *Op1 = I.getOperand(1);
2600 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2601 if (!BO ||
2602 (BO->getOpcode() != Instruction::UDiv &&
2603 BO->getOpcode() != Instruction::SDiv)) {
2604 Op1 = Op0;
2605 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2606 }
2607 Value *Neg = dyn_castNegVal(Op1);
2608 if (BO && BO->hasOneUse() &&
2609 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2610 (BO->getOpcode() == Instruction::UDiv ||
2611 BO->getOpcode() == Instruction::SDiv)) {
2612 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2613
2614 Instruction *Rem;
2615 if (BO->getOpcode() == Instruction::UDiv)
2616 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2617 else
2618 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2619
2620 InsertNewInstBefore(Rem, I);
2621 Rem->takeName(BO);
2622
2623 if (Op1BO == Op1)
2624 return BinaryOperator::CreateSub(Op0BO, Rem);
2625 else
2626 return BinaryOperator::CreateSub(Rem, Op0BO);
2627 }
2628 }
2629
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002630 if (I.getType() == Type::Int1Ty)
2631 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2632
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002633 // If one of the operands of the multiply is a cast from a boolean value, then
2634 // we know the bool is either zero or one, so this is a 'masking' multiply.
2635 // See if we can simplify things based on how the boolean was originally
2636 // formed.
2637 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002638 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002639 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002640 BoolCast = CI;
2641 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002642 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002643 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002644 BoolCast = CI;
2645 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002646 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002647 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2648 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002649 bool TIS = false;
2650
Reid Spencere4d87aa2006-12-23 06:05:41 +00002651 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002652 // multiply into a shift/and combination.
2653 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002654 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2655 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002656 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002657 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002658 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002659 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002660 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002661 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002662 BoolCast->getOperand(0)->getName()+
2663 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002664
2665 // If the multiply type is not the same as the source type, sign extend
2666 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002667 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002668 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2669 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002670 Instruction::CastOps opcode =
2671 (SrcBits == DstBits ? Instruction::BitCast :
2672 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2673 V = InsertCastBefore(opcode, V, I.getType(), I);
2674 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002675
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002676 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002677 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002678 }
2679 }
2680 }
2681
Chris Lattner7e708292002-06-25 16:13:24 +00002682 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002683}
2684
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002685/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2686/// instruction.
2687bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2688 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2689
2690 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2691 int NonNullOperand = -1;
2692 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2693 if (ST->isNullValue())
2694 NonNullOperand = 2;
2695 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2696 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2697 if (ST->isNullValue())
2698 NonNullOperand = 1;
2699
2700 if (NonNullOperand == -1)
2701 return false;
2702
2703 Value *SelectCond = SI->getOperand(0);
2704
2705 // Change the div/rem to use 'Y' instead of the select.
2706 I.setOperand(1, SI->getOperand(NonNullOperand));
2707
2708 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2709 // problem. However, the select, or the condition of the select may have
2710 // multiple uses. Based on our knowledge that the operand must be non-zero,
2711 // propagate the known value for the select into other uses of it, and
2712 // propagate a known value of the condition into its other users.
2713
2714 // If the select and condition only have a single use, don't bother with this,
2715 // early exit.
2716 if (SI->use_empty() && SelectCond->hasOneUse())
2717 return true;
2718
2719 // Scan the current block backward, looking for other uses of SI.
2720 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2721
2722 while (BBI != BBFront) {
2723 --BBI;
2724 // If we found a call to a function, we can't assume it will return, so
2725 // information from below it cannot be propagated above it.
2726 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2727 break;
2728
2729 // Replace uses of the select or its condition with the known values.
2730 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2731 I != E; ++I) {
2732 if (*I == SI) {
2733 *I = SI->getOperand(NonNullOperand);
2734 AddToWorkList(BBI);
2735 } else if (*I == SelectCond) {
2736 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2737 ConstantInt::getFalse();
2738 AddToWorkList(BBI);
2739 }
2740 }
2741
2742 // If we past the instruction, quit looking for it.
2743 if (&*BBI == SI)
2744 SI = 0;
2745 if (&*BBI == SelectCond)
2746 SelectCond = 0;
2747
2748 // If we ran out of things to eliminate, break out of the loop.
2749 if (SelectCond == 0 && SI == 0)
2750 break;
2751
2752 }
2753 return true;
2754}
2755
2756
Reid Spencer1628cec2006-10-26 06:15:43 +00002757/// This function implements the transforms on div instructions that work
2758/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2759/// used by the visitors to those instructions.
2760/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002761Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002763
Chris Lattner50b2ca42008-02-19 06:12:18 +00002764 // undef / X -> 0 for integer.
2765 // undef / X -> undef for FP (the undef could be a snan).
2766 if (isa<UndefValue>(Op0)) {
2767 if (Op0->getType()->isFPOrFPVector())
2768 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002769 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002770 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002771
2772 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002773 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002774 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002775
Reid Spencer1628cec2006-10-26 06:15:43 +00002776 return 0;
2777}
Misha Brukmanfd939082005-04-21 23:48:37 +00002778
Reid Spencer1628cec2006-10-26 06:15:43 +00002779/// This function implements the transforms common to both integer division
2780/// instructions (udiv and sdiv). It is called by the visitors to those integer
2781/// division instructions.
2782/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002783Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2785
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002786 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002787 if (Op0 == Op1) {
2788 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2789 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2790 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2791 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2792 }
2793
2794 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2795 return ReplaceInstUsesWith(I, CI);
2796 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002797
Reid Spencer1628cec2006-10-26 06:15:43 +00002798 if (Instruction *Common = commonDivTransforms(I))
2799 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002800
2801 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2802 // This does not apply for fdiv.
2803 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2804 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002805
2806 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2807 // div X, 1 == X
2808 if (RHS->equalsInt(1))
2809 return ReplaceInstUsesWith(I, Op0);
2810
2811 // (X / C1) / C2 -> X / (C1*C2)
2812 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2813 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2814 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002815 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2816 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2817 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002818 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002819 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002820 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002821
Reid Spencerbca0e382007-03-23 20:05:17 +00002822 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002823 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2824 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2825 return R;
2826 if (isa<PHINode>(Op0))
2827 if (Instruction *NV = FoldOpIntoPhi(I))
2828 return NV;
2829 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002830 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002831
Chris Lattnera2881962003-02-18 19:28:33 +00002832 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002833 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002834 if (LHS->equalsInt(0))
2835 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2836
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002837 // It can't be division by zero, hence it must be division by one.
2838 if (I.getType() == Type::Int1Ty)
2839 return ReplaceInstUsesWith(I, Op0);
2840
Nick Lewycky895f0852008-11-27 20:21:08 +00002841 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2842 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2843 // div X, 1 == X
2844 if (X->isOne())
2845 return ReplaceInstUsesWith(I, Op0);
2846 }
2847
Reid Spencer1628cec2006-10-26 06:15:43 +00002848 return 0;
2849}
2850
2851Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2853
2854 // Handle the integer div common cases
2855 if (Instruction *Common = commonIDivTransforms(I))
2856 return Common;
2857
Reid Spencer1628cec2006-10-26 06:15:43 +00002858 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002859 // X udiv C^2 -> X >> C
2860 // Check to see if this is an unsigned division with an exact power of 2,
2861 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002862 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002863 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002864 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002865
2866 // X udiv C, where C >= signbit
2867 if (C->getValue().isNegative()) {
2868 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2869 I);
2870 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2871 ConstantInt::get(I.getType(), 1));
2872 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002873 }
2874
2875 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002876 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002877 if (RHSI->getOpcode() == Instruction::Shl &&
2878 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002879 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002880 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002881 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002882 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002883 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002884 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002885 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002886 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002887 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002888 }
2889 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002890 }
2891
Reid Spencer1628cec2006-10-26 06:15:43 +00002892 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2893 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002894 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002895 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002896 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002897 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002898 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002899 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002900 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002901 // Construct the "on true" case of the select
2902 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002903 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002904 Op0, TC, SI->getName()+".t");
2905 TSI = InsertNewInstBefore(TSI, I);
2906
2907 // Construct the "on false" case of the select
2908 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002909 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002910 Op0, FC, SI->getName()+".f");
2911 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002912
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002913 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002914 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002915 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002916 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002917 return 0;
2918}
2919
Reid Spencer1628cec2006-10-26 06:15:43 +00002920Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2921 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2922
2923 // Handle the integer div common cases
2924 if (Instruction *Common = commonIDivTransforms(I))
2925 return Common;
2926
2927 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2928 // sdiv X, -1 == -X
2929 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002930 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002931 }
2932
2933 // If the sign bits of both operands are zero (i.e. we can prove they are
2934 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002935 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002936 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002937 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002938 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002939 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002940 }
2941 }
2942
2943 return 0;
2944}
2945
2946Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2947 return commonDivTransforms(I);
2948}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002949
Reid Spencer0a783f72006-11-02 01:53:59 +00002950/// This function implements the transforms on rem instructions that work
2951/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2952/// is used by the visitors to those instructions.
2953/// @brief Transforms common to all three rem instructions
2954Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002956
Chris Lattner50b2ca42008-02-19 06:12:18 +00002957 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2958 if (I.getType()->isFPOrFPVector())
2959 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002960 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002961 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002962 if (isa<UndefValue>(Op1))
2963 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002964
2965 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002966 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2967 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00002968
Reid Spencer0a783f72006-11-02 01:53:59 +00002969 return 0;
2970}
2971
2972/// This function implements the transforms common to both integer remainder
2973/// instructions (urem and srem). It is called by the visitors to those integer
2974/// remainder instructions.
2975/// @brief Common integer remainder transforms
2976Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2977 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2978
2979 if (Instruction *common = commonRemTransforms(I))
2980 return common;
2981
Dale Johannesened6af242009-01-21 00:35:19 +00002982 // 0 % X == 0 for integer, we don't need to preserve faults!
2983 if (Constant *LHS = dyn_cast<Constant>(Op0))
2984 if (LHS->isNullValue())
2985 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2986
Chris Lattner857e8cd2004-12-12 21:48:58 +00002987 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002988 // X % 0 == undef, we don't need to preserve faults!
2989 if (RHS->equalsInt(0))
2990 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2991
Chris Lattnera2881962003-02-18 19:28:33 +00002992 if (RHS->equalsInt(1)) // X % 1 == 0
2993 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2994
Chris Lattner97943922006-02-28 05:49:21 +00002995 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2996 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2997 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2998 return R;
2999 } else if (isa<PHINode>(Op0I)) {
3000 if (Instruction *NV = FoldOpIntoPhi(I))
3001 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003002 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003003
3004 // See if we can fold away this rem instruction.
3005 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3006 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3007 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3008 KnownZero, KnownOne))
3009 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003010 }
Chris Lattnera2881962003-02-18 19:28:33 +00003011 }
3012
Reid Spencer0a783f72006-11-02 01:53:59 +00003013 return 0;
3014}
3015
3016Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3018
3019 if (Instruction *common = commonIRemTransforms(I))
3020 return common;
3021
3022 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3023 // X urem C^2 -> X and C
3024 // Check to see if this is an unsigned remainder with an exact power of 2,
3025 // if so, convert to a bitwise and.
3026 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003027 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003028 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003029 }
3030
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003031 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003032 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3033 if (RHSI->getOpcode() == Instruction::Shl &&
3034 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003035 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003036 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003037 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003038 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003039 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003040 }
3041 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003042 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003043
Reid Spencer0a783f72006-11-02 01:53:59 +00003044 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3045 // where C1&C2 are powers of two.
3046 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3047 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3048 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3049 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003050 if ((STO->getValue().isPowerOf2()) &&
3051 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003052 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003053 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003054 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003055 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003056 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003057 }
3058 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003059 }
3060
Chris Lattner3f5b8772002-05-06 16:14:14 +00003061 return 0;
3062}
3063
Reid Spencer0a783f72006-11-02 01:53:59 +00003064Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3065 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3066
Dan Gohmancff55092007-11-05 23:16:33 +00003067 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003068 if (Instruction *common = commonIRemTransforms(I))
3069 return common;
3070
3071 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003072 if (!isa<Constant>(RHSNeg) ||
3073 (isa<ConstantInt>(RHSNeg) &&
3074 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003075 // X % -Y -> X % Y
3076 AddUsesToWorkList(I);
3077 I.setOperand(1, RHSNeg);
3078 return &I;
3079 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003080
Dan Gohmancff55092007-11-05 23:16:33 +00003081 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003082 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003083 if (I.getType()->isInteger()) {
3084 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3085 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3086 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003087 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003088 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003089 }
3090
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003091 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003092 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3093 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003094
Nick Lewycky9dce8732008-12-20 16:48:00 +00003095 bool hasNegative = false;
3096 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3097 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3098 if (RHS->getValue().isNegative())
3099 hasNegative = true;
3100
3101 if (hasNegative) {
3102 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003103 for (unsigned i = 0; i != VWidth; ++i) {
3104 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3105 if (RHS->getValue().isNegative())
3106 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3107 else
3108 Elts[i] = RHS;
3109 }
3110 }
3111
3112 Constant *NewRHSV = ConstantVector::get(Elts);
3113 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003114 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003115 I.setOperand(1, NewRHSV);
3116 return &I;
3117 }
3118 }
3119 }
3120
Reid Spencer0a783f72006-11-02 01:53:59 +00003121 return 0;
3122}
3123
3124Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003125 return commonRemTransforms(I);
3126}
3127
Chris Lattner457dd822004-06-09 07:59:58 +00003128// isOneBitSet - Return true if there is exactly one bit set in the specified
3129// constant.
3130static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003131 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003132}
3133
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003134// isHighOnes - Return true if the constant is of the form 1+0+.
3135// This is the same as lowones(~X).
3136static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003137 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003138}
3139
Reid Spencere4d87aa2006-12-23 06:05:41 +00003140/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003141/// are carefully arranged to allow folding of expressions such as:
3142///
3143/// (A < B) | (A > B) --> (A != B)
3144///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003145/// Note that this is only valid if the first and second predicates have the
3146/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003147///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003148/// Three bits are used to represent the condition, as follows:
3149/// 0 A > B
3150/// 1 A == B
3151/// 2 A < B
3152///
3153/// <=> Value Definition
3154/// 000 0 Always false
3155/// 001 1 A > B
3156/// 010 2 A == B
3157/// 011 3 A >= B
3158/// 100 4 A < B
3159/// 101 5 A != B
3160/// 110 6 A <= B
3161/// 111 7 Always true
3162///
3163static unsigned getICmpCode(const ICmpInst *ICI) {
3164 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003165 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003166 case ICmpInst::ICMP_UGT: return 1; // 001
3167 case ICmpInst::ICMP_SGT: return 1; // 001
3168 case ICmpInst::ICMP_EQ: return 2; // 010
3169 case ICmpInst::ICMP_UGE: return 3; // 011
3170 case ICmpInst::ICMP_SGE: return 3; // 011
3171 case ICmpInst::ICMP_ULT: return 4; // 100
3172 case ICmpInst::ICMP_SLT: return 4; // 100
3173 case ICmpInst::ICMP_NE: return 5; // 101
3174 case ICmpInst::ICMP_ULE: return 6; // 110
3175 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003176 // True -> 7
3177 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003178 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003179 return 0;
3180 }
3181}
3182
Evan Cheng8db90722008-10-14 17:15:11 +00003183/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3184/// predicate into a three bit mask. It also returns whether it is an ordered
3185/// predicate by reference.
3186static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3187 isOrdered = false;
3188 switch (CC) {
3189 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3190 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003191 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3192 case FCmpInst::FCMP_UGT: return 1; // 001
3193 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3194 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003195 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3196 case FCmpInst::FCMP_UGE: return 3; // 011
3197 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3198 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003199 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3200 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003201 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3202 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003203 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003204 default:
3205 // Not expecting FCMP_FALSE and FCMP_TRUE;
3206 assert(0 && "Unexpected FCmp predicate!");
3207 return 0;
3208 }
3209}
3210
Reid Spencere4d87aa2006-12-23 06:05:41 +00003211/// getICmpValue - This is the complement of getICmpCode, which turns an
3212/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003213/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003214/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003215static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3216 switch (code) {
3217 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003218 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003219 case 1:
3220 if (sign)
3221 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3222 else
3223 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3224 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3225 case 3:
3226 if (sign)
3227 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3228 else
3229 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3230 case 4:
3231 if (sign)
3232 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3233 else
3234 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3235 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3236 case 6:
3237 if (sign)
3238 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3239 else
3240 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003241 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003242 }
3243}
3244
Evan Cheng8db90722008-10-14 17:15:11 +00003245/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3246/// opcode and two operands into either a FCmp instruction. isordered is passed
3247/// in to determine which kind of predicate to use in the new fcmp instruction.
3248static Value *getFCmpValue(bool isordered, unsigned code,
3249 Value *LHS, Value *RHS) {
3250 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003251 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003252 case 0:
3253 if (isordered)
3254 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3255 else
3256 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3257 case 1:
3258 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003259 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3260 else
3261 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003262 case 2:
3263 if (isordered)
3264 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3265 else
3266 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003267 case 3:
3268 if (isordered)
3269 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3270 else
3271 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3272 case 4:
3273 if (isordered)
3274 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3275 else
3276 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3277 case 5:
3278 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003279 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3280 else
3281 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3282 case 6:
3283 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003284 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3285 else
3286 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003287 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003288 }
3289}
3290
Chris Lattnerb9553d62008-11-16 04:55:20 +00003291/// PredicatesFoldable - Return true if both predicates match sign or if at
3292/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003293static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3294 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003295 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3296 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003297}
3298
3299namespace {
3300// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3301struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003302 InstCombiner &IC;
3303 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003304 ICmpInst::Predicate pred;
3305 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3306 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3307 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003308 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003309 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3310 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003311 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3312 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003313 return false;
3314 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003315 Instruction *apply(Instruction &Log) const {
3316 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3317 if (ICI->getOperand(0) != LHS) {
3318 assert(ICI->getOperand(1) == LHS);
3319 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003320 }
3321
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003322 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003323 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003324 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003325 unsigned Code;
3326 switch (Log.getOpcode()) {
3327 case Instruction::And: Code = LHSCode & RHSCode; break;
3328 case Instruction::Or: Code = LHSCode | RHSCode; break;
3329 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003330 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003331 }
3332
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003333 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3334 ICmpInst::isSignedPredicate(ICI->getPredicate());
3335
3336 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003337 if (Instruction *I = dyn_cast<Instruction>(RV))
3338 return I;
3339 // Otherwise, it's a constant boolean value...
3340 return IC.ReplaceInstUsesWith(Log, RV);
3341 }
3342};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003343} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003344
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003345// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3346// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003347// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003348Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003349 ConstantInt *OpRHS,
3350 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003351 BinaryOperator &TheAnd) {
3352 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003353 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003354 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003355 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003356
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003357 switch (Op->getOpcode()) {
3358 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003359 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003360 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003361 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003362 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003363 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003364 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003365 }
3366 break;
3367 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003368 if (Together == AndRHS) // (X | C) & C --> C
3369 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003370
Chris Lattner6e7ba452005-01-01 16:22:27 +00003371 if (Op->hasOneUse() && Together != OpRHS) {
3372 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003373 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003374 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003375 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003376 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003377 }
3378 break;
3379 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003380 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003381 // Adding a one to a single bit bit-field should be turned into an XOR
3382 // of the bit. First thing to check is to see if this AND is with a
3383 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003384 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003385
3386 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003387 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003388 // Ok, at this point, we know that we are masking the result of the
3389 // ADD down to exactly one bit. If the constant we are adding has
3390 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003391 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003392
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003393 // Check to see if any bits below the one bit set in AndRHSV are set.
3394 if ((AddRHS & (AndRHSV-1)) == 0) {
3395 // If not, the only thing that can effect the output of the AND is
3396 // the bit specified by AndRHSV. If that bit is set, the effect of
3397 // the XOR is to toggle the bit. If it is clear, then the ADD has
3398 // no effect.
3399 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3400 TheAnd.setOperand(0, X);
3401 return &TheAnd;
3402 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003403 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003404 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003405 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003406 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003407 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003408 }
3409 }
3410 }
3411 }
3412 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003413
3414 case Instruction::Shl: {
3415 // We know that the AND will not produce any of the bits shifted in, so if
3416 // the anded constant includes them, clear them now!
3417 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003418 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003419 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003420 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3421 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003422
Zhou Sheng290bec52007-03-29 08:15:12 +00003423 if (CI->getValue() == ShlMask) {
3424 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003425 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3426 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003427 TheAnd.setOperand(1, CI);
3428 return &TheAnd;
3429 }
3430 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003431 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003432 case Instruction::LShr:
3433 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003434 // We know that the AND will not produce any of the bits shifted in, so if
3435 // the anded constant includes them, clear them now! This only applies to
3436 // unsigned shifts, because a signed shr may bring in set bits!
3437 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003438 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003439 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003440 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3441 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003442
Zhou Sheng290bec52007-03-29 08:15:12 +00003443 if (CI->getValue() == ShrMask) {
3444 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003445 return ReplaceInstUsesWith(TheAnd, Op);
3446 } else if (CI != AndRHS) {
3447 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3448 return &TheAnd;
3449 }
3450 break;
3451 }
3452 case Instruction::AShr:
3453 // Signed shr.
3454 // See if this is shifting in some sign extension, then masking it out
3455 // with an and.
3456 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003457 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003458 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003459 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3460 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003461 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003462 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003463 // Make the argument unsigned.
3464 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003465 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003466 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003467 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003468 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003469 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003470 }
3471 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003472 }
3473 return 0;
3474}
3475
Chris Lattner8b170942002-08-09 23:47:40 +00003476
Chris Lattnera96879a2004-09-29 17:40:11 +00003477/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3478/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3480/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003481/// insert new instructions.
3482Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483 bool isSigned, bool Inside,
3484 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003485 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003486 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003487 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003488
Chris Lattnera96879a2004-09-29 17:40:11 +00003489 if (Inside) {
3490 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003491 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003492
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003494 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003495 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003496 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3497 return new ICmpInst(pred, V, Hi);
3498 }
3499
3500 // Emit V-Lo <u Hi-Lo
3501 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003502 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003503 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003504 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3505 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003506 }
3507
3508 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003509 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003510
Reid Spencere4e40032007-03-21 23:19:50 +00003511 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003512 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003513 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003514 ICmpInst::Predicate pred = (isSigned ?
3515 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3516 return new ICmpInst(pred, V, Hi);
3517 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003518
Reid Spencere4e40032007-03-21 23:19:50 +00003519 // Emit V-Lo >u Hi-1-Lo
3520 // Note that Hi has already had one subtracted from it, above.
3521 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003522 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003523 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003524 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3525 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003526}
3527
Chris Lattner7203e152005-09-18 07:22:02 +00003528// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3529// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3530// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3531// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003532static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003533 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003534 uint32_t BitWidth = Val->getType()->getBitWidth();
3535 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003536
3537 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003538 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003539 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003540 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003541 return true;
3542}
3543
Chris Lattner7203e152005-09-18 07:22:02 +00003544/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3545/// where isSub determines whether the operator is a sub. If we can fold one of
3546/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003547///
3548/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3549/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3550/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3551///
3552/// return (A +/- B).
3553///
3554Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003555 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003556 Instruction &I) {
3557 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3558 if (!LHSI || LHSI->getNumOperands() != 2 ||
3559 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3560
3561 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3562
3563 switch (LHSI->getOpcode()) {
3564 default: return 0;
3565 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003566 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003567 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003568 if ((Mask->getValue().countLeadingZeros() +
3569 Mask->getValue().countPopulation()) ==
3570 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003571 break;
3572
3573 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3574 // part, we don't need any explicit masks to take them out of A. If that
3575 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003576 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003577 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003578 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003579 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003580 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003581 break;
3582 }
3583 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003584 return 0;
3585 case Instruction::Or:
3586 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003587 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003588 if ((Mask->getValue().countLeadingZeros() +
3589 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003590 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003591 break;
3592 return 0;
3593 }
3594
3595 Instruction *New;
3596 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003597 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003598 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003599 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003600 return InsertNewInstBefore(New, I);
3601}
3602
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003603/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3604Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3605 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003606 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003607 ConstantInt *LHSCst, *RHSCst;
3608 ICmpInst::Predicate LHSCC, RHSCC;
3609
Chris Lattnerea065fb2008-11-16 05:10:52 +00003610 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003611 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003612 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003613 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003614
3615 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3616 // where C is a power of 2
3617 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3618 LHSCst->getValue().isPowerOf2()) {
3619 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3620 InsertNewInstBefore(NewOr, I);
3621 return new ICmpInst(LHSCC, NewOr, LHSCst);
3622 }
3623
3624 // From here on, we only handle:
3625 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3626 if (Val != Val2) return 0;
3627
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003628 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3629 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3630 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3631 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3632 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3633 return 0;
3634
3635 // We can't fold (ugt x, C) & (sgt x, C2).
3636 if (!PredicatesFoldable(LHSCC, RHSCC))
3637 return 0;
3638
3639 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003640 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003641 if (ICmpInst::isSignedPredicate(LHSCC) ||
3642 (ICmpInst::isEquality(LHSCC) &&
3643 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003644 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003645 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003646 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3647
3648 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003649 std::swap(LHS, RHS);
3650 std::swap(LHSCst, RHSCst);
3651 std::swap(LHSCC, RHSCC);
3652 }
3653
3654 // At this point, we know we have have two icmp instructions
3655 // comparing a value against two constants and and'ing the result
3656 // together. Because of the above check, we know that we only have
3657 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3658 // (from the FoldICmpLogical check above), that the two constants
3659 // are not equal and that the larger constant is on the RHS
3660 assert(LHSCst != RHSCst && "Compares not folded above?");
3661
3662 switch (LHSCC) {
3663 default: assert(0 && "Unknown integer condition code!");
3664 case ICmpInst::ICMP_EQ:
3665 switch (RHSCC) {
3666 default: assert(0 && "Unknown integer condition code!");
3667 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3668 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3669 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3670 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3671 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3672 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3673 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3674 return ReplaceInstUsesWith(I, LHS);
3675 }
3676 case ICmpInst::ICMP_NE:
3677 switch (RHSCC) {
3678 default: assert(0 && "Unknown integer condition code!");
3679 case ICmpInst::ICMP_ULT:
3680 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3681 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3682 break; // (X != 13 & X u< 15) -> no change
3683 case ICmpInst::ICMP_SLT:
3684 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3685 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3686 break; // (X != 13 & X s< 15) -> no change
3687 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3688 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3689 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3690 return ReplaceInstUsesWith(I, RHS);
3691 case ICmpInst::ICMP_NE:
3692 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3693 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3694 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3695 Val->getName()+".off");
3696 InsertNewInstBefore(Add, I);
3697 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3698 ConstantInt::get(Add->getType(), 1));
3699 }
3700 break; // (X != 13 & X != 15) -> no change
3701 }
3702 break;
3703 case ICmpInst::ICMP_ULT:
3704 switch (RHSCC) {
3705 default: assert(0 && "Unknown integer condition code!");
3706 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3707 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3709 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3710 break;
3711 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3712 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3713 return ReplaceInstUsesWith(I, LHS);
3714 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3715 break;
3716 }
3717 break;
3718 case ICmpInst::ICMP_SLT:
3719 switch (RHSCC) {
3720 default: assert(0 && "Unknown integer condition code!");
3721 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3722 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3723 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3724 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3725 break;
3726 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3727 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3728 return ReplaceInstUsesWith(I, LHS);
3729 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3730 break;
3731 }
3732 break;
3733 case ICmpInst::ICMP_UGT:
3734 switch (RHSCC) {
3735 default: assert(0 && "Unknown integer condition code!");
3736 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3737 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3738 return ReplaceInstUsesWith(I, RHS);
3739 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3740 break;
3741 case ICmpInst::ICMP_NE:
3742 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3743 return new ICmpInst(LHSCC, Val, RHSCst);
3744 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003745 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003746 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3747 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3748 break;
3749 }
3750 break;
3751 case ICmpInst::ICMP_SGT:
3752 switch (RHSCC) {
3753 default: assert(0 && "Unknown integer condition code!");
3754 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3755 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3756 return ReplaceInstUsesWith(I, RHS);
3757 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3758 break;
3759 case ICmpInst::ICMP_NE:
3760 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3761 return new ICmpInst(LHSCC, Val, RHSCst);
3762 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003763 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003764 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3765 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3766 break;
3767 }
3768 break;
3769 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003770
3771 return 0;
3772}
3773
3774
Chris Lattner7e708292002-06-25 16:13:24 +00003775Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003776 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003778
Chris Lattnere87597f2004-10-16 18:11:37 +00003779 if (isa<UndefValue>(Op1)) // X & undef -> 0
3780 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3781
Chris Lattner6e7ba452005-01-01 16:22:27 +00003782 // and X, X = X
3783 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003784 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003785
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003786 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003787 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003788 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003789 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3790 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3791 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003792 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003793 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003794 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003795 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003796 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003797 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003798 } else if (isa<ConstantAggregateZero>(Op1)) {
3799 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003800 }
3801 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003802
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003803 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003804 const APInt& AndRHSMask = AndRHS->getValue();
3805 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003806
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003807 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003808 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003809 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003810 Value *Op0LHS = Op0I->getOperand(0);
3811 Value *Op0RHS = Op0I->getOperand(1);
3812 switch (Op0I->getOpcode()) {
3813 case Instruction::Xor:
3814 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003815 // If the mask is only needed on one incoming arm, push it up.
3816 if (Op0I->hasOneUse()) {
3817 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3818 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003819 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003820 Op0RHS->getName()+".masked");
3821 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003822 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003823 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003824 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003825 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003826 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3827 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003828 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003829 Op0LHS->getName()+".masked");
3830 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003831 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003832 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3833 }
3834 }
3835
Chris Lattner6e7ba452005-01-01 16:22:27 +00003836 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003837 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003838 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3839 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3840 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3841 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003842 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003843 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003844 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003845 break;
3846
3847 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003848 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3849 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3850 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3851 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003852 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003853
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003854 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3855 // has 1's for all bits that the subtraction with A might affect.
3856 if (Op0I->hasOneUse()) {
3857 uint32_t BitWidth = AndRHSMask.getBitWidth();
3858 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3859 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3860
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003861 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003862 if (!(A && A->isZero()) && // avoid infinite recursion.
3863 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003864 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3865 InsertNewInstBefore(NewNeg, I);
3866 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3867 }
3868 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003869 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003870
3871 case Instruction::Shl:
3872 case Instruction::LShr:
3873 // (1 << x) & 1 --> zext(x == 0)
3874 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003875 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003876 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3877 Constant::getNullValue(I.getType()));
3878 InsertNewInstBefore(NewICmp, I);
3879 return new ZExtInst(NewICmp, I.getType());
3880 }
3881 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003882 }
3883
Chris Lattner58403262003-07-23 19:25:52 +00003884 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003885 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003886 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003887 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003888 // If this is an integer truncation or change from signed-to-unsigned, and
3889 // if the source is an and/or with immediate, transform it. This
3890 // frequently occurs for bitfield accesses.
3891 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003892 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003893 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003894 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003895 if (CastOp->getOpcode() == Instruction::And) {
3896 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003897 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3898 // This will fold the two constants together, which may allow
3899 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003900 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003901 CastOp->getOperand(0), I.getType(),
3902 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003903 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003904 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003905 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003906 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003907 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003908 } else if (CastOp->getOpcode() == Instruction::Or) {
3909 // Change: and (cast (or X, C1) to T), C2
3910 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003911 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003912 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3913 return ReplaceInstUsesWith(I, AndRHS);
3914 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003915 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003916 }
Chris Lattner06782f82003-07-23 19:36:21 +00003917 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003918
3919 // Try to fold constant and into select arguments.
3920 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003921 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003922 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003923 if (isa<PHINode>(Op0))
3924 if (Instruction *NV = FoldOpIntoPhi(I))
3925 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003926 }
3927
Chris Lattner8d969642003-03-10 23:06:50 +00003928 Value *Op0NotVal = dyn_castNotVal(Op0);
3929 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003930
Chris Lattner5b62aa72004-06-18 06:07:51 +00003931 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3932 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3933
Misha Brukmancb6267b2004-07-30 12:50:08 +00003934 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003935 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003936 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003937 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003938 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003939 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003940 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003941
3942 {
Chris Lattner003b6202007-06-15 05:58:24 +00003943 Value *A = 0, *B = 0, *C = 0, *D = 0;
3944 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003945 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3946 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003947
3948 // (A|B) & ~(A&B) -> A^B
3949 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3950 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003951 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003952 }
3953 }
3954
3955 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003956 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3957 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003958
3959 // ~(A&B) & (A|B) -> A^B
3960 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3961 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003962 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003963 }
3964 }
Chris Lattner64daab52006-04-01 08:03:55 +00003965
3966 if (Op0->hasOneUse() &&
3967 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3968 if (A == Op1) { // (A^B)&A -> A&(A^B)
3969 I.swapOperands(); // Simplify below
3970 std::swap(Op0, Op1);
3971 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3972 cast<BinaryOperator>(Op0)->swapOperands();
3973 I.swapOperands(); // Simplify below
3974 std::swap(Op0, Op1);
3975 }
3976 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00003977
Chris Lattner64daab52006-04-01 08:03:55 +00003978 if (Op1->hasOneUse() &&
3979 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3980 if (B == Op0) { // B&(A^B) -> B&(B^A)
3981 cast<BinaryOperator>(Op1)->swapOperands();
3982 std::swap(A, B);
3983 }
3984 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003985 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003986 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003987 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003988 }
3989 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00003990
3991 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00003992 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3993 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3994 return BinaryOperator::CreateAnd(A, Op1);
3995 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3996 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3997 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00003998 }
3999
Reid Spencere4d87aa2006-12-23 06:05:41 +00004000 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4001 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4002 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004003 return R;
4004
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004005 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4006 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4007 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004008 }
4009
Chris Lattner6fc205f2006-05-05 06:39:07 +00004010 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004011 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4012 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4013 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4014 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004015 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004016 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004017 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4018 I.getType(), TD) &&
4019 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4020 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004021 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004022 Op1C->getOperand(0),
4023 I.getName());
4024 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004025 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004026 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004027 }
Chris Lattnere511b742006-11-14 07:46:50 +00004028
4029 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004030 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004033 SI0->getOperand(1) == SI1->getOperand(1) &&
4034 (SI0->hasOneUse() || SI1->hasOneUse())) {
4035 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004036 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004037 SI1->getOperand(0),
4038 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004039 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004040 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004041 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004042 }
4043
Evan Cheng8db90722008-10-14 17:15:11 +00004044 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004045 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4046 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4047 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004048 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4049 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004050 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4051 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4052 // If either of the constants are nans, then the whole thing returns
4053 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004054 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004055 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4056 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4057 RHS->getOperand(0));
4058 }
Evan Cheng8db90722008-10-14 17:15:11 +00004059 } else {
4060 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4061 FCmpInst::Predicate Op0CC, Op1CC;
4062 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4063 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004064 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4065 // Swap RHS operands to match LHS.
4066 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4067 std::swap(Op1LHS, Op1RHS);
4068 }
Evan Cheng8db90722008-10-14 17:15:11 +00004069 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4070 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4071 if (Op0CC == Op1CC)
4072 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4073 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4074 Op1CC == FCmpInst::FCMP_FALSE)
4075 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4076 else if (Op0CC == FCmpInst::FCMP_TRUE)
4077 return ReplaceInstUsesWith(I, Op1);
4078 else if (Op1CC == FCmpInst::FCMP_TRUE)
4079 return ReplaceInstUsesWith(I, Op0);
4080 bool Op0Ordered;
4081 bool Op1Ordered;
4082 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4083 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4084 if (Op1Pred == 0) {
4085 std::swap(Op0, Op1);
4086 std::swap(Op0Pred, Op1Pred);
4087 std::swap(Op0Ordered, Op1Ordered);
4088 }
4089 if (Op0Pred == 0) {
4090 // uno && ueq -> uno && (uno || eq) -> ueq
4091 // ord && olt -> ord && (ord && lt) -> olt
4092 if (Op0Ordered == Op1Ordered)
4093 return ReplaceInstUsesWith(I, Op1);
4094 // uno && oeq -> uno && (ord && eq) -> false
4095 // uno && ord -> false
4096 if (!Op0Ordered)
4097 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4098 // ord && ueq -> ord && (uno || eq) -> oeq
4099 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4100 Op0LHS, Op0RHS));
4101 }
4102 }
4103 }
4104 }
Chris Lattner99c65742007-10-24 05:38:08 +00004105 }
4106 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004107
Chris Lattner7e708292002-06-25 16:13:24 +00004108 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004109}
4110
Chris Lattner8c34cd22008-10-05 02:13:19 +00004111/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4112/// capable of providing pieces of a bswap. The subexpression provides pieces
4113/// of a bswap if it is proven that each of the non-zero bytes in the output of
4114/// the expression came from the corresponding "byte swapped" byte in some other
4115/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4116/// we know that the expression deposits the low byte of %X into the high byte
4117/// of the bswap result and that all other bytes are zero. This expression is
4118/// accepted, the high byte of ByteValues is set to X to indicate a correct
4119/// match.
4120///
4121/// This function returns true if the match was unsuccessful and false if so.
4122/// On entry to the function the "OverallLeftShift" is a signed integer value
4123/// indicating the number of bytes that the subexpression is later shifted. For
4124/// example, if the expression is later right shifted by 16 bits, the
4125/// OverallLeftShift value would be -2 on entry. This is used to specify which
4126/// byte of ByteValues is actually being set.
4127///
4128/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4129/// byte is masked to zero by a user. For example, in (X & 255), X will be
4130/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4131/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4132/// always in the local (OverallLeftShift) coordinate space.
4133///
4134static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4135 SmallVector<Value*, 8> &ByteValues) {
4136 if (Instruction *I = dyn_cast<Instruction>(V)) {
4137 // If this is an or instruction, it may be an inner node of the bswap.
4138 if (I->getOpcode() == Instruction::Or) {
4139 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4140 ByteValues) ||
4141 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4142 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004143 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004144
4145 // If this is a logical shift by a constant multiple of 8, recurse with
4146 // OverallLeftShift and ByteMask adjusted.
4147 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4148 unsigned ShAmt =
4149 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4150 // Ensure the shift amount is defined and of a byte value.
4151 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4152 return true;
4153
4154 unsigned ByteShift = ShAmt >> 3;
4155 if (I->getOpcode() == Instruction::Shl) {
4156 // X << 2 -> collect(X, +2)
4157 OverallLeftShift += ByteShift;
4158 ByteMask >>= ByteShift;
4159 } else {
4160 // X >>u 2 -> collect(X, -2)
4161 OverallLeftShift -= ByteShift;
4162 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004163 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004164 }
4165
4166 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4167 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4168
4169 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4170 ByteValues);
4171 }
4172
4173 // If this is a logical 'and' with a mask that clears bytes, clear the
4174 // corresponding bytes in ByteMask.
4175 if (I->getOpcode() == Instruction::And &&
4176 isa<ConstantInt>(I->getOperand(1))) {
4177 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4178 unsigned NumBytes = ByteValues.size();
4179 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4180 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4181
4182 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4183 // If this byte is masked out by a later operation, we don't care what
4184 // the and mask is.
4185 if ((ByteMask & (1 << i)) == 0)
4186 continue;
4187
4188 // If the AndMask is all zeros for this byte, clear the bit.
4189 APInt MaskB = AndMask & Byte;
4190 if (MaskB == 0) {
4191 ByteMask &= ~(1U << i);
4192 continue;
4193 }
4194
4195 // If the AndMask is not all ones for this byte, it's not a bytezap.
4196 if (MaskB != Byte)
4197 return true;
4198
4199 // Otherwise, this byte is kept.
4200 }
4201
4202 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4203 ByteValues);
4204 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004205 }
4206
Chris Lattner8c34cd22008-10-05 02:13:19 +00004207 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4208 // the input value to the bswap. Some observations: 1) if more than one byte
4209 // is demanded from this input, then it could not be successfully assembled
4210 // into a byteswap. At least one of the two bytes would not be aligned with
4211 // their ultimate destination.
4212 if (!isPowerOf2_32(ByteMask)) return true;
4213 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004214
Chris Lattner8c34cd22008-10-05 02:13:19 +00004215 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4216 // is demanded, it needs to go into byte 0 of the result. This means that the
4217 // byte needs to be shifted until it lands in the right byte bucket. The
4218 // shift amount depends on the position: if the byte is coming from the high
4219 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4220 // low part, it must be shifted left.
4221 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4222 if (InputByteNo < ByteValues.size()/2) {
4223 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4224 return true;
4225 } else {
4226 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4227 return true;
4228 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004229
4230 // If the destination byte value is already defined, the values are or'd
4231 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004232 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004233 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004234 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004235 return false;
4236}
4237
4238/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4239/// If so, insert the new bswap intrinsic and return it.
4240Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004241 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004242 if (!ITy || ITy->getBitWidth() % 16 ||
4243 // ByteMask only allows up to 32-byte values.
4244 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004245 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004246
4247 /// ByteValues - For each byte of the result, we keep track of which value
4248 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004249 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004250 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004251
4252 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004253 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4254 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004255 return 0;
4256
4257 // Check to see if all of the bytes come from the same value.
4258 Value *V = ByteValues[0];
4259 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4260
4261 // Check to make sure that all of the bytes come from the same value.
4262 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4263 if (ByteValues[i] != V)
4264 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004265 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004266 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004267 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004268 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004269}
4270
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004271/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4272/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4273/// we can simplify this expression to "cond ? C : D or B".
4274static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4275 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004276 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004277 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004278 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004279 return 0;
4280
Chris Lattnera6a474d2008-11-16 04:26:55 +00004281 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004282 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004283 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004284 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004285 return SelectInst::Create(Cond, C, B);
4286 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004287 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004288 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004289 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004290 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004291 return 0;
4292}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004293
Chris Lattner69d4ced2008-11-16 05:20:07 +00004294/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4295Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4296 ICmpInst *LHS, ICmpInst *RHS) {
4297 Value *Val, *Val2;
4298 ConstantInt *LHSCst, *RHSCst;
4299 ICmpInst::Predicate LHSCC, RHSCC;
4300
4301 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4302 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4303 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4304 return 0;
4305
4306 // From here on, we only handle:
4307 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4308 if (Val != Val2) return 0;
4309
4310 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4311 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4312 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4313 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4314 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4315 return 0;
4316
4317 // We can't fold (ugt x, C) | (sgt x, C2).
4318 if (!PredicatesFoldable(LHSCC, RHSCC))
4319 return 0;
4320
4321 // Ensure that the larger constant is on the RHS.
4322 bool ShouldSwap;
4323 if (ICmpInst::isSignedPredicate(LHSCC) ||
4324 (ICmpInst::isEquality(LHSCC) &&
4325 ICmpInst::isSignedPredicate(RHSCC)))
4326 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4327 else
4328 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4329
4330 if (ShouldSwap) {
4331 std::swap(LHS, RHS);
4332 std::swap(LHSCst, RHSCst);
4333 std::swap(LHSCC, RHSCC);
4334 }
4335
4336 // At this point, we know we have have two icmp instructions
4337 // comparing a value against two constants and or'ing the result
4338 // together. Because of the above check, we know that we only have
4339 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4340 // FoldICmpLogical check above), that the two constants are not
4341 // equal.
4342 assert(LHSCst != RHSCst && "Compares not folded above?");
4343
4344 switch (LHSCC) {
4345 default: assert(0 && "Unknown integer condition code!");
4346 case ICmpInst::ICMP_EQ:
4347 switch (RHSCC) {
4348 default: assert(0 && "Unknown integer condition code!");
4349 case ICmpInst::ICMP_EQ:
4350 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4351 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4352 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4353 Val->getName()+".off");
4354 InsertNewInstBefore(Add, I);
4355 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4356 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4357 }
4358 break; // (X == 13 | X == 15) -> no change
4359 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4360 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4361 break;
4362 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4363 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4364 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4365 return ReplaceInstUsesWith(I, RHS);
4366 }
4367 break;
4368 case ICmpInst::ICMP_NE:
4369 switch (RHSCC) {
4370 default: assert(0 && "Unknown integer condition code!");
4371 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4372 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4373 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4374 return ReplaceInstUsesWith(I, LHS);
4375 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4376 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4377 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4378 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4379 }
4380 break;
4381 case ICmpInst::ICMP_ULT:
4382 switch (RHSCC) {
4383 default: assert(0 && "Unknown integer condition code!");
4384 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4385 break;
4386 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4387 // If RHSCst is [us]MAXINT, it is always false. Not handling
4388 // this can cause overflow.
4389 if (RHSCst->isMaxValue(false))
4390 return ReplaceInstUsesWith(I, LHS);
4391 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4392 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4393 break;
4394 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4395 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4396 return ReplaceInstUsesWith(I, RHS);
4397 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4398 break;
4399 }
4400 break;
4401 case ICmpInst::ICMP_SLT:
4402 switch (RHSCC) {
4403 default: assert(0 && "Unknown integer condition code!");
4404 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4405 break;
4406 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4407 // If RHSCst is [us]MAXINT, it is always false. Not handling
4408 // this can cause overflow.
4409 if (RHSCst->isMaxValue(true))
4410 return ReplaceInstUsesWith(I, LHS);
4411 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4412 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4413 break;
4414 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4415 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4416 return ReplaceInstUsesWith(I, RHS);
4417 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4418 break;
4419 }
4420 break;
4421 case ICmpInst::ICMP_UGT:
4422 switch (RHSCC) {
4423 default: assert(0 && "Unknown integer condition code!");
4424 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4425 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4426 return ReplaceInstUsesWith(I, LHS);
4427 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4428 break;
4429 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4430 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4431 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4432 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4433 break;
4434 }
4435 break;
4436 case ICmpInst::ICMP_SGT:
4437 switch (RHSCC) {
4438 default: assert(0 && "Unknown integer condition code!");
4439 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4440 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4441 return ReplaceInstUsesWith(I, LHS);
4442 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4443 break;
4444 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4445 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4446 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4447 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4448 break;
4449 }
4450 break;
4451 }
4452 return 0;
4453}
4454
Bill Wendlinga698a472008-12-01 08:23:25 +00004455/// FoldOrWithConstants - This helper function folds:
4456///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004457/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004458///
4459/// into:
4460///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004461/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004462///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004463/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004464Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004465 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004466 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4467 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004468
Bill Wendling286a0542008-12-02 06:24:20 +00004469 Value *V1 = 0;
4470 ConstantInt *CI2 = 0;
4471 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004472
Bill Wendling29976b92008-12-02 06:18:11 +00004473 APInt Xor = CI1->getValue() ^ CI2->getValue();
4474 if (!Xor.isAllOnesValue()) return 0;
4475
Bill Wendling286a0542008-12-02 06:24:20 +00004476 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004477 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004478 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4479 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004480 }
4481
4482 return 0;
4483}
4484
Chris Lattner7e708292002-06-25 16:13:24 +00004485Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004486 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004487 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004488
Chris Lattner42593e62007-03-24 23:56:43 +00004489 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004490 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004491
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004492 // or X, X = X
4493 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004494 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004495
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004496 // See if we can simplify any instructions used by the instruction whose sole
4497 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004498 if (!isa<VectorType>(I.getType())) {
4499 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4500 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4501 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4502 KnownZero, KnownOne))
4503 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004504 } else if (isa<ConstantAggregateZero>(Op1)) {
4505 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4506 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4507 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4508 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004509 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004510
4511
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004512
Chris Lattner3f5b8772002-05-06 16:14:14 +00004513 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004515 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004516 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4517 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004518 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004519 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004520 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004521 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004522 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004523 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004524
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004525 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4526 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004527 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004528 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004529 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004530 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004531 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004532 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004533
4534 // Try to fold constant and into select arguments.
4535 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004536 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004537 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004538 if (isa<PHINode>(Op0))
4539 if (Instruction *NV = FoldOpIntoPhi(I))
4540 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004541 }
4542
Chris Lattner4f637d42006-01-06 17:59:59 +00004543 Value *A = 0, *B = 0;
4544 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004545
4546 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4547 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4548 return ReplaceInstUsesWith(I, Op1);
4549 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4550 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4551 return ReplaceInstUsesWith(I, Op0);
4552
Chris Lattner6423d4c2006-07-10 20:25:24 +00004553 // (A | B) | C and A | (B | C) -> bswap if possible.
4554 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004555 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004556 match(Op1, m_Or(m_Value(), m_Value())) ||
4557 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4558 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004559 if (Instruction *BSwap = MatchBSwap(I))
4560 return BSwap;
4561 }
4562
Chris Lattner6e4c6492005-05-09 04:58:36 +00004563 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4564 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004565 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004566 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004567 InsertNewInstBefore(NOr, I);
4568 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004569 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004570 }
4571
4572 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4573 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004574 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004575 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004576 InsertNewInstBefore(NOr, I);
4577 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004578 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004579 }
4580
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004581 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004582 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004583 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4584 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004585 Value *V1 = 0, *V2 = 0, *V3 = 0;
4586 C1 = dyn_cast<ConstantInt>(C);
4587 C2 = dyn_cast<ConstantInt>(D);
4588 if (C1 && C2) { // (A & C1)|(B & C2)
4589 // If we have: ((V + N) & C1) | (V & C2)
4590 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4591 // replace with V+N.
4592 if (C1->getValue() == ~C2->getValue()) {
4593 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4594 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4595 // Add commutes, try both ways.
4596 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4597 return ReplaceInstUsesWith(I, A);
4598 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4599 return ReplaceInstUsesWith(I, A);
4600 }
4601 // Or commutes, try both ways.
4602 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4603 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4604 // Add commutes, try both ways.
4605 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4606 return ReplaceInstUsesWith(I, B);
4607 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4608 return ReplaceInstUsesWith(I, B);
4609 }
4610 }
Chris Lattner044e5332007-04-08 08:01:49 +00004611 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004612 }
4613
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004614 // Check to see if we have any common things being and'ed. If so, find the
4615 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004616 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4617 if (A == B) // (A & C)|(A & D) == A & (C|D)
4618 V1 = A, V2 = C, V3 = D;
4619 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4620 V1 = A, V2 = B, V3 = C;
4621 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4622 V1 = C, V2 = A, V3 = D;
4623 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4624 V1 = C, V2 = A, V3 = B;
4625
4626 if (V1) {
4627 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004628 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4629 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004630 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004631 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004632
Dan Gohman1975d032008-10-30 20:40:10 +00004633 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004634 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4635 return Match;
4636 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4637 return Match;
4638 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4639 return Match;
4640 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4641 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004642
Bill Wendlingb01865c2008-11-30 13:52:49 +00004643 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004644 if ((match(C, m_Not(m_Specific(D))) &&
4645 match(B, m_Not(m_Specific(A)))))
4646 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004647 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004648 if ((match(A, m_Not(m_Specific(D))) &&
4649 match(B, m_Not(m_Specific(C)))))
4650 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004651 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004652 if ((match(C, m_Not(m_Specific(B))) &&
4653 match(D, m_Not(m_Specific(A)))))
4654 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004655 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004656 if ((match(A, m_Not(m_Specific(B))) &&
4657 match(D, m_Not(m_Specific(C)))))
4658 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004659 }
Chris Lattnere511b742006-11-14 07:46:50 +00004660
4661 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004662 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4663 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4664 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004665 SI0->getOperand(1) == SI1->getOperand(1) &&
4666 (SI0->hasOneUse() || SI1->hasOneUse())) {
4667 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004668 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004669 SI1->getOperand(0),
4670 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004671 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004672 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004673 }
4674 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004675
Bill Wendlingb3833d12008-12-01 01:07:11 +00004676 // ((A|B)&1)|(B&-2) -> (A&1) | B
4677 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4678 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004679 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004680 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004681 }
4682 // (B&-2)|((A|B)&1) -> (A&1) | B
4683 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4684 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004685 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004686 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004687 }
4688
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004689 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4690 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004691 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004692 } else {
4693 A = 0;
4694 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004695 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004696 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4697 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004698 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004699
Misha Brukmancb6267b2004-07-30 12:50:08 +00004700 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004701 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004702 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004703 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004704 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004705 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004706 }
Chris Lattnera2881962003-02-18 19:28:33 +00004707
Reid Spencere4d87aa2006-12-23 06:05:41 +00004708 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4709 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4710 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004711 return R;
4712
Chris Lattner69d4ced2008-11-16 05:20:07 +00004713 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4714 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4715 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004716 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004717
4718 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004719 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004720 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004721 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004722 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4723 !isa<ICmpInst>(Op1C->getOperand(0))) {
4724 const Type *SrcTy = Op0C->getOperand(0)->getType();
4725 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4726 // Only do this if the casts both really cause code to be
4727 // generated.
4728 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4729 I.getType(), TD) &&
4730 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4731 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004732 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004733 Op1C->getOperand(0),
4734 I.getName());
4735 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004736 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004737 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004738 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004739 }
Chris Lattner99c65742007-10-24 05:38:08 +00004740 }
4741
4742
4743 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4744 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4745 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4746 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004747 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004748 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004749 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4750 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4751 // If either of the constants are nans, then the whole thing returns
4752 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004753 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004754 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4755
4756 // Otherwise, no need to compare the two constants, compare the
4757 // rest.
4758 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4759 RHS->getOperand(0));
4760 }
Evan Cheng40300622008-10-14 18:44:08 +00004761 } else {
4762 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4763 FCmpInst::Predicate Op0CC, Op1CC;
4764 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4765 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4766 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4767 // Swap RHS operands to match LHS.
4768 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4769 std::swap(Op1LHS, Op1RHS);
4770 }
4771 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4772 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4773 if (Op0CC == Op1CC)
4774 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4775 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4776 Op1CC == FCmpInst::FCMP_TRUE)
4777 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4778 else if (Op0CC == FCmpInst::FCMP_FALSE)
4779 return ReplaceInstUsesWith(I, Op1);
4780 else if (Op1CC == FCmpInst::FCMP_FALSE)
4781 return ReplaceInstUsesWith(I, Op0);
4782 bool Op0Ordered;
4783 bool Op1Ordered;
4784 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4785 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4786 if (Op0Ordered == Op1Ordered) {
4787 // If both are ordered or unordered, return a new fcmp with
4788 // or'ed predicates.
4789 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4790 Op0LHS, Op0RHS);
4791 if (Instruction *I = dyn_cast<Instruction>(RV))
4792 return I;
4793 // Otherwise, it's a constant boolean value...
4794 return ReplaceInstUsesWith(I, RV);
4795 }
4796 }
4797 }
4798 }
Chris Lattner99c65742007-10-24 05:38:08 +00004799 }
4800 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004801
Chris Lattner7e708292002-06-25 16:13:24 +00004802 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004803}
4804
Dan Gohman844731a2008-05-13 00:00:25 +00004805namespace {
4806
Chris Lattnerc317d392004-02-16 01:20:27 +00004807// XorSelf - Implements: X ^ X --> 0
4808struct XorSelf {
4809 Value *RHS;
4810 XorSelf(Value *rhs) : RHS(rhs) {}
4811 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4812 Instruction *apply(BinaryOperator &Xor) const {
4813 return &Xor;
4814 }
4815};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004816
Dan Gohman844731a2008-05-13 00:00:25 +00004817}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004818
Chris Lattner7e708292002-06-25 16:13:24 +00004819Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004820 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004822
Evan Chengd34af782008-03-25 20:07:13 +00004823 if (isa<UndefValue>(Op1)) {
4824 if (isa<UndefValue>(Op0))
4825 // Handle undef ^ undef -> 0 special case. This is a common
4826 // idiom (misuse).
4827 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004828 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004829 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004830
Chris Lattnerc317d392004-02-16 01:20:27 +00004831 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4832 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004833 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004834 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004835 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004836
4837 // See if we can simplify any instructions used by the instruction whose sole
4838 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004839 if (!isa<VectorType>(I.getType())) {
4840 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4841 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4842 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4843 KnownZero, KnownOne))
4844 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004845 } else if (isa<ConstantAggregateZero>(Op1)) {
4846 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004847 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004848
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004849 // Is this a ~ operation?
4850 if (Value *NotOp = dyn_castNotVal(&I)) {
4851 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4852 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4853 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4854 if (Op0I->getOpcode() == Instruction::And ||
4855 Op0I->getOpcode() == Instruction::Or) {
4856 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4857 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4858 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004859 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004860 Op0I->getOperand(1)->getName()+".not");
4861 InsertNewInstBefore(NotY, I);
4862 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004863 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004864 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004865 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004866 }
4867 }
4868 }
4869 }
4870
4871
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004872 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004873 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004874 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004875 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004876 return new ICmpInst(ICI->getInversePredicate(),
4877 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004878
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004879 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4880 return new FCmpInst(FCI->getInversePredicate(),
4881 FCI->getOperand(0), FCI->getOperand(1));
4882 }
4883
Nick Lewycky517e1f52008-05-31 19:01:33 +00004884 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4885 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4886 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4887 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4888 Instruction::CastOps Opcode = Op0C->getOpcode();
4889 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4890 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4891 Op0C->getDestTy())) {
4892 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4893 CI->getOpcode(), CI->getInversePredicate(),
4894 CI->getOperand(0), CI->getOperand(1)), I);
4895 NewCI->takeName(CI);
4896 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4897 }
4898 }
4899 }
4900 }
4901 }
4902
Reid Spencere4d87aa2006-12-23 06:05:41 +00004903 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004904 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004905 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4906 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004907 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4908 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004909 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004910 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004911 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004912
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004913 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004914 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004915 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004916 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004917 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004918 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004919 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004920 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004921 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004922 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004923 // (X + C) ^ signbit -> (X + C + signbit)
4924 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004925 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004926
Chris Lattner7c4049c2004-01-12 19:35:11 +00004927 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004928 } else if (Op0I->getOpcode() == Instruction::Or) {
4929 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004930 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004931 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4932 // Anything in both C1 and C2 is known to be zero, remove it from
4933 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004934 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004935 NewRHS = ConstantExpr::getAnd(NewRHS,
4936 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004937 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004938 I.setOperand(0, Op0I->getOperand(0));
4939 I.setOperand(1, NewRHS);
4940 return &I;
4941 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004942 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004943 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004944 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004945
4946 // Try to fold constant and into select arguments.
4947 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004948 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004949 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004950 if (isa<PHINode>(Op0))
4951 if (Instruction *NV = FoldOpIntoPhi(I))
4952 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004953 }
4954
Chris Lattner8d969642003-03-10 23:06:50 +00004955 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004956 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004957 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004958
Chris Lattner8d969642003-03-10 23:06:50 +00004959 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004960 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004961 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004962
Chris Lattner318bf792007-03-18 22:51:34 +00004963
4964 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4965 if (Op1I) {
4966 Value *A, *B;
4967 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4968 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004969 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004970 I.swapOperands();
4971 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004972 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004973 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004974 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004975 }
Chris Lattnercb504b92008-11-16 05:38:51 +00004976 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4977 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
4978 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4979 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00004980 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004981 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004982 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004983 std::swap(A, B);
4984 }
Chris Lattner318bf792007-03-18 22:51:34 +00004985 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004986 I.swapOperands(); // Simplified below.
4987 std::swap(Op0, Op1);
4988 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004989 }
Chris Lattner318bf792007-03-18 22:51:34 +00004990 }
4991
4992 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4993 if (Op0I) {
4994 Value *A, *B;
4995 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4996 if (A == Op1) // (B|A)^B == (A|B)^B
4997 std::swap(A, B);
4998 if (B == Op1) { // (A|B)^B == A & ~B
4999 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005000 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5001 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005002 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005003 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5004 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5005 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5006 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005007 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5008 if (A == Op1) // (A&B)^A -> (B&A)^A
5009 std::swap(A, B);
5010 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005011 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005012 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005013 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5014 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005015 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005016 }
Chris Lattner318bf792007-03-18 22:51:34 +00005017 }
5018
5019 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5020 if (Op0I && Op1I && Op0I->isShift() &&
5021 Op0I->getOpcode() == Op1I->getOpcode() &&
5022 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5023 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5024 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005025 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005026 Op1I->getOperand(0),
5027 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005028 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005029 Op1I->getOperand(1));
5030 }
5031
5032 if (Op0I && Op1I) {
5033 Value *A, *B, *C, *D;
5034 // (A & B)^(A | B) -> A ^ B
5035 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5036 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5037 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005038 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005039 }
5040 // (A | B)^(A & B) -> A ^ B
5041 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5042 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5043 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005044 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005045 }
5046
5047 // (A & B)^(C & D)
5048 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5049 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5050 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5051 // (X & Y)^(X & Y) -> (Y^Z) & X
5052 Value *X = 0, *Y = 0, *Z = 0;
5053 if (A == C)
5054 X = A, Y = B, Z = D;
5055 else if (A == D)
5056 X = A, Y = B, Z = C;
5057 else if (B == C)
5058 X = B, Y = A, Z = D;
5059 else if (B == D)
5060 X = B, Y = A, Z = C;
5061
5062 if (X) {
5063 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005064 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5065 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005066 }
5067 }
5068 }
5069
Reid Spencere4d87aa2006-12-23 06:05:41 +00005070 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5071 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5072 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005073 return R;
5074
Chris Lattner6fc205f2006-05-05 06:39:07 +00005075 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005076 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005077 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005078 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5079 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005080 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005081 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005082 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5083 I.getType(), TD) &&
5084 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5085 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005086 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005087 Op1C->getOperand(0),
5088 I.getName());
5089 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005090 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005091 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005092 }
Chris Lattner99c65742007-10-24 05:38:08 +00005093 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005094
Chris Lattner7e708292002-06-25 16:13:24 +00005095 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005096}
5097
Chris Lattnera96879a2004-09-29 17:40:11 +00005098/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5099/// overflowed for this type.
5100static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005101 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005102 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005103
Reid Spencere4e40032007-03-21 23:19:50 +00005104 if (IsSigned)
5105 if (In2->getValue().isNegative())
5106 return Result->getValue().sgt(In1->getValue());
5107 else
5108 return Result->getValue().slt(In1->getValue());
5109 else
5110 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005111}
5112
Dan Gohman1df3fd62008-09-10 23:30:57 +00005113/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5114/// overflowed for this type.
5115static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5116 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005117 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005118
5119 if (IsSigned)
5120 if (In2->getValue().isNegative())
5121 return Result->getValue().slt(In1->getValue());
5122 else
5123 return Result->getValue().sgt(In1->getValue());
5124 else
5125 return Result->getValue().ugt(In1->getValue());
5126}
5127
Chris Lattner574da9b2005-01-13 20:14:25 +00005128/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5129/// code necessary to compute the offset from the base pointer (without adding
5130/// in the base pointer). Return the result as a signed integer of intptr size.
5131static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5132 TargetData &TD = IC.getTargetData();
5133 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005134 const Type *IntPtrTy = TD.getIntPtrType();
5135 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005136
5137 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005138 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005139 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005140
Gabor Greif177dd3f2008-06-12 21:37:33 +00005141 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5142 ++i, ++GTI) {
5143 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005144 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005145 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5146 if (OpC->isZero()) continue;
5147
5148 // Handle a struct index, which adds its field offset to the pointer.
5149 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5150 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5151
5152 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5153 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005154 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005155 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005156 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005157 ConstantInt::get(IntPtrTy, Size),
5158 GEP->getName()+".offs"), I);
5159 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005160 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005161
5162 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5163 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5164 Scale = ConstantExpr::getMul(OC, Scale);
5165 if (Constant *RC = dyn_cast<Constant>(Result))
5166 Result = ConstantExpr::getAdd(RC, Scale);
5167 else {
5168 // Emit an add instruction.
5169 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005170 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005171 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005172 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005173 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005174 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005175 // Convert to correct type.
5176 if (Op->getType() != IntPtrTy) {
5177 if (Constant *OpC = dyn_cast<Constant>(Op))
5178 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5179 else
5180 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5181 Op->getName()+".c"), I);
5182 }
5183 if (Size != 1) {
5184 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5185 if (Constant *OpC = dyn_cast<Constant>(Op))
5186 Op = ConstantExpr::getMul(OpC, Scale);
5187 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005188 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005189 GEP->getName()+".idx"), I);
5190 }
5191
5192 // Emit an add instruction.
5193 if (isa<Constant>(Op) && isa<Constant>(Result))
5194 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5195 cast<Constant>(Result));
5196 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005197 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005198 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005199 }
5200 return Result;
5201}
5202
Chris Lattner10c0d912008-04-22 02:53:33 +00005203
5204/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5205/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5206/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5207/// complex, and scales are involved. The above expression would also be legal
5208/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5209/// later form is less amenable to optimization though, and we are allowed to
5210/// generate the first by knowing that pointer arithmetic doesn't overflow.
5211///
5212/// If we can't emit an optimized form for this expression, this returns null.
5213///
5214static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5215 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005216 TargetData &TD = IC.getTargetData();
5217 gep_type_iterator GTI = gep_type_begin(GEP);
5218
5219 // Check to see if this gep only has a single variable index. If so, and if
5220 // any constant indices are a multiple of its scale, then we can compute this
5221 // in terms of the scale of the variable index. For example, if the GEP
5222 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5223 // because the expression will cross zero at the same point.
5224 unsigned i, e = GEP->getNumOperands();
5225 int64_t Offset = 0;
5226 for (i = 1; i != e; ++i, ++GTI) {
5227 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5228 // Compute the aggregate offset of constant indices.
5229 if (CI->isZero()) continue;
5230
5231 // Handle a struct index, which adds its field offset to the pointer.
5232 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5233 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5234 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005235 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005236 Offset += Size*CI->getSExtValue();
5237 }
5238 } else {
5239 // Found our variable index.
5240 break;
5241 }
5242 }
5243
5244 // If there are no variable indices, we must have a constant offset, just
5245 // evaluate it the general way.
5246 if (i == e) return 0;
5247
5248 Value *VariableIdx = GEP->getOperand(i);
5249 // Determine the scale factor of the variable element. For example, this is
5250 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005251 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005252
5253 // Verify that there are no other variable indices. If so, emit the hard way.
5254 for (++i, ++GTI; i != e; ++i, ++GTI) {
5255 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5256 if (!CI) return 0;
5257
5258 // Compute the aggregate offset of constant indices.
5259 if (CI->isZero()) continue;
5260
5261 // Handle a struct index, which adds its field offset to the pointer.
5262 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5263 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5264 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005265 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005266 Offset += Size*CI->getSExtValue();
5267 }
5268 }
5269
5270 // Okay, we know we have a single variable index, which must be a
5271 // pointer/array/vector index. If there is no offset, life is simple, return
5272 // the index.
5273 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5274 if (Offset == 0) {
5275 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5276 // we don't need to bother extending: the extension won't affect where the
5277 // computation crosses zero.
5278 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5279 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5280 VariableIdx->getNameStart(), &I);
5281 return VariableIdx;
5282 }
5283
5284 // Otherwise, there is an index. The computation we will do will be modulo
5285 // the pointer size, so get it.
5286 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5287
5288 Offset &= PtrSizeMask;
5289 VariableScale &= PtrSizeMask;
5290
5291 // To do this transformation, any constant index must be a multiple of the
5292 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5293 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5294 // multiple of the variable scale.
5295 int64_t NewOffs = Offset / (int64_t)VariableScale;
5296 if (Offset != NewOffs*(int64_t)VariableScale)
5297 return 0;
5298
5299 // Okay, we can do this evaluation. Start by converting the index to intptr.
5300 const Type *IntPtrTy = TD.getIntPtrType();
5301 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005302 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005303 true /*SExt*/,
5304 VariableIdx->getNameStart(), &I);
5305 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005306 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005307}
5308
5309
Reid Spencere4d87aa2006-12-23 06:05:41 +00005310/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005311/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005312Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5313 ICmpInst::Predicate Cond,
5314 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005315 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005316
Chris Lattner10c0d912008-04-22 02:53:33 +00005317 // Look through bitcasts.
5318 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5319 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005320
Chris Lattner574da9b2005-01-13 20:14:25 +00005321 Value *PtrBase = GEPLHS->getOperand(0);
5322 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005323 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005324 // This transformation (ignoring the base and scales) is valid because we
5325 // know pointers can't overflow. See if we can output an optimized form.
5326 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5327
5328 // If not, synthesize the offset the hard way.
5329 if (Offset == 0)
5330 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005331 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5332 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005333 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005334 // If the base pointers are different, but the indices are the same, just
5335 // compare the base pointer.
5336 if (PtrBase != GEPRHS->getOperand(0)) {
5337 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005338 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005339 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005340 if (IndicesTheSame)
5341 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5342 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5343 IndicesTheSame = false;
5344 break;
5345 }
5346
5347 // If all indices are the same, just compare the base pointers.
5348 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005349 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5350 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005351
5352 // Otherwise, the base pointers are different and the indices are
5353 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005354 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005355 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005356
Chris Lattnere9d782b2005-01-13 22:25:21 +00005357 // If one of the GEPs has all zero indices, recurse.
5358 bool AllZeros = true;
5359 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5360 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5361 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5362 AllZeros = false;
5363 break;
5364 }
5365 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005366 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5367 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005368
5369 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005370 AllZeros = true;
5371 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5372 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5373 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5374 AllZeros = false;
5375 break;
5376 }
5377 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005378 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005379
Chris Lattner4401c9c2005-01-14 00:20:05 +00005380 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5381 // If the GEPs only differ by one index, compare it.
5382 unsigned NumDifferences = 0; // Keep track of # differences.
5383 unsigned DiffOperand = 0; // The operand that differs.
5384 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5385 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005386 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5387 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005388 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005389 NumDifferences = 2;
5390 break;
5391 } else {
5392 if (NumDifferences++) break;
5393 DiffOperand = i;
5394 }
5395 }
5396
5397 if (NumDifferences == 0) // SAME GEP?
5398 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005399 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005400 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005401
Chris Lattner4401c9c2005-01-14 00:20:05 +00005402 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005403 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5404 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005405 // Make sure we do a signed comparison here.
5406 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005407 }
5408 }
5409
Reid Spencere4d87aa2006-12-23 06:05:41 +00005410 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005411 // the result to fold to a constant!
5412 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5413 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5414 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5415 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5416 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005417 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005418 }
5419 }
5420 return 0;
5421}
5422
Chris Lattnera5406232008-05-19 20:18:56 +00005423/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5424///
5425Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5426 Instruction *LHSI,
5427 Constant *RHSC) {
5428 if (!isa<ConstantFP>(RHSC)) return 0;
5429 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5430
5431 // Get the width of the mantissa. We don't want to hack on conversions that
5432 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005433 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005434 if (MantissaWidth == -1) return 0; // Unknown.
5435
5436 // Check to see that the input is converted from an integer type that is small
5437 // enough that preserves all bits. TODO: check here for "known" sign bits.
5438 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5439 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5440
5441 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005442 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5443 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005444 ++InputSize;
5445
5446 // If the conversion would lose info, don't hack on this.
5447 if ((int)InputSize > MantissaWidth)
5448 return 0;
5449
5450 // Otherwise, we can potentially simplify the comparison. We know that it
5451 // will always come through as an integer value and we know the constant is
5452 // not a NAN (it would have been previously simplified).
5453 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5454
5455 ICmpInst::Predicate Pred;
5456 switch (I.getPredicate()) {
5457 default: assert(0 && "Unexpected predicate!");
5458 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005459 case FCmpInst::FCMP_OEQ:
5460 Pred = ICmpInst::ICMP_EQ;
5461 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005462 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005463 case FCmpInst::FCMP_OGT:
5464 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5465 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005466 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005467 case FCmpInst::FCMP_OGE:
5468 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5469 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005470 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005471 case FCmpInst::FCMP_OLT:
5472 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5473 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005474 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005475 case FCmpInst::FCMP_OLE:
5476 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5477 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005478 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005479 case FCmpInst::FCMP_ONE:
5480 Pred = ICmpInst::ICMP_NE;
5481 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005482 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005483 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005484 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005485 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005486 }
5487
5488 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5489
5490 // Now we know that the APFloat is a normal number, zero or inf.
5491
Chris Lattner85162782008-05-20 03:50:52 +00005492 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005493 // comparing an i8 to 300.0.
5494 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5495
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005496 if (!LHSUnsigned) {
5497 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5498 // and large values.
5499 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5500 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5501 APFloat::rmNearestTiesToEven);
5502 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5503 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5504 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005505 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5506 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005507 }
5508 } else {
5509 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5510 // +INF and large values.
5511 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5512 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5513 APFloat::rmNearestTiesToEven);
5514 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5515 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5516 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005517 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5518 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005519 }
Chris Lattnera5406232008-05-19 20:18:56 +00005520 }
5521
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005522 if (!LHSUnsigned) {
5523 // See if the RHS value is < SignedMin.
5524 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5525 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5526 APFloat::rmNearestTiesToEven);
5527 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5528 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5529 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005530 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5531 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005532 }
Chris Lattnera5406232008-05-19 20:18:56 +00005533 }
5534
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005535 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5536 // [0, UMAX], but it may still be fractional. See if it is fractional by
5537 // casting the FP value to the integer value and back, checking for equality.
5538 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005539 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5540 if (!RHS.isZero() &&
5541 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005542 // If we had a comparison against a fractional value, we have to adjust the
5543 // compare predicate and sometimes the value. RHSC is rounded towards zero
5544 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005545 switch (Pred) {
5546 default: assert(0 && "Unexpected integer comparison!");
5547 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005548 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005549 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005550 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005551 case ICmpInst::ICMP_ULE:
5552 // (float)int <= 4.4 --> int <= 4
5553 // (float)int <= -4.4 --> false
5554 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005555 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005556 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005557 case ICmpInst::ICMP_SLE:
5558 // (float)int <= 4.4 --> int <= 4
5559 // (float)int <= -4.4 --> int < -4
5560 if (RHS.isNegative())
5561 Pred = ICmpInst::ICMP_SLT;
5562 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005563 case ICmpInst::ICMP_ULT:
5564 // (float)int < -4.4 --> false
5565 // (float)int < 4.4 --> int <= 4
5566 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005567 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005568 Pred = ICmpInst::ICMP_ULE;
5569 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005570 case ICmpInst::ICMP_SLT:
5571 // (float)int < -4.4 --> int < -4
5572 // (float)int < 4.4 --> int <= 4
5573 if (!RHS.isNegative())
5574 Pred = ICmpInst::ICMP_SLE;
5575 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005576 case ICmpInst::ICMP_UGT:
5577 // (float)int > 4.4 --> int > 4
5578 // (float)int > -4.4 --> true
5579 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005580 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005581 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005582 case ICmpInst::ICMP_SGT:
5583 // (float)int > 4.4 --> int > 4
5584 // (float)int > -4.4 --> int >= -4
5585 if (RHS.isNegative())
5586 Pred = ICmpInst::ICMP_SGE;
5587 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005588 case ICmpInst::ICMP_UGE:
5589 // (float)int >= -4.4 --> true
5590 // (float)int >= 4.4 --> int > 4
5591 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005592 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005593 Pred = ICmpInst::ICMP_UGT;
5594 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005595 case ICmpInst::ICMP_SGE:
5596 // (float)int >= -4.4 --> int >= -4
5597 // (float)int >= 4.4 --> int > 4
5598 if (!RHS.isNegative())
5599 Pred = ICmpInst::ICMP_SGT;
5600 break;
5601 }
5602 }
5603
5604 // Lower this FP comparison into an appropriate integer version of the
5605 // comparison.
5606 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5607}
5608
Reid Spencere4d87aa2006-12-23 06:05:41 +00005609Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5610 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005611 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005612
Chris Lattner58e97462007-01-14 19:42:17 +00005613 // Fold trivial predicates.
5614 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005615 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005616 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005617 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005618
5619 // Simplify 'fcmp pred X, X'
5620 if (Op0 == Op1) {
5621 switch (I.getPredicate()) {
5622 default: assert(0 && "Unknown predicate!");
5623 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5624 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5625 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005626 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005627 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5628 case FCmpInst::FCMP_OLT: // True if ordered and less than
5629 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005630 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005631
5632 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5633 case FCmpInst::FCMP_ULT: // True if unordered or less than
5634 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5635 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5636 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5637 I.setPredicate(FCmpInst::FCMP_UNO);
5638 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5639 return &I;
5640
5641 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5642 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5643 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5644 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5645 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5646 I.setPredicate(FCmpInst::FCMP_ORD);
5647 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5648 return &I;
5649 }
5650 }
5651
Reid Spencere4d87aa2006-12-23 06:05:41 +00005652 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005653 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005654
Reid Spencere4d87aa2006-12-23 06:05:41 +00005655 // Handle fcmp with constant RHS
5656 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005657 // If the constant is a nan, see if we can fold the comparison based on it.
5658 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5659 if (CFP->getValueAPF().isNaN()) {
5660 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005661 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005662 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5663 "Comparison must be either ordered or unordered!");
5664 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005665 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005666 }
5667 }
5668
Reid Spencere4d87aa2006-12-23 06:05:41 +00005669 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5670 switch (LHSI->getOpcode()) {
5671 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005672 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5673 // block. If in the same block, we're encouraging jump threading. If
5674 // not, we are just pessimizing the code by making an i1 phi.
5675 if (LHSI->getParent() == I.getParent())
5676 if (Instruction *NV = FoldOpIntoPhi(I))
5677 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005678 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005679 case Instruction::SIToFP:
5680 case Instruction::UIToFP:
5681 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5682 return NV;
5683 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005684 case Instruction::Select:
5685 // If either operand of the select is a constant, we can fold the
5686 // comparison into the select arms, which will cause one to be
5687 // constant folded and the select turned into a bitwise or.
5688 Value *Op1 = 0, *Op2 = 0;
5689 if (LHSI->hasOneUse()) {
5690 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5691 // Fold the known value into the constant operand.
5692 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5693 // Insert a new FCmp of the other select operand.
5694 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5695 LHSI->getOperand(2), RHSC,
5696 I.getName()), I);
5697 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5698 // Fold the known value into the constant operand.
5699 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5700 // Insert a new FCmp of the other select operand.
5701 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5702 LHSI->getOperand(1), RHSC,
5703 I.getName()), I);
5704 }
5705 }
5706
5707 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005708 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005709 break;
5710 }
5711 }
5712
5713 return Changed ? &I : 0;
5714}
5715
5716Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5717 bool Changed = SimplifyCompare(I);
5718 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5719 const Type *Ty = Op0->getType();
5720
5721 // icmp X, X
5722 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005723 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005724 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005725
5726 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005727 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005728
Reid Spencere4d87aa2006-12-23 06:05:41 +00005729 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005730 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005731 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5732 isa<ConstantPointerNull>(Op0)) &&
5733 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005734 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005735 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005736 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005737
Reid Spencere4d87aa2006-12-23 06:05:41 +00005738 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005739 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005740 switch (I.getPredicate()) {
5741 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005742 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005743 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005744 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005745 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005746 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005747 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005748 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005749
Reid Spencere4d87aa2006-12-23 06:05:41 +00005750 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005751 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005752 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005753 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005754 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005755 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005756 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005757 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005758 case ICmpInst::ICMP_SGT:
5759 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005760 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005761 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5762 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5763 InsertNewInstBefore(Not, I);
5764 return BinaryOperator::CreateAnd(Not, Op0);
5765 }
5766 case ICmpInst::ICMP_UGE:
5767 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5768 // FALL THROUGH
5769 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005770 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005771 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005772 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005773 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005774 case ICmpInst::ICMP_SGE:
5775 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5776 // FALL THROUGH
5777 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5778 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5779 InsertNewInstBefore(Not, I);
5780 return BinaryOperator::CreateOr(Not, Op0);
5781 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005782 }
Chris Lattner8b170942002-08-09 23:47:40 +00005783 }
5784
Dan Gohman81b28ce2008-09-16 18:46:06 +00005785 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005786 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerf2991842008-07-11 04:09:09 +00005787 Value *A, *B;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005788
Chris Lattnerb6566012008-01-05 01:18:20 +00005789 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5790 if (I.isEquality() && CI->isNullValue() &&
5791 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5792 // (icmp cond A B) if cond is equality
5793 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005794 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005795
Dan Gohman81b28ce2008-09-16 18:46:06 +00005796 // If we have an icmp le or icmp ge instruction, turn it into the
5797 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5798 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005799 switch (I.getPredicate()) {
5800 default: break;
5801 case ICmpInst::ICMP_ULE:
5802 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5803 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5804 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5805 case ICmpInst::ICMP_SLE:
5806 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5807 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5808 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5809 case ICmpInst::ICMP_UGE:
5810 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5811 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5812 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5813 case ICmpInst::ICMP_SGE:
5814 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5815 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5816 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5817 }
5818
Chris Lattner183661e2008-07-11 05:40:05 +00005819 // See if we can fold the comparison based on range information we can get
5820 // by checking whether bits are known to be zero or one in the input.
5821 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5822 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5823
5824 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005825 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005826 bool UnusedBit;
5827 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5828
Chris Lattner4241e4d2007-07-15 20:54:51 +00005829 if (SimplifyDemandedBits(Op0,
5830 isSignBit ? APInt::getSignBit(BitWidth)
5831 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005832 KnownZero, KnownOne, 0))
5833 return &I;
5834
5835 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005836 // in. Compute the Min, Max and RHS values based on the known bits. For the
5837 // EQ and NE we use unsigned values.
5838 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005839 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5840 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5841 else
5842 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5843
Chris Lattner183661e2008-07-11 05:40:05 +00005844 // If Min and Max are known to be the same, then SimplifyDemandedBits
5845 // figured out that the LHS is a constant. Just constant fold this now so
5846 // that code below can assume that Min != Max.
5847 if (Min == Max)
5848 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5849 ConstantInt::get(Min),
5850 CI));
5851
5852 // Based on the range information we know about the LHS, see if we can
5853 // simplify this comparison. For example, (x&4) < 8 is always true.
5854 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005855 switch (I.getPredicate()) { // LE/GE have been folded already.
5856 default: assert(0 && "Unknown icmp opcode!");
5857 case ICmpInst::ICMP_EQ:
5858 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5859 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5860 break;
5861 case ICmpInst::ICMP_NE:
5862 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5863 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5864 break;
5865 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005866 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005867 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005868 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005869 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005870 if (RHSVal == Max) // A <u MAX -> A != MAX
5871 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5872 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5873 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5874
5875 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5876 if (CI->isMinValue(true))
5877 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5878 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005879 break;
5880 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005881 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005882 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005883 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005884 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005885
5886 if (RHSVal == Min) // A >u MIN -> A != MIN
5887 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5888 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5889 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5890
5891 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5892 if (CI->isMaxValue(true))
5893 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5894 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005895 break;
5896 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005897 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005898 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005899 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005900 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005901 if (RHSVal == Max) // A <s MAX -> A != MAX
5902 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005903 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005904 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005905 break;
5906 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005907 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005908 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005909 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005910 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005911
5912 if (RHSVal == Min) // A >s MIN -> A != MIN
5913 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5914 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5915 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005916 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005917 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005918 }
5919
5920 // Test if the ICmpInst instruction is used exclusively by a select as
5921 // part of a minimum or maximum operation. If so, refrain from doing
5922 // any other folding. This helps out other analyses which understand
5923 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5924 // and CodeGen. And in this case, at least one of the comparison
5925 // operands has at least one user besides the compare (the select),
5926 // which would often largely negate the benefit of folding anyway.
5927 if (I.hasOneUse())
5928 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5929 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5930 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5931 return 0;
5932
5933 // See if we are doing a comparison between a constant and an instruction that
5934 // can be folded into the comparison.
5935 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005936 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005937 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005938 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005939 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005940 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5941 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005942 }
5943
Chris Lattner01deb9d2007-04-03 17:43:25 +00005944 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005945 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5946 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5947 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005948 case Instruction::GetElementPtr:
5949 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005950 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005951 bool isAllZeros = true;
5952 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5953 if (!isa<Constant>(LHSI->getOperand(i)) ||
5954 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5955 isAllZeros = false;
5956 break;
5957 }
5958 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005959 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005960 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5961 }
5962 break;
5963
Chris Lattner6970b662005-04-23 15:31:55 +00005964 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005965 // Only fold icmp into the PHI if the phi and fcmp are in the same
5966 // block. If in the same block, we're encouraging jump threading. If
5967 // not, we are just pessimizing the code by making an i1 phi.
5968 if (LHSI->getParent() == I.getParent())
5969 if (Instruction *NV = FoldOpIntoPhi(I))
5970 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00005971 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005972 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005973 // If either operand of the select is a constant, we can fold the
5974 // comparison into the select arms, which will cause one to be
5975 // constant folded and the select turned into a bitwise or.
5976 Value *Op1 = 0, *Op2 = 0;
5977 if (LHSI->hasOneUse()) {
5978 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5979 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005980 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5981 // Insert a new ICmp of the other select operand.
5982 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5983 LHSI->getOperand(2), RHSC,
5984 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005985 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5986 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005987 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5988 // Insert a new ICmp of the other select operand.
5989 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5990 LHSI->getOperand(1), RHSC,
5991 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005992 }
5993 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005994
Chris Lattner6970b662005-04-23 15:31:55 +00005995 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005996 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005997 break;
5998 }
Chris Lattner4802d902007-04-06 18:57:34 +00005999 case Instruction::Malloc:
6000 // If we have (malloc != null), and if the malloc has a single use, we
6001 // can assume it is successful and remove the malloc.
6002 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6003 AddToWorkList(LHSI);
6004 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006005 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006006 }
6007 break;
6008 }
Chris Lattner6970b662005-04-23 15:31:55 +00006009 }
6010
Reid Spencere4d87aa2006-12-23 06:05:41 +00006011 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006012 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006013 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006014 return NI;
6015 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006016 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6017 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006018 return NI;
6019
Reid Spencere4d87aa2006-12-23 06:05:41 +00006020 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006021 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6022 // now.
6023 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6024 if (isa<PointerType>(Op0->getType()) &&
6025 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006026 // We keep moving the cast from the left operand over to the right
6027 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006028 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006029
Chris Lattner57d86372007-01-06 01:45:59 +00006030 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6031 // so eliminate it as well.
6032 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6033 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006034
Chris Lattnerde90b762003-11-03 04:25:02 +00006035 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006036 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006037 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006038 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006039 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006040 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006041 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006042 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006043 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006044 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006045 }
Chris Lattner57d86372007-01-06 01:45:59 +00006046 }
6047
6048 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006049 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006050 // This comes up when you have code like
6051 // int X = A < B;
6052 // if (X) ...
6053 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006054 // with a constant or another cast from the same type.
6055 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006056 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006057 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006058 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006059
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006060 // See if it's the same type of instruction on the left and right.
6061 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6062 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006063 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6064 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6065 I.isEquality()) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006066 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006067 default: break;
6068 case Instruction::Add:
6069 case Instruction::Sub:
6070 case Instruction::Xor:
Nick Lewycky5d52c452008-08-21 05:56:10 +00006071 // a+x icmp eq/ne b+x --> a icmp b
6072 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6073 Op1I->getOperand(0));
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006074 break;
6075 case Instruction::Mul:
Nick Lewycky5d52c452008-08-21 05:56:10 +00006076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6077 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6078 // Mask = -1 >> count-trailing-zeros(Cst).
6079 if (!CI->isZero() && !CI->isOne()) {
6080 const APInt &AP = CI->getValue();
6081 ConstantInt *Mask = ConstantInt::get(
6082 APInt::getLowBitsSet(AP.getBitWidth(),
6083 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006084 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006085 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6086 Mask);
6087 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6088 Mask);
6089 InsertNewInstBefore(And1, I);
6090 InsertNewInstBefore(And2, I);
6091 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006092 }
6093 }
6094 break;
6095 }
6096 }
6097 }
6098 }
6099
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006100 // ~x < ~y --> y < x
6101 { Value *A, *B;
6102 if (match(Op0, m_Not(m_Value(A))) &&
6103 match(Op1, m_Not(m_Value(B))))
6104 return new ICmpInst(I.getPredicate(), B, A);
6105 }
6106
Chris Lattner65b72ba2006-09-18 04:22:48 +00006107 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006108 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006109
6110 // -x == -y --> x == y
6111 if (match(Op0, m_Neg(m_Value(A))) &&
6112 match(Op1, m_Neg(m_Value(B))))
6113 return new ICmpInst(I.getPredicate(), A, B);
6114
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006115 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6116 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6117 Value *OtherVal = A == Op1 ? B : A;
6118 return new ICmpInst(I.getPredicate(), OtherVal,
6119 Constant::getNullValue(A->getType()));
6120 }
6121
6122 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6123 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006124 ConstantInt *C1, *C2;
6125 if (match(B, m_ConstantInt(C1)) &&
6126 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6127 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6128 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6129 return new ICmpInst(I.getPredicate(), A,
6130 InsertNewInstBefore(Xor, I));
6131 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006132
6133 // A^B == A^D -> B == D
6134 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6135 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6136 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6137 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6138 }
6139 }
6140
6141 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6142 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006143 // A == (A^B) -> B == 0
6144 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006145 return new ICmpInst(I.getPredicate(), OtherVal,
6146 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006147 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006148
6149 // (A-B) == A -> B == 0
6150 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6151 return new ICmpInst(I.getPredicate(), B,
6152 Constant::getNullValue(B->getType()));
6153
6154 // A == (A-B) -> B == 0
6155 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006156 return new ICmpInst(I.getPredicate(), B,
6157 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006158
Chris Lattner9c2328e2006-11-14 06:06:06 +00006159 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6160 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6161 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6162 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6163 Value *X = 0, *Y = 0, *Z = 0;
6164
6165 if (A == C) {
6166 X = B; Y = D; Z = A;
6167 } else if (A == D) {
6168 X = B; Y = C; Z = A;
6169 } else if (B == C) {
6170 X = A; Y = D; Z = B;
6171 } else if (B == D) {
6172 X = A; Y = C; Z = B;
6173 }
6174
6175 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006176 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6177 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006178 I.setOperand(0, Op1);
6179 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6180 return &I;
6181 }
6182 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006183 }
Chris Lattner7e708292002-06-25 16:13:24 +00006184 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006185}
6186
Chris Lattner562ef782007-06-20 23:46:26 +00006187
6188/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6189/// and CmpRHS are both known to be integer constants.
6190Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6191 ConstantInt *DivRHS) {
6192 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6193 const APInt &CmpRHSV = CmpRHS->getValue();
6194
6195 // FIXME: If the operand types don't match the type of the divide
6196 // then don't attempt this transform. The code below doesn't have the
6197 // logic to deal with a signed divide and an unsigned compare (and
6198 // vice versa). This is because (x /s C1) <s C2 produces different
6199 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6200 // (x /u C1) <u C2. Simply casting the operands and result won't
6201 // work. :( The if statement below tests that condition and bails
6202 // if it finds it.
6203 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6204 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6205 return 0;
6206 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006207 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006208 if (DivIsSigned && DivRHS->isAllOnesValue())
6209 return 0; // The overflow computation also screws up here
6210 if (DivRHS->isOne())
6211 return 0; // Not worth bothering, and eliminates some funny cases
6212 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006213
6214 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6215 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6216 // C2 (CI). By solving for X we can turn this into a range check
6217 // instead of computing a divide.
6218 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6219
6220 // Determine if the product overflows by seeing if the product is
6221 // not equal to the divide. Make sure we do the same kind of divide
6222 // as in the LHS instruction that we're folding.
6223 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6224 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6225
6226 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006227 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006228
Chris Lattner1dbfd482007-06-21 18:11:19 +00006229 // Figure out the interval that is being checked. For example, a comparison
6230 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6231 // Compute this interval based on the constants involved and the signedness of
6232 // the compare/divide. This computes a half-open interval, keeping track of
6233 // whether either value in the interval overflows. After analysis each
6234 // overflow variable is set to 0 if it's corresponding bound variable is valid
6235 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6236 int LoOverflow = 0, HiOverflow = 0;
6237 ConstantInt *LoBound = 0, *HiBound = 0;
6238
Chris Lattner562ef782007-06-20 23:46:26 +00006239 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006240 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006241 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006242 HiOverflow = LoOverflow = ProdOV;
6243 if (!HiOverflow)
6244 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006245 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006246 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006247 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006248 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6249 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006250 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006251 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6252 HiOverflow = LoOverflow = ProdOV;
6253 if (!HiOverflow)
6254 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006255 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006256 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006257 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006258 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6259 if (!LoOverflow) {
6260 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6261 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6262 true) ? -1 : 0;
6263 }
Chris Lattner562ef782007-06-20 23:46:26 +00006264 }
Dan Gohman76491272008-02-13 22:09:18 +00006265 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006266 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006267 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006268 LoBound = AddOne(DivRHS);
6269 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006270 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6271 HiOverflow = 1; // [INTMIN+1, overflow)
6272 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6273 }
Dan Gohman76491272008-02-13 22:09:18 +00006274 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006275 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006276 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006277 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006278 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006279 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006280 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006281 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6282 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006283 if (!HiOverflow)
6284 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006285 }
6286
Chris Lattner1dbfd482007-06-21 18:11:19 +00006287 // Dividing by a negative swaps the condition. LT <-> GT
6288 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006289 }
6290
6291 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006292 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006293 default: assert(0 && "Unhandled icmp opcode!");
6294 case ICmpInst::ICMP_EQ:
6295 if (LoOverflow && HiOverflow)
6296 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6297 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006298 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006299 ICmpInst::ICMP_UGE, X, LoBound);
6300 else if (LoOverflow)
6301 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6302 ICmpInst::ICMP_ULT, X, HiBound);
6303 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006304 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006305 case ICmpInst::ICMP_NE:
6306 if (LoOverflow && HiOverflow)
6307 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6308 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006309 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006310 ICmpInst::ICMP_ULT, X, LoBound);
6311 else if (LoOverflow)
6312 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6313 ICmpInst::ICMP_UGE, X, HiBound);
6314 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006315 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006316 case ICmpInst::ICMP_ULT:
6317 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006318 if (LoOverflow == +1) // Low bound is greater than input range.
6319 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6320 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006322 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006323 case ICmpInst::ICMP_UGT:
6324 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006325 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006326 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006327 else if (HiOverflow == -1) // High bound less than input range.
6328 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6329 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006330 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6331 else
6332 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6333 }
6334}
6335
6336
Chris Lattner01deb9d2007-04-03 17:43:25 +00006337/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6338///
6339Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6340 Instruction *LHSI,
6341 ConstantInt *RHS) {
6342 const APInt &RHSV = RHS->getValue();
6343
6344 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006345 case Instruction::Trunc:
6346 if (ICI.isEquality() && LHSI->hasOneUse()) {
6347 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6348 // of the high bits truncated out of x are known.
6349 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6350 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6351 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6352 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6353 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6354
6355 // If all the high bits are known, we can do this xform.
6356 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6357 // Pull in the high bits from known-ones set.
6358 APInt NewRHS(RHS->getValue());
6359 NewRHS.zext(SrcBits);
6360 NewRHS |= KnownOne;
6361 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6362 ConstantInt::get(NewRHS));
6363 }
6364 }
6365 break;
6366
Duncan Sands0091bf22007-04-04 06:42:45 +00006367 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006368 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6369 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6370 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006371 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6372 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006373 Value *CompareVal = LHSI->getOperand(0);
6374
6375 // If the sign bit of the XorCST is not set, there is no change to
6376 // the operation, just stop using the Xor.
6377 if (!XorCST->getValue().isNegative()) {
6378 ICI.setOperand(0, CompareVal);
6379 AddToWorkList(LHSI);
6380 return &ICI;
6381 }
6382
6383 // Was the old condition true if the operand is positive?
6384 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6385
6386 // If so, the new one isn't.
6387 isTrueIfPositive ^= true;
6388
6389 if (isTrueIfPositive)
6390 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6391 else
6392 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6393 }
6394 }
6395 break;
6396 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6397 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6398 LHSI->getOperand(0)->hasOneUse()) {
6399 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6400
6401 // If the LHS is an AND of a truncating cast, we can widen the
6402 // and/compare to be the input width without changing the value
6403 // produced, eliminating a cast.
6404 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6405 // We can do this transformation if either the AND constant does not
6406 // have its sign bit set or if it is an equality comparison.
6407 // Extending a relational comparison when we're checking the sign
6408 // bit would not work.
6409 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006410 (ICI.isEquality() ||
6411 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006412 uint32_t BitWidth =
6413 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6414 APInt NewCST = AndCST->getValue();
6415 NewCST.zext(BitWidth);
6416 APInt NewCI = RHSV;
6417 NewCI.zext(BitWidth);
6418 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006419 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006420 ConstantInt::get(NewCST),LHSI->getName());
6421 InsertNewInstBefore(NewAnd, ICI);
6422 return new ICmpInst(ICI.getPredicate(), NewAnd,
6423 ConstantInt::get(NewCI));
6424 }
6425 }
6426
6427 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6428 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6429 // happens a LOT in code produced by the C front-end, for bitfield
6430 // access.
6431 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6432 if (Shift && !Shift->isShift())
6433 Shift = 0;
6434
6435 ConstantInt *ShAmt;
6436 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6437 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6438 const Type *AndTy = AndCST->getType(); // Type of the and.
6439
6440 // We can fold this as long as we can't shift unknown bits
6441 // into the mask. This can only happen with signed shift
6442 // rights, as they sign-extend.
6443 if (ShAmt) {
6444 bool CanFold = Shift->isLogicalShift();
6445 if (!CanFold) {
6446 // To test for the bad case of the signed shr, see if any
6447 // of the bits shifted in could be tested after the mask.
6448 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6449 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6450
6451 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6452 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6453 AndCST->getValue()) == 0)
6454 CanFold = true;
6455 }
6456
6457 if (CanFold) {
6458 Constant *NewCst;
6459 if (Shift->getOpcode() == Instruction::Shl)
6460 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6461 else
6462 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6463
6464 // Check to see if we are shifting out any of the bits being
6465 // compared.
6466 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6467 // If we shifted bits out, the fold is not going to work out.
6468 // As a special case, check to see if this means that the
6469 // result is always true or false now.
6470 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6471 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6472 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6473 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6474 } else {
6475 ICI.setOperand(1, NewCst);
6476 Constant *NewAndCST;
6477 if (Shift->getOpcode() == Instruction::Shl)
6478 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6479 else
6480 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6481 LHSI->setOperand(1, NewAndCST);
6482 LHSI->setOperand(0, Shift->getOperand(0));
6483 AddToWorkList(Shift); // Shift is dead.
6484 AddUsesToWorkList(ICI);
6485 return &ICI;
6486 }
6487 }
6488 }
6489
6490 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6491 // preferable because it allows the C<<Y expression to be hoisted out
6492 // of a loop if Y is invariant and X is not.
6493 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6494 ICI.isEquality() && !Shift->isArithmeticShift() &&
6495 isa<Instruction>(Shift->getOperand(0))) {
6496 // Compute C << Y.
6497 Value *NS;
6498 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006499 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006500 Shift->getOperand(1), "tmp");
6501 } else {
6502 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006503 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006504 Shift->getOperand(1), "tmp");
6505 }
6506 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6507
6508 // Compute X & (C << Y).
6509 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006510 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006511 InsertNewInstBefore(NewAnd, ICI);
6512
6513 ICI.setOperand(0, NewAnd);
6514 return &ICI;
6515 }
6516 }
6517 break;
6518
Chris Lattnera0141b92007-07-15 20:42:37 +00006519 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6520 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6521 if (!ShAmt) break;
6522
6523 uint32_t TypeBits = RHSV.getBitWidth();
6524
6525 // Check that the shift amount is in range. If not, don't perform
6526 // undefined shifts. When the shift is visited it will be
6527 // simplified.
6528 if (ShAmt->uge(TypeBits))
6529 break;
6530
6531 if (ICI.isEquality()) {
6532 // If we are comparing against bits always shifted out, the
6533 // comparison cannot succeed.
6534 Constant *Comp =
6535 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6536 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6537 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6538 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6539 return ReplaceInstUsesWith(ICI, Cst);
6540 }
6541
6542 if (LHSI->hasOneUse()) {
6543 // Otherwise strength reduce the shift into an and.
6544 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6545 Constant *Mask =
6546 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006547
Chris Lattnera0141b92007-07-15 20:42:37 +00006548 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006549 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006550 Mask, LHSI->getName()+".mask");
6551 Value *And = InsertNewInstBefore(AndI, ICI);
6552 return new ICmpInst(ICI.getPredicate(), And,
6553 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006554 }
6555 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006556
6557 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6558 bool TrueIfSigned = false;
6559 if (LHSI->hasOneUse() &&
6560 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6561 // (X << 31) <s 0 --> (X&1) != 0
6562 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6563 (TypeBits-ShAmt->getZExtValue()-1));
6564 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006565 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006566 Mask, LHSI->getName()+".mask");
6567 Value *And = InsertNewInstBefore(AndI, ICI);
6568
6569 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6570 And, Constant::getNullValue(And->getType()));
6571 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006572 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006573 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006574
6575 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006576 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006577 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006578 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006579 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006580
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006581 // Check that the shift amount is in range. If not, don't perform
6582 // undefined shifts. When the shift is visited it will be
6583 // simplified.
6584 uint32_t TypeBits = RHSV.getBitWidth();
6585 if (ShAmt->uge(TypeBits))
6586 break;
6587
6588 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006589
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006590 // If we are comparing against bits always shifted out, the
6591 // comparison cannot succeed.
6592 APInt Comp = RHSV << ShAmtVal;
6593 if (LHSI->getOpcode() == Instruction::LShr)
6594 Comp = Comp.lshr(ShAmtVal);
6595 else
6596 Comp = Comp.ashr(ShAmtVal);
6597
6598 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6599 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6600 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6601 return ReplaceInstUsesWith(ICI, Cst);
6602 }
6603
6604 // Otherwise, check to see if the bits shifted out are known to be zero.
6605 // If so, we can compare against the unshifted value:
6606 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006607 if (LHSI->hasOneUse() &&
6608 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006609 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6610 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6611 ConstantExpr::getShl(RHS, ShAmt));
6612 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006613
Evan Chengf30752c2008-04-23 00:38:06 +00006614 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006615 // Otherwise strength reduce the shift into an and.
6616 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6617 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006618
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006619 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006620 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006621 Mask, LHSI->getName()+".mask");
6622 Value *And = InsertNewInstBefore(AndI, ICI);
6623 return new ICmpInst(ICI.getPredicate(), And,
6624 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006625 }
6626 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006627 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006628
6629 case Instruction::SDiv:
6630 case Instruction::UDiv:
6631 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6632 // Fold this div into the comparison, producing a range check.
6633 // Determine, based on the divide type, what the range is being
6634 // checked. If there is an overflow on the low or high side, remember
6635 // it, otherwise compute the range [low, hi) bounding the new value.
6636 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006637 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6638 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6639 DivRHS))
6640 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006641 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006642
6643 case Instruction::Add:
6644 // Fold: icmp pred (add, X, C1), C2
6645
6646 if (!ICI.isEquality()) {
6647 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6648 if (!LHSC) break;
6649 const APInt &LHSV = LHSC->getValue();
6650
6651 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6652 .subtract(LHSV);
6653
6654 if (ICI.isSignedPredicate()) {
6655 if (CR.getLower().isSignBit()) {
6656 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6657 ConstantInt::get(CR.getUpper()));
6658 } else if (CR.getUpper().isSignBit()) {
6659 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6660 ConstantInt::get(CR.getLower()));
6661 }
6662 } else {
6663 if (CR.getLower().isMinValue()) {
6664 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6665 ConstantInt::get(CR.getUpper()));
6666 } else if (CR.getUpper().isMinValue()) {
6667 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6668 ConstantInt::get(CR.getLower()));
6669 }
6670 }
6671 }
6672 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006673 }
6674
6675 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6676 if (ICI.isEquality()) {
6677 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6678
6679 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6680 // the second operand is a constant, simplify a bit.
6681 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6682 switch (BO->getOpcode()) {
6683 case Instruction::SRem:
6684 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6685 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6686 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6687 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6688 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006689 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006690 BO->getName());
6691 InsertNewInstBefore(NewRem, ICI);
6692 return new ICmpInst(ICI.getPredicate(), NewRem,
6693 Constant::getNullValue(BO->getType()));
6694 }
6695 }
6696 break;
6697 case Instruction::Add:
6698 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6699 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6700 if (BO->hasOneUse())
6701 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6702 Subtract(RHS, BOp1C));
6703 } else if (RHSV == 0) {
6704 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6705 // efficiently invertible, or if the add has just this one use.
6706 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6707
6708 if (Value *NegVal = dyn_castNegVal(BOp1))
6709 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6710 else if (Value *NegVal = dyn_castNegVal(BOp0))
6711 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6712 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006713 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006714 InsertNewInstBefore(Neg, ICI);
6715 Neg->takeName(BO);
6716 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6717 }
6718 }
6719 break;
6720 case Instruction::Xor:
6721 // For the xor case, we can xor two constants together, eliminating
6722 // the explicit xor.
6723 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6724 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6725 ConstantExpr::getXor(RHS, BOC));
6726
6727 // FALLTHROUGH
6728 case Instruction::Sub:
6729 // Replace (([sub|xor] A, B) != 0) with (A != B)
6730 if (RHSV == 0)
6731 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6732 BO->getOperand(1));
6733 break;
6734
6735 case Instruction::Or:
6736 // If bits are being or'd in that are not present in the constant we
6737 // are comparing against, then the comparison could never succeed!
6738 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6739 Constant *NotCI = ConstantExpr::getNot(RHS);
6740 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6741 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6742 isICMP_NE));
6743 }
6744 break;
6745
6746 case Instruction::And:
6747 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6748 // If bits are being compared against that are and'd out, then the
6749 // comparison can never succeed!
6750 if ((RHSV & ~BOC->getValue()) != 0)
6751 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6752 isICMP_NE));
6753
6754 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6755 if (RHS == BOC && RHSV.isPowerOf2())
6756 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6757 ICmpInst::ICMP_NE, LHSI,
6758 Constant::getNullValue(RHS->getType()));
6759
6760 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006761 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006762 Value *X = BO->getOperand(0);
6763 Constant *Zero = Constant::getNullValue(X->getType());
6764 ICmpInst::Predicate pred = isICMP_NE ?
6765 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6766 return new ICmpInst(pred, X, Zero);
6767 }
6768
6769 // ((X & ~7) == 0) --> X < 8
6770 if (RHSV == 0 && isHighOnes(BOC)) {
6771 Value *X = BO->getOperand(0);
6772 Constant *NegX = ConstantExpr::getNeg(BOC);
6773 ICmpInst::Predicate pred = isICMP_NE ?
6774 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6775 return new ICmpInst(pred, X, NegX);
6776 }
6777 }
6778 default: break;
6779 }
6780 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6781 // Handle icmp {eq|ne} <intrinsic>, intcst.
6782 if (II->getIntrinsicID() == Intrinsic::bswap) {
6783 AddToWorkList(II);
6784 ICI.setOperand(0, II->getOperand(1));
6785 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6786 return &ICI;
6787 }
6788 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006789 }
6790 return 0;
6791}
6792
6793/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6794/// We only handle extending casts so far.
6795///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006796Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6797 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006798 Value *LHSCIOp = LHSCI->getOperand(0);
6799 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006800 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006801 Value *RHSCIOp;
6802
Chris Lattner8c756c12007-05-05 22:41:33 +00006803 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6804 // integer type is the same size as the pointer type.
6805 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6806 getTargetData().getPointerSizeInBits() ==
6807 cast<IntegerType>(DestTy)->getBitWidth()) {
6808 Value *RHSOp = 0;
6809 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006810 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006811 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6812 RHSOp = RHSC->getOperand(0);
6813 // If the pointer types don't match, insert a bitcast.
6814 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006815 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006816 }
6817
6818 if (RHSOp)
6819 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6820 }
6821
6822 // The code below only handles extension cast instructions, so far.
6823 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006824 if (LHSCI->getOpcode() != Instruction::ZExt &&
6825 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006826 return 0;
6827
Reid Spencere4d87aa2006-12-23 06:05:41 +00006828 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6829 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006830
Reid Spencere4d87aa2006-12-23 06:05:41 +00006831 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006832 // Not an extension from the same type?
6833 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006834 if (RHSCIOp->getType() != LHSCIOp->getType())
6835 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006836
Nick Lewycky4189a532008-01-28 03:48:02 +00006837 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006838 // and the other is a zext), then we can't handle this.
6839 if (CI->getOpcode() != LHSCI->getOpcode())
6840 return 0;
6841
Nick Lewycky4189a532008-01-28 03:48:02 +00006842 // Deal with equality cases early.
6843 if (ICI.isEquality())
6844 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6845
6846 // A signed comparison of sign extended values simplifies into a
6847 // signed comparison.
6848 if (isSignedCmp && isSignedExt)
6849 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6850
6851 // The other three cases all fold into an unsigned comparison.
6852 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006853 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006854
Reid Spencere4d87aa2006-12-23 06:05:41 +00006855 // If we aren't dealing with a constant on the RHS, exit early
6856 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6857 if (!CI)
6858 return 0;
6859
6860 // Compute the constant that would happen if we truncated to SrcTy then
6861 // reextended to DestTy.
6862 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6863 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6864
6865 // If the re-extended constant didn't change...
6866 if (Res2 == CI) {
6867 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6868 // For example, we might have:
6869 // %A = sext short %X to uint
6870 // %B = icmp ugt uint %A, 1330
6871 // It is incorrect to transform this into
6872 // %B = icmp ugt short %X, 1330
6873 // because %A may have negative value.
6874 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006875 // However, we allow this when the compare is EQ/NE, because they are
6876 // signless.
6877 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006878 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006879 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006880 }
6881
6882 // The re-extended constant changed so the constant cannot be represented
6883 // in the shorter type. Consequently, we cannot emit a simple comparison.
6884
6885 // First, handle some easy cases. We know the result cannot be equal at this
6886 // point so handle the ICI.isEquality() cases
6887 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006888 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006889 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006890 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006891
6892 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6893 // should have been folded away previously and not enter in here.
6894 Value *Result;
6895 if (isSignedCmp) {
6896 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006897 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006898 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006899 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006900 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006901 } else {
6902 // We're performing an unsigned comparison.
6903 if (isSignedExt) {
6904 // We're performing an unsigned comp with a sign extended value.
6905 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006906 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006907 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6908 NegOne, ICI.getName()), ICI);
6909 } else {
6910 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006911 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006912 }
6913 }
6914
6915 // Finally, return the value computed.
6916 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006917 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006918 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00006919
6920 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6921 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6922 "ICmp should be folded!");
6923 if (Constant *CI = dyn_cast<Constant>(Result))
6924 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6925 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00006926}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006927
Reid Spencer832254e2007-02-02 02:16:23 +00006928Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6929 return commonShiftTransforms(I);
6930}
6931
6932Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6933 return commonShiftTransforms(I);
6934}
6935
6936Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006937 if (Instruction *R = commonShiftTransforms(I))
6938 return R;
6939
6940 Value *Op0 = I.getOperand(0);
6941
6942 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6943 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6944 if (CSI->isAllOnesValue())
6945 return ReplaceInstUsesWith(I, CSI);
6946
6947 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00006948 if (!isa<VectorType>(I.getType()) &&
6949 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00006950 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006951 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006952
6953 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006954}
6955
6956Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6957 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006959
6960 // shl X, 0 == X and shr X, 0 == X
6961 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006962 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006963 Op0 == Constant::getNullValue(Op0->getType()))
6964 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006965
Reid Spencere4d87aa2006-12-23 06:05:41 +00006966 if (isa<UndefValue>(Op0)) {
6967 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006968 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006969 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6971 }
6972 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006973 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6974 return ReplaceInstUsesWith(I, Op0);
6975 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006977 }
6978
Chris Lattner2eefe512004-04-09 19:05:30 +00006979 // Try to fold constant and into select arguments.
6980 if (isa<Constant>(Op0))
6981 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006982 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006983 return R;
6984
Reid Spencerb83eb642006-10-20 07:07:24 +00006985 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006986 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6987 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006988 return 0;
6989}
6990
Reid Spencerb83eb642006-10-20 07:07:24 +00006991Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006992 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006993 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006994
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006995 // See if we can simplify any instructions used by the instruction whose sole
6996 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006997 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6998 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6999 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007000 KnownZero, KnownOne))
7001 return &I;
7002
Chris Lattner4d5542c2006-01-06 07:12:35 +00007003 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7004 // of a signed value.
7005 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007006 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007007 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007008 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7009 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007010 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007011 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007012 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007013 }
7014
7015 // ((X*C1) << C2) == (X * (C1 << C2))
7016 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7017 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7018 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007019 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007020 ConstantExpr::getShl(BOOp, Op1));
7021
7022 // Try to fold constant and into select arguments.
7023 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7024 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7025 return R;
7026 if (isa<PHINode>(Op0))
7027 if (Instruction *NV = FoldOpIntoPhi(I))
7028 return NV;
7029
Chris Lattner8999dd32007-12-22 09:07:47 +00007030 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7031 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7032 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7033 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7034 // place. Don't try to do this transformation in this case. Also, we
7035 // require that the input operand is a shift-by-constant so that we have
7036 // confidence that the shifts will get folded together. We could do this
7037 // xform in more cases, but it is unlikely to be profitable.
7038 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7039 isa<ConstantInt>(TrOp->getOperand(1))) {
7040 // Okay, we'll do this xform. Make the shift of shift.
7041 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007042 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007043 I.getName());
7044 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7045
7046 // For logical shifts, the truncation has the effect of making the high
7047 // part of the register be zeros. Emulate this by inserting an AND to
7048 // clear the top bits as needed. This 'and' will usually be zapped by
7049 // other xforms later if dead.
7050 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7051 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7052 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7053
7054 // The mask we constructed says what the trunc would do if occurring
7055 // between the shifts. We want to know the effect *after* the second
7056 // shift. We know that it is a logical shift by a constant, so adjust the
7057 // mask as appropriate.
7058 if (I.getOpcode() == Instruction::Shl)
7059 MaskV <<= Op1->getZExtValue();
7060 else {
7061 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7062 MaskV = MaskV.lshr(Op1->getZExtValue());
7063 }
7064
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007065 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007066 TI->getName());
7067 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7068
7069 // Return the value truncated to the interesting size.
7070 return new TruncInst(And, I.getType());
7071 }
7072 }
7073
Chris Lattner4d5542c2006-01-06 07:12:35 +00007074 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007075 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7076 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7077 Value *V1, *V2;
7078 ConstantInt *CC;
7079 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007080 default: break;
7081 case Instruction::Add:
7082 case Instruction::And:
7083 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007084 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007085 // These operators commute.
7086 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007087 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007088 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007089 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007090 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007091 Op0BO->getName());
7092 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007093 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007094 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007095 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007096 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007097 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007098 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007099 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007100 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007101
Chris Lattner150f12a2005-09-18 06:30:59 +00007102 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007103 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007104 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007105 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007106 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7107 m_ConstantInt(CC))) &&
7108 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007109 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007110 Op0BO->getOperand(0), Op1,
7111 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007112 InsertNewInstBefore(YS, I); // (Y << C)
7113 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007114 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007115 V1->getName()+".mask");
7116 InsertNewInstBefore(XM, I); // X & (CC << C)
7117
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007118 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007119 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007120 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007121
Reid Spencera07cb7d2007-02-02 14:41:37 +00007122 // FALL THROUGH.
7123 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007124 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007125 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007126 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007127 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007128 Op0BO->getOperand(1), Op1,
7129 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007130 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007131 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007132 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007133 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007134 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007135 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007136 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007137 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007138 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007139
Chris Lattner13d4ab42006-05-31 21:14:00 +00007140 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007141 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7142 match(Op0BO->getOperand(0),
7143 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007144 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007145 cast<BinaryOperator>(Op0BO->getOperand(0))
7146 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007147 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007148 Op0BO->getOperand(1), Op1,
7149 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007150 InsertNewInstBefore(YS, I); // (Y << C)
7151 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007152 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007153 V1->getName()+".mask");
7154 InsertNewInstBefore(XM, I); // X & (CC << C)
7155
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007156 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007157 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007158
Chris Lattner11021cb2005-09-18 05:12:10 +00007159 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007160 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007161 }
7162
7163
7164 // If the operand is an bitwise operator with a constant RHS, and the
7165 // shift is the only use, we can pull it out of the shift.
7166 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7167 bool isValid = true; // Valid only for And, Or, Xor
7168 bool highBitSet = false; // Transform if high bit of constant set?
7169
7170 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007171 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007172 case Instruction::Add:
7173 isValid = isLeftShift;
7174 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007175 case Instruction::Or:
7176 case Instruction::Xor:
7177 highBitSet = false;
7178 break;
7179 case Instruction::And:
7180 highBitSet = true;
7181 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007182 }
7183
7184 // If this is a signed shift right, and the high bit is modified
7185 // by the logical operation, do not perform the transformation.
7186 // The highBitSet boolean indicates the value of the high bit of
7187 // the constant which would cause it to be modified for this
7188 // operation.
7189 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007190 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007191 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007192
7193 if (isValid) {
7194 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7195
7196 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007197 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007198 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007199 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007200
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007201 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007202 NewRHS);
7203 }
7204 }
7205 }
7206 }
7207
Chris Lattnerad0124c2006-01-06 07:52:12 +00007208 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007209 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7210 if (ShiftOp && !ShiftOp->isShift())
7211 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007212
Reid Spencerb83eb642006-10-20 07:07:24 +00007213 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007214 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007215 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7216 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007217 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7218 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7219 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007220
Zhou Sheng4351c642007-04-02 08:20:41 +00007221 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007222 if (AmtSum > TypeBits)
7223 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007224
7225 const IntegerType *Ty = cast<IntegerType>(I.getType());
7226
7227 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007228 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007229 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007230 ConstantInt::get(Ty, AmtSum));
7231 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7232 I.getOpcode() == Instruction::AShr) {
7233 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007234 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007235 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7236 I.getOpcode() == Instruction::LShr) {
7237 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7238 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007239 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007240 InsertNewInstBefore(Shift, I);
7241
Zhou Shenge9e03f62007-03-28 15:02:20 +00007242 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007243 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007244 }
7245
Chris Lattnerb87056f2007-02-05 00:57:54 +00007246 // Okay, if we get here, one shift must be left, and the other shift must be
7247 // right. See if the amounts are equal.
7248 if (ShiftAmt1 == ShiftAmt2) {
7249 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7250 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007251 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007252 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007253 }
7254 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7255 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007256 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007257 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007258 }
7259 // We can simplify ((X << C) >>s C) into a trunc + sext.
7260 // NOTE: we could do this for any C, but that would make 'unusual' integer
7261 // types. For now, just stick to ones well-supported by the code
7262 // generators.
7263 const Type *SExtType = 0;
7264 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007265 case 1 :
7266 case 8 :
7267 case 16 :
7268 case 32 :
7269 case 64 :
7270 case 128:
7271 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7272 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007273 default: break;
7274 }
7275 if (SExtType) {
7276 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7277 InsertNewInstBefore(NewTrunc, I);
7278 return new SExtInst(NewTrunc, Ty);
7279 }
7280 // Otherwise, we can't handle it yet.
7281 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007282 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007283
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007284 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007285 if (I.getOpcode() == Instruction::Shl) {
7286 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7287 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007288 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007289 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007290 InsertNewInstBefore(Shift, I);
7291
Reid Spencer55702aa2007-03-25 21:11:44 +00007292 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007293 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007294 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007295
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007296 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007297 if (I.getOpcode() == Instruction::LShr) {
7298 assert(ShiftOp->getOpcode() == Instruction::Shl);
7299 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007300 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007301 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007302
Reid Spencerd5e30f02007-03-26 17:18:58 +00007303 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007304 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007305 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007306
7307 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7308 } else {
7309 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007310 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007311
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007312 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007313 if (I.getOpcode() == Instruction::Shl) {
7314 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7315 ShiftOp->getOpcode() == Instruction::AShr);
7316 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007317 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007318 ConstantInt::get(Ty, ShiftDiff));
7319 InsertNewInstBefore(Shift, I);
7320
Reid Spencer55702aa2007-03-25 21:11:44 +00007321 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007322 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007323 }
7324
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007325 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007326 if (I.getOpcode() == Instruction::LShr) {
7327 assert(ShiftOp->getOpcode() == Instruction::Shl);
7328 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007329 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007330 InsertNewInstBefore(Shift, I);
7331
Reid Spencer68d27cf2007-03-26 23:45:51 +00007332 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007333 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007334 }
7335
7336 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007337 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007338 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007339 return 0;
7340}
7341
Chris Lattnera1be5662002-05-02 17:06:02 +00007342
Chris Lattnercfd65102005-10-29 04:36:15 +00007343/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7344/// expression. If so, decompose it, returning some value X, such that Val is
7345/// X*Scale+Offset.
7346///
7347static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007348 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007349 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007350 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007351 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007352 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007353 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007354 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7355 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7356 if (I->getOpcode() == Instruction::Shl) {
7357 // This is a value scaled by '1 << the shift amt'.
7358 Scale = 1U << RHS->getZExtValue();
7359 Offset = 0;
7360 return I->getOperand(0);
7361 } else if (I->getOpcode() == Instruction::Mul) {
7362 // This value is scaled by 'RHS'.
7363 Scale = RHS->getZExtValue();
7364 Offset = 0;
7365 return I->getOperand(0);
7366 } else if (I->getOpcode() == Instruction::Add) {
7367 // We have X+C. Check to see if we really have (X*C2)+C1,
7368 // where C1 is divisible by C2.
7369 unsigned SubScale;
7370 Value *SubVal =
7371 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7372 Offset += RHS->getZExtValue();
7373 Scale = SubScale;
7374 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007375 }
7376 }
7377 }
7378
7379 // Otherwise, we can't look past this.
7380 Scale = 1;
7381 Offset = 0;
7382 return Val;
7383}
7384
7385
Chris Lattnerb3f83972005-10-24 06:03:58 +00007386/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7387/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007388Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007389 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007390 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007391
Chris Lattnerb53c2382005-10-24 06:22:12 +00007392 // Remove any uses of AI that are dead.
7393 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007394
Chris Lattnerb53c2382005-10-24 06:22:12 +00007395 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7396 Instruction *User = cast<Instruction>(*UI++);
7397 if (isInstructionTriviallyDead(User)) {
7398 while (UI != E && *UI == User)
7399 ++UI; // If this instruction uses AI more than once, don't break UI.
7400
Chris Lattnerb53c2382005-10-24 06:22:12 +00007401 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007402 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007403 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007404 }
7405 }
7406
Chris Lattnerb3f83972005-10-24 06:03:58 +00007407 // Get the type really allocated and the type casted to.
7408 const Type *AllocElTy = AI.getAllocatedType();
7409 const Type *CastElTy = PTy->getElementType();
7410 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007411
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007412 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7413 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007414 if (CastElTyAlign < AllocElTyAlign) return 0;
7415
Chris Lattner39387a52005-10-24 06:35:18 +00007416 // If the allocation has multiple uses, only promote it if we are strictly
7417 // increasing the alignment of the resultant allocation. If we keep it the
7418 // same, we open the door to infinite loops of various kinds.
7419 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7420
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007421 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7422 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007423 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007424
Chris Lattner455fcc82005-10-29 03:19:53 +00007425 // See if we can satisfy the modulus by pulling a scale out of the array
7426 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007427 unsigned ArraySizeScale;
7428 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007429 Value *NumElements = // See if the array size is a decomposable linear expr.
7430 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7431
Chris Lattner455fcc82005-10-29 03:19:53 +00007432 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7433 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007434 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7435 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007436
Chris Lattner455fcc82005-10-29 03:19:53 +00007437 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7438 Value *Amt = 0;
7439 if (Scale == 1) {
7440 Amt = NumElements;
7441 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007442 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007443 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7444 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007445 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007446 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007447 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007448 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007449 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007450 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007451 }
7452
Jeff Cohen86796be2007-04-04 16:58:57 +00007453 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7454 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007455 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007456 Amt = InsertNewInstBefore(Tmp, AI);
7457 }
7458
Chris Lattnerb3f83972005-10-24 06:03:58 +00007459 AllocationInst *New;
7460 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007461 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007462 else
Chris Lattner6934a042007-02-11 01:23:03 +00007463 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007464 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007465 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007466
7467 // If the allocation has multiple uses, insert a cast and change all things
7468 // that used it to use the new cast. This will also hack on CI, but it will
7469 // die soon.
7470 if (!AI.hasOneUse()) {
7471 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007472 // New is the allocation instruction, pointer typed. AI is the original
7473 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7474 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007475 InsertNewInstBefore(NewCast, AI);
7476 AI.replaceAllUsesWith(NewCast);
7477 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007478 return ReplaceInstUsesWith(CI, New);
7479}
7480
Chris Lattner70074e02006-05-13 02:06:03 +00007481/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007482/// and return it as type Ty without inserting any new casts and without
7483/// changing the computed value. This is used by code that tries to decide
7484/// whether promoting or shrinking integer operations to wider or smaller types
7485/// will allow us to eliminate a truncate or extend.
7486///
7487/// This is a truncation operation if Ty is smaller than V->getType(), or an
7488/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007489///
7490/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7491/// should return true if trunc(V) can be computed by computing V in the smaller
7492/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7493/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7494/// efficiently truncated.
7495///
7496/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7497/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7498/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007499bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7500 unsigned CastOpc,
7501 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007502 // We can always evaluate constants in another type.
7503 if (isa<ConstantInt>(V))
7504 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007505
7506 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007507 if (!I) return false;
7508
7509 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007510
Chris Lattner951626b2007-08-02 06:11:14 +00007511 // If this is an extension or truncate, we can often eliminate it.
7512 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7513 // If this is a cast from the destination type, we can trivially eliminate
7514 // it, and this will remove a cast overall.
7515 if (I->getOperand(0)->getType() == Ty) {
7516 // If the first operand is itself a cast, and is eliminable, do not count
7517 // this as an eliminable cast. We would prefer to eliminate those two
7518 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007519 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007520 ++NumCastsRemoved;
7521 return true;
7522 }
7523 }
7524
7525 // We can't extend or shrink something that has multiple uses: doing so would
7526 // require duplicating the instruction in general, which isn't profitable.
7527 if (!I->hasOneUse()) return false;
7528
Evan Chengf35fd542009-01-15 17:01:23 +00007529 unsigned Opc = I->getOpcode();
7530 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007531 case Instruction::Add:
7532 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007533 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007534 case Instruction::And:
7535 case Instruction::Or:
7536 case Instruction::Xor:
7537 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007538 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007539 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007540 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007541 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007542
Chris Lattner46b96052006-11-29 07:18:39 +00007543 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007544 // If we are truncating the result of this SHL, and if it's a shift of a
7545 // constant amount, we can always perform a SHL in a smaller type.
7546 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007547 uint32_t BitWidth = Ty->getBitWidth();
7548 if (BitWidth < OrigTy->getBitWidth() &&
7549 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007550 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007551 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007552 }
7553 break;
7554 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007555 // If this is a truncate of a logical shr, we can truncate it to a smaller
7556 // lshr iff we know that the bits we would otherwise be shifting in are
7557 // already zeros.
7558 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007559 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7560 uint32_t BitWidth = Ty->getBitWidth();
7561 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007562 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007563 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7564 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007565 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007566 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007567 }
7568 }
Chris Lattner46b96052006-11-29 07:18:39 +00007569 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007570 case Instruction::ZExt:
7571 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007572 case Instruction::Trunc:
7573 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007574 // can safely replace it. Note that replacing it does not reduce the number
7575 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007576 if (Opc == CastOpc)
7577 return true;
7578
7579 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007580 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007581 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007582 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007583 case Instruction::Select: {
7584 SelectInst *SI = cast<SelectInst>(I);
7585 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007586 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007587 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007588 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007589 }
Chris Lattner8114b712008-06-18 04:00:49 +00007590 case Instruction::PHI: {
7591 // We can change a phi if we can change all operands.
7592 PHINode *PN = cast<PHINode>(I);
7593 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7594 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007595 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007596 return false;
7597 return true;
7598 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007599 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007600 // TODO: Can handle more cases here.
7601 break;
7602 }
7603
7604 return false;
7605}
7606
7607/// EvaluateInDifferentType - Given an expression that
7608/// CanEvaluateInDifferentType returns true for, actually insert the code to
7609/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007610Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007611 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007612 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007613 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007614
7615 // Otherwise, it must be an instruction.
7616 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007617 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007618 unsigned Opc = I->getOpcode();
7619 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007620 case Instruction::Add:
7621 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007622 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007623 case Instruction::And:
7624 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007625 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007626 case Instruction::AShr:
7627 case Instruction::LShr:
7628 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007629 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007630 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007631 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007632 break;
7633 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007634 case Instruction::Trunc:
7635 case Instruction::ZExt:
7636 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007637 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007638 // just return the source. There's no need to insert it because it is not
7639 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007640 if (I->getOperand(0)->getType() == Ty)
7641 return I->getOperand(0);
7642
Chris Lattner8114b712008-06-18 04:00:49 +00007643 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007644 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007645 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007646 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007647 case Instruction::Select: {
7648 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7649 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7650 Res = SelectInst::Create(I->getOperand(0), True, False);
7651 break;
7652 }
Chris Lattner8114b712008-06-18 04:00:49 +00007653 case Instruction::PHI: {
7654 PHINode *OPN = cast<PHINode>(I);
7655 PHINode *NPN = PHINode::Create(Ty);
7656 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7657 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7658 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7659 }
7660 Res = NPN;
7661 break;
7662 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007663 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007664 // TODO: Can handle more cases here.
7665 assert(0 && "Unreachable!");
7666 break;
7667 }
7668
Chris Lattner8114b712008-06-18 04:00:49 +00007669 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007670 return InsertNewInstBefore(Res, *I);
7671}
7672
Reid Spencer3da59db2006-11-27 01:05:10 +00007673/// @brief Implement the transforms common to all CastInst visitors.
7674Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007675 Value *Src = CI.getOperand(0);
7676
Dan Gohman23d9d272007-05-11 21:10:54 +00007677 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007678 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007679 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007680 if (Instruction::CastOps opc =
7681 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7682 // The first cast (CSrc) is eliminable so we need to fix up or replace
7683 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007684 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007685 }
7686 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007687
Reid Spencer3da59db2006-11-27 01:05:10 +00007688 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007689 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7690 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7691 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007692
7693 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007694 if (isa<PHINode>(Src))
7695 if (Instruction *NV = FoldOpIntoPhi(CI))
7696 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007697
Reid Spencer3da59db2006-11-27 01:05:10 +00007698 return 0;
7699}
7700
Chris Lattner46cd5a12009-01-09 05:44:56 +00007701/// FindElementAtOffset - Given a type and a constant offset, determine whether
7702/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007703/// the specified offset. If so, fill them into NewIndices and return the
7704/// resultant element type, otherwise return null.
7705static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7706 SmallVectorImpl<Value*> &NewIndices,
7707 const TargetData *TD) {
7708 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007709
7710 // Start with the index over the outer type. Note that the type size
7711 // might be zero (even if the offset isn't zero) if the indexed type
7712 // is something like [0 x {int, int}]
7713 const Type *IntPtrTy = TD->getIntPtrType();
7714 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007715 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007716 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007717 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007718
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007719 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007720 if (Offset < 0) {
7721 --FirstIdx;
7722 Offset += TySize;
7723 assert(Offset >= 0);
7724 }
7725 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7726 }
7727
7728 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7729
7730 // Index into the types. If we fail, set OrigBase to null.
7731 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007732 // Indexing into tail padding between struct/array elements.
7733 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007734 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007735
Chris Lattner46cd5a12009-01-09 05:44:56 +00007736 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7737 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007738 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7739 "Offset must stay within the indexed type");
7740
Chris Lattner46cd5a12009-01-09 05:44:56 +00007741 unsigned Elt = SL->getElementContainingOffset(Offset);
7742 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7743
7744 Offset -= SL->getElementOffset(Elt);
7745 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007746 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007747 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007748 assert(EltSize && "Cannot index into a zero-sized array");
7749 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7750 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007751 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007752 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007753 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007754 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007755 }
7756 }
7757
Chris Lattner3914f722009-01-24 01:00:13 +00007758 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007759}
7760
Chris Lattnerd3e28342007-04-27 17:44:50 +00007761/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7762Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7763 Value *Src = CI.getOperand(0);
7764
Chris Lattnerd3e28342007-04-27 17:44:50 +00007765 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007766 // If casting the result of a getelementptr instruction with no offset, turn
7767 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007768 if (GEP->hasAllZeroIndices()) {
7769 // Changing the cast operand is usually not a good idea but it is safe
7770 // here because the pointer operand is being replaced with another
7771 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007772 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007773 CI.setOperand(0, GEP->getOperand(0));
7774 return &CI;
7775 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007776
7777 // If the GEP has a single use, and the base pointer is a bitcast, and the
7778 // GEP computes a constant offset, see if we can convert these three
7779 // instructions into fewer. This typically happens with unions and other
7780 // non-type-safe code.
7781 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7782 if (GEP->hasAllConstantIndices()) {
7783 // We are guaranteed to get a constant from EmitGEPOffset.
7784 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7785 int64_t Offset = OffsetV->getSExtValue();
7786
7787 // Get the base pointer input of the bitcast, and the type it points to.
7788 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7789 const Type *GEPIdxTy =
7790 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007791 SmallVector<Value*, 8> NewIndices;
7792 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7793 // If we were able to index down into an element, create the GEP
7794 // and bitcast the result. This eliminates one bitcast, potentially
7795 // two.
7796 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7797 NewIndices.begin(),
7798 NewIndices.end(), "");
7799 InsertNewInstBefore(NGEP, CI);
7800 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007801
Chris Lattner46cd5a12009-01-09 05:44:56 +00007802 if (isa<BitCastInst>(CI))
7803 return new BitCastInst(NGEP, CI.getType());
7804 assert(isa<PtrToIntInst>(CI));
7805 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007806 }
7807 }
7808 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007809 }
7810
7811 return commonCastTransforms(CI);
7812}
7813
7814
Chris Lattnerc739cd62007-03-03 05:27:34 +00007815/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7816/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007817/// cases.
7818/// @brief Implement the transforms common to CastInst with integer operands
7819Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7820 if (Instruction *Result = commonCastTransforms(CI))
7821 return Result;
7822
7823 Value *Src = CI.getOperand(0);
7824 const Type *SrcTy = Src->getType();
7825 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007826 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7827 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007828
Reid Spencer3da59db2006-11-27 01:05:10 +00007829 // See if we can simplify any instructions used by the LHS whose sole
7830 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007831 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7832 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007833 KnownZero, KnownOne))
7834 return &CI;
7835
7836 // If the source isn't an instruction or has more than one use then we
7837 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007838 Instruction *SrcI = dyn_cast<Instruction>(Src);
7839 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007840 return 0;
7841
Chris Lattnerc739cd62007-03-03 05:27:34 +00007842 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007843 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007844 if (!isa<BitCastInst>(CI) &&
7845 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00007846 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007847 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007848 // eliminates the cast, so it is always a win. If this is a zero-extension,
7849 // we need to do an AND to maintain the clear top-part of the computation,
7850 // so we require that the input have eliminated at least one cast. If this
7851 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007852 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007853 bool DoXForm = false;
7854 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007855 switch (CI.getOpcode()) {
7856 default:
7857 // All the others use floating point so we shouldn't actually
7858 // get here because of the check above.
7859 assert(0 && "Unknown cast type");
7860 case Instruction::Trunc:
7861 DoXForm = true;
7862 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007863 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007864 DoXForm = NumCastsRemoved >= 1;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007865 if (!DoXForm) {
7866 // If it's unnecessary to issue an AND to clear the high bits, it's
7867 // always profitable to do this xform.
7868 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7869 CI.getOpcode() == Instruction::SExt);
7870 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7871 if (MaskedValueIsZero(TryRes, Mask))
7872 return ReplaceInstUsesWith(CI, TryRes);
7873 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7874 if (TryI->use_empty())
7875 EraseInstFromFunction(*TryI);
7876 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007877 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007878 }
Evan Chengf35fd542009-01-15 17:01:23 +00007879 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007880 DoXForm = NumCastsRemoved >= 2;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007881 if (!DoXForm && !isa<TruncInst>(SrcI)) {
7882 // If we do not have to emit the truncate + sext pair, then it's always
7883 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007884 //
7885 // It's not safe to eliminate the trunc + sext pair if one of the
7886 // eliminated cast is a truncate. e.g.
7887 // t2 = trunc i32 t1 to i16
7888 // t3 = sext i16 t2 to i32
7889 // !=
7890 // i32 t1
Evan Cheng4e56ab22009-01-16 02:11:43 +00007891 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7892 CI.getOpcode() == Instruction::SExt);
7893 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7894 if (NumSignBits > (DestBitSize - SrcBitSize))
7895 return ReplaceInstUsesWith(CI, TryRes);
7896 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7897 if (TryI->use_empty())
7898 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00007899 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007900 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007901 }
Evan Chengf35fd542009-01-15 17:01:23 +00007902 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007903
7904 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007905 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7906 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007907 if (JustReplace)
7908 // Just replace this cast with the result.
7909 return ReplaceInstUsesWith(CI, Res);
7910
Reid Spencer3da59db2006-11-27 01:05:10 +00007911 assert(Res->getType() == DestTy);
7912 switch (CI.getOpcode()) {
7913 default: assert(0 && "Unknown cast type!");
7914 case Instruction::Trunc:
7915 case Instruction::BitCast:
7916 // Just replace this cast with the result.
7917 return ReplaceInstUsesWith(CI, Res);
7918 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00007919 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00007920
7921 // If the high bits are already zero, just replace this cast with the
7922 // result.
7923 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7924 if (MaskedValueIsZero(Res, Mask))
7925 return ReplaceInstUsesWith(CI, Res);
7926
7927 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007928 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7929 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007930 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007931 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007932 case Instruction::SExt: {
7933 // If the high bits are already filled with sign bit, just replace this
7934 // cast with the result.
7935 unsigned NumSignBits = ComputeNumSignBits(Res);
7936 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00007937 return ReplaceInstUsesWith(CI, Res);
7938
Reid Spencer3da59db2006-11-27 01:05:10 +00007939 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007940 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007941 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7942 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007943 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00007944 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007945 }
7946 }
7947
7948 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7949 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7950
7951 switch (SrcI->getOpcode()) {
7952 case Instruction::Add:
7953 case Instruction::Mul:
7954 case Instruction::And:
7955 case Instruction::Or:
7956 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007957 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007958 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7959 // Don't insert two casts if they cannot be eliminated. We allow
7960 // two casts to be inserted if the sizes are the same. This could
7961 // only be converting signedness, which is a noop.
7962 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007963 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7964 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007965 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007966 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7967 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007968 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007969 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007970 }
7971 }
7972
7973 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7974 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7975 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007976 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007977 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007978 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007979 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007980 }
7981 break;
7982 case Instruction::SDiv:
7983 case Instruction::UDiv:
7984 case Instruction::SRem:
7985 case Instruction::URem:
7986 // If we are just changing the sign, rewrite.
7987 if (DestBitSize == SrcBitSize) {
7988 // Don't insert two casts if they cannot be eliminated. We allow
7989 // two casts to be inserted if the sizes are the same. This could
7990 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007991 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7992 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00007993 Value *Op0c = InsertCastBefore(Instruction::BitCast,
7994 Op0, DestTy, *SrcI);
7995 Value *Op1c = InsertCastBefore(Instruction::BitCast,
7996 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007997 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007998 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7999 }
8000 }
8001 break;
8002
8003 case Instruction::Shl:
8004 // Allow changing the sign of the source operand. Do not allow
8005 // changing the size of the shift, UNLESS the shift amount is a
8006 // constant. We must not change variable sized shifts to a smaller
8007 // size, because it is undefined to shift more bits out than exist
8008 // in the value.
8009 if (DestBitSize == SrcBitSize ||
8010 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008011 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8012 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008013 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8014 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008015 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008016 }
8017 break;
8018 case Instruction::AShr:
8019 // If this is a signed shr, and if all bits shifted in are about to be
8020 // truncated off, turn it into an unsigned shr to allow greater
8021 // simplifications.
8022 if (DestBitSize < SrcBitSize &&
8023 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008024 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008025 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8026 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008027 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008028 }
8029 }
8030 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008031 }
8032 return 0;
8033}
8034
Chris Lattner8a9f5712007-04-11 06:57:46 +00008035Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008036 if (Instruction *Result = commonIntCastTransforms(CI))
8037 return Result;
8038
8039 Value *Src = CI.getOperand(0);
8040 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008041 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8042 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008043
8044 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8045 switch (SrcI->getOpcode()) {
8046 default: break;
8047 case Instruction::LShr:
8048 // We can shrink lshr to something smaller if we know the bits shifted in
8049 // are already zeros.
8050 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008051 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008052
8053 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00008054 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00008055 Value* SrcIOp0 = SrcI->getOperand(0);
8056 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008057 if (ShAmt >= DestBitWidth) // All zeros.
8058 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8059
8060 // Okay, we can shrink this. Truncate the input, then return a new
8061 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00008062 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8063 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8064 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008065 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008066 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008067 } else { // This is a variable shr.
8068
8069 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8070 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8071 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00008072 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008073 Value *One = ConstantInt::get(SrcI->getType(), 1);
8074
Reid Spencer832254e2007-02-02 02:16:23 +00008075 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008076 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00008077 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008078 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008079 SrcI->getOperand(0),
8080 "tmp"), CI);
8081 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008082 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008083 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008084 }
8085 break;
8086 }
8087 }
8088
8089 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008090}
8091
Evan Chengb98a10e2008-03-24 00:21:34 +00008092/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8093/// in order to eliminate the icmp.
8094Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8095 bool DoXform) {
8096 // If we are just checking for a icmp eq of a single bit and zext'ing it
8097 // to an integer, then shift the bit to the appropriate place and then
8098 // cast to integer to avoid the comparison.
8099 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8100 const APInt &Op1CV = Op1C->getValue();
8101
8102 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8103 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8104 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8105 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8106 if (!DoXform) return ICI;
8107
8108 Value *In = ICI->getOperand(0);
8109 Value *Sh = ConstantInt::get(In->getType(),
8110 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008111 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008112 In->getName()+".lobit"),
8113 CI);
8114 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008115 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008116 false/*ZExt*/, "tmp", &CI);
8117
8118 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8119 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008120 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008121 In->getName()+".not"),
8122 CI);
8123 }
8124
8125 return ReplaceInstUsesWith(CI, In);
8126 }
8127
8128
8129
8130 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8131 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8132 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8133 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8134 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8135 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8136 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8137 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8138 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8139 // This only works for EQ and NE
8140 ICI->isEquality()) {
8141 // If Op1C some other power of two, convert:
8142 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8143 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8144 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8145 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8146
8147 APInt KnownZeroMask(~KnownZero);
8148 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8149 if (!DoXform) return ICI;
8150
8151 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8152 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8153 // (X&4) == 2 --> false
8154 // (X&4) != 2 --> true
8155 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8156 Res = ConstantExpr::getZExt(Res, CI.getType());
8157 return ReplaceInstUsesWith(CI, Res);
8158 }
8159
8160 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8161 Value *In = ICI->getOperand(0);
8162 if (ShiftAmt) {
8163 // Perform a logical shr by shiftamt.
8164 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008165 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008166 ConstantInt::get(In->getType(), ShiftAmt),
8167 In->getName()+".lobit"), CI);
8168 }
8169
8170 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8171 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008172 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008173 InsertNewInstBefore(cast<Instruction>(In), CI);
8174 }
8175
8176 if (CI.getType() == In->getType())
8177 return ReplaceInstUsesWith(CI, In);
8178 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008179 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008180 }
8181 }
8182 }
8183
8184 return 0;
8185}
8186
Chris Lattner8a9f5712007-04-11 06:57:46 +00008187Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008188 // If one of the common conversion will work ..
8189 if (Instruction *Result = commonIntCastTransforms(CI))
8190 return Result;
8191
8192 Value *Src = CI.getOperand(0);
8193
8194 // If this is a cast of a cast
8195 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008196 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8197 // types and if the sizes are just right we can convert this into a logical
8198 // 'and' which will be much cheaper than the pair of casts.
8199 if (isa<TruncInst>(CSrc)) {
8200 // Get the sizes of the types involved
8201 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008202 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8203 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8204 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008205 // If we're actually extending zero bits and the trunc is a no-op
8206 if (MidSize < DstSize && SrcSize == DstSize) {
8207 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008208 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008209 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008210 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008211 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008212 // Unfortunately, if the type changed, we need to cast it back.
8213 if (And->getType() != CI.getType()) {
8214 And->setName(CSrc->getName()+".mask");
8215 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008216 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008217 }
8218 return And;
8219 }
8220 }
8221 }
8222
Evan Chengb98a10e2008-03-24 00:21:34 +00008223 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8224 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008225
Evan Chengb98a10e2008-03-24 00:21:34 +00008226 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8227 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8228 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8229 // of the (zext icmp) will be transformed.
8230 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8231 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8232 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8233 (transformZExtICmp(LHS, CI, false) ||
8234 transformZExtICmp(RHS, CI, false))) {
8235 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8236 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008237 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008238 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008239 }
8240
Reid Spencer3da59db2006-11-27 01:05:10 +00008241 return 0;
8242}
8243
Chris Lattner8a9f5712007-04-11 06:57:46 +00008244Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008245 if (Instruction *I = commonIntCastTransforms(CI))
8246 return I;
8247
Chris Lattner8a9f5712007-04-11 06:57:46 +00008248 Value *Src = CI.getOperand(0);
8249
Dan Gohman1975d032008-10-30 20:40:10 +00008250 // Canonicalize sign-extend from i1 to a select.
8251 if (Src->getType() == Type::Int1Ty)
8252 return SelectInst::Create(Src,
8253 ConstantInt::getAllOnesValue(CI.getType()),
8254 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008255
8256 // See if the value being truncated is already sign extended. If so, just
8257 // eliminate the trunc/sext pair.
8258 if (getOpcode(Src) == Instruction::Trunc) {
8259 Value *Op = cast<User>(Src)->getOperand(0);
8260 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8261 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8262 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8263 unsigned NumSignBits = ComputeNumSignBits(Op);
8264
8265 if (OpBits == DestBits) {
8266 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8267 // bits, it is already ready.
8268 if (NumSignBits > DestBits-MidBits)
8269 return ReplaceInstUsesWith(CI, Op);
8270 } else if (OpBits < DestBits) {
8271 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8272 // bits, just sext from i32.
8273 if (NumSignBits > OpBits-MidBits)
8274 return new SExtInst(Op, CI.getType(), "tmp");
8275 } else {
8276 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8277 // bits, just truncate to i32.
8278 if (NumSignBits > OpBits-MidBits)
8279 return new TruncInst(Op, CI.getType(), "tmp");
8280 }
8281 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008282
8283 // If the input is a shl/ashr pair of a same constant, then this is a sign
8284 // extension from a smaller value. If we could trust arbitrary bitwidth
8285 // integers, we could turn this into a truncate to the smaller bit and then
8286 // use a sext for the whole extension. Since we don't, look deeper and check
8287 // for a truncate. If the source and dest are the same type, eliminate the
8288 // trunc and extend and just do shifts. For example, turn:
8289 // %a = trunc i32 %i to i8
8290 // %b = shl i8 %a, 6
8291 // %c = ashr i8 %b, 6
8292 // %d = sext i8 %c to i32
8293 // into:
8294 // %a = shl i32 %i, 30
8295 // %d = ashr i32 %a, 30
8296 Value *A = 0;
8297 ConstantInt *BA = 0, *CA = 0;
8298 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8299 m_ConstantInt(CA))) &&
8300 BA == CA && isa<TruncInst>(A)) {
8301 Value *I = cast<TruncInst>(A)->getOperand(0);
8302 if (I->getType() == CI.getType()) {
8303 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8304 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8305 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8306 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8307 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8308 CI.getName()), CI);
8309 return BinaryOperator::CreateAShr(I, ShAmtV);
8310 }
8311 }
8312
Chris Lattnerba417832007-04-11 06:12:58 +00008313 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008314}
8315
Chris Lattnerb7530652008-01-27 05:29:54 +00008316/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8317/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008318static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008319 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008320 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008321 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8322 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008323 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008324 return 0;
8325}
8326
8327/// LookThroughFPExtensions - If this is an fp extension instruction, look
8328/// through it until we get the source value.
8329static Value *LookThroughFPExtensions(Value *V) {
8330 if (Instruction *I = dyn_cast<Instruction>(V))
8331 if (I->getOpcode() == Instruction::FPExt)
8332 return LookThroughFPExtensions(I->getOperand(0));
8333
8334 // If this value is a constant, return the constant in the smallest FP type
8335 // that can accurately represent it. This allows us to turn
8336 // (float)((double)X+2.0) into x+2.0f.
8337 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8338 if (CFP->getType() == Type::PPC_FP128Ty)
8339 return V; // No constant folding of this.
8340 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008341 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008342 return V;
8343 if (CFP->getType() == Type::DoubleTy)
8344 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008345 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008346 return V;
8347 // Don't try to shrink to various long double types.
8348 }
8349
8350 return V;
8351}
8352
8353Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8354 if (Instruction *I = commonCastTransforms(CI))
8355 return I;
8356
8357 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8358 // smaller than the destination type, we can eliminate the truncate by doing
8359 // the add as the smaller type. This applies to add/sub/mul/div as well as
8360 // many builtins (sqrt, etc).
8361 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8362 if (OpI && OpI->hasOneUse()) {
8363 switch (OpI->getOpcode()) {
8364 default: break;
8365 case Instruction::Add:
8366 case Instruction::Sub:
8367 case Instruction::Mul:
8368 case Instruction::FDiv:
8369 case Instruction::FRem:
8370 const Type *SrcTy = OpI->getType();
8371 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8372 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8373 if (LHSTrunc->getType() != SrcTy &&
8374 RHSTrunc->getType() != SrcTy) {
8375 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8376 // If the source types were both smaller than the destination type of
8377 // the cast, do this xform.
8378 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8379 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8380 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8381 CI.getType(), CI);
8382 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8383 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008384 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008385 }
8386 }
8387 break;
8388 }
8389 }
8390 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008391}
8392
8393Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8394 return commonCastTransforms(CI);
8395}
8396
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008397Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008398 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8399 if (OpI == 0)
8400 return commonCastTransforms(FI);
8401
8402 // fptoui(uitofp(X)) --> X
8403 // fptoui(sitofp(X)) --> X
8404 // This is safe if the intermediate type has enough bits in its mantissa to
8405 // accurately represent all values of X. For example, do not do this with
8406 // i64->float->i64. This is also safe for sitofp case, because any negative
8407 // 'X' value would cause an undefined result for the fptoui.
8408 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8409 OpI->getOperand(0)->getType() == FI.getType() &&
8410 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8411 OpI->getType()->getFPMantissaWidth())
8412 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008413
8414 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008415}
8416
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008417Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008418 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8419 if (OpI == 0)
8420 return commonCastTransforms(FI);
8421
8422 // fptosi(sitofp(X)) --> X
8423 // fptosi(uitofp(X)) --> X
8424 // This is safe if the intermediate type has enough bits in its mantissa to
8425 // accurately represent all values of X. For example, do not do this with
8426 // i64->float->i64. This is also safe for sitofp case, because any negative
8427 // 'X' value would cause an undefined result for the fptoui.
8428 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8429 OpI->getOperand(0)->getType() == FI.getType() &&
8430 (int)FI.getType()->getPrimitiveSizeInBits() <=
8431 OpI->getType()->getFPMantissaWidth())
8432 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008433
8434 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008435}
8436
8437Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8438 return commonCastTransforms(CI);
8439}
8440
8441Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8442 return commonCastTransforms(CI);
8443}
8444
8445Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008446 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008447}
8448
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008449Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8450 if (Instruction *I = commonCastTransforms(CI))
8451 return I;
8452
8453 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8454 if (!DestPointee->isSized()) return 0;
8455
8456 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8457 ConstantInt *Cst;
8458 Value *X;
8459 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8460 m_ConstantInt(Cst)))) {
8461 // If the source and destination operands have the same type, see if this
8462 // is a single-index GEP.
8463 if (X->getType() == CI.getType()) {
8464 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008465 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008466
8467 // Convert the constant to intptr type.
8468 APInt Offset = Cst->getValue();
8469 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8470
8471 // If Offset is evenly divisible by Size, we can do this xform.
8472 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8473 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008474 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008475 }
8476 }
8477 // TODO: Could handle other cases, e.g. where add is indexing into field of
8478 // struct etc.
8479 } else if (CI.getOperand(0)->hasOneUse() &&
8480 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8481 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8482 // "inttoptr+GEP" instead of "add+intptr".
8483
8484 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008485 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008486
8487 // Convert the constant to intptr type.
8488 APInt Offset = Cst->getValue();
8489 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8490
8491 // If Offset is evenly divisible by Size, we can do this xform.
8492 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8493 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8494
8495 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8496 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008497 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008498 }
8499 }
8500 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008501}
8502
Chris Lattnerd3e28342007-04-27 17:44:50 +00008503Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008504 // If the operands are integer typed then apply the integer transforms,
8505 // otherwise just apply the common ones.
8506 Value *Src = CI.getOperand(0);
8507 const Type *SrcTy = Src->getType();
8508 const Type *DestTy = CI.getType();
8509
Chris Lattner42a75512007-01-15 02:27:26 +00008510 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008511 if (Instruction *Result = commonIntCastTransforms(CI))
8512 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008513 } else if (isa<PointerType>(SrcTy)) {
8514 if (Instruction *I = commonPointerCastTransforms(CI))
8515 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008516 } else {
8517 if (Instruction *Result = commonCastTransforms(CI))
8518 return Result;
8519 }
8520
8521
8522 // Get rid of casts from one type to the same type. These are useless and can
8523 // be replaced by the operand.
8524 if (DestTy == Src->getType())
8525 return ReplaceInstUsesWith(CI, Src);
8526
Reid Spencer3da59db2006-11-27 01:05:10 +00008527 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008528 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8529 const Type *DstElTy = DstPTy->getElementType();
8530 const Type *SrcElTy = SrcPTy->getElementType();
8531
Nate Begeman83ad90a2008-03-31 00:22:16 +00008532 // If the address spaces don't match, don't eliminate the bitcast, which is
8533 // required for changing types.
8534 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8535 return 0;
8536
Chris Lattnerd3e28342007-04-27 17:44:50 +00008537 // If we are casting a malloc or alloca to a pointer to a type of the same
8538 // size, rewrite the allocation instruction to allocate the "right" type.
8539 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8540 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8541 return V;
8542
Chris Lattnerd717c182007-05-05 22:32:24 +00008543 // If the source and destination are pointers, and this cast is equivalent
8544 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008545 // This can enhance SROA and other transforms that want type-safe pointers.
8546 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8547 unsigned NumZeros = 0;
8548 while (SrcElTy != DstElTy &&
8549 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8550 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8551 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8552 ++NumZeros;
8553 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008554
Chris Lattnerd3e28342007-04-27 17:44:50 +00008555 // If we found a path from the src to dest, create the getelementptr now.
8556 if (SrcElTy == DstElTy) {
8557 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008558 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8559 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008560 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008561 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008562
Reid Spencer3da59db2006-11-27 01:05:10 +00008563 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8564 if (SVI->hasOneUse()) {
8565 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8566 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008567 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008568 cast<VectorType>(DestTy)->getNumElements() ==
8569 SVI->getType()->getNumElements() &&
8570 SVI->getType()->getNumElements() ==
8571 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008572 CastInst *Tmp;
8573 // If either of the operands is a cast from CI.getType(), then
8574 // evaluating the shuffle in the casted destination's type will allow
8575 // us to eliminate at least one cast.
8576 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8577 Tmp->getOperand(0)->getType() == DestTy) ||
8578 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8579 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008580 Value *LHS = InsertCastBefore(Instruction::BitCast,
8581 SVI->getOperand(0), DestTy, CI);
8582 Value *RHS = InsertCastBefore(Instruction::BitCast,
8583 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008584 // Return a new shuffle vector. Use the same element ID's, as we
8585 // know the vector types match #elts.
8586 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008587 }
8588 }
8589 }
8590 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008591 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008592}
8593
Chris Lattnere576b912004-04-09 23:46:01 +00008594/// GetSelectFoldableOperands - We want to turn code that looks like this:
8595/// %C = or %A, %B
8596/// %D = select %cond, %C, %A
8597/// into:
8598/// %C = select %cond, %B, 0
8599/// %D = or %A, %C
8600///
8601/// Assuming that the specified instruction is an operand to the select, return
8602/// a bitmask indicating which operands of this instruction are foldable if they
8603/// equal the other incoming value of the select.
8604///
8605static unsigned GetSelectFoldableOperands(Instruction *I) {
8606 switch (I->getOpcode()) {
8607 case Instruction::Add:
8608 case Instruction::Mul:
8609 case Instruction::And:
8610 case Instruction::Or:
8611 case Instruction::Xor:
8612 return 3; // Can fold through either operand.
8613 case Instruction::Sub: // Can only fold on the amount subtracted.
8614 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008615 case Instruction::LShr:
8616 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008617 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008618 default:
8619 return 0; // Cannot fold
8620 }
8621}
8622
8623/// GetSelectFoldableConstant - For the same transformation as the previous
8624/// function, return the identity constant that goes into the select.
8625static Constant *GetSelectFoldableConstant(Instruction *I) {
8626 switch (I->getOpcode()) {
8627 default: assert(0 && "This cannot happen!"); abort();
8628 case Instruction::Add:
8629 case Instruction::Sub:
8630 case Instruction::Or:
8631 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008632 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008633 case Instruction::LShr:
8634 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008635 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008636 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008637 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008638 case Instruction::Mul:
8639 return ConstantInt::get(I->getType(), 1);
8640 }
8641}
8642
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008643/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8644/// have the same opcode and only one use each. Try to simplify this.
8645Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8646 Instruction *FI) {
8647 if (TI->getNumOperands() == 1) {
8648 // If this is a non-volatile load or a cast from the same type,
8649 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008650 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008651 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8652 return 0;
8653 } else {
8654 return 0; // unknown unary op.
8655 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008656
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008657 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008658 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8659 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008660 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008661 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008662 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008663 }
8664
Reid Spencer832254e2007-02-02 02:16:23 +00008665 // Only handle binary operators here.
8666 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008667 return 0;
8668
8669 // Figure out if the operations have any operands in common.
8670 Value *MatchOp, *OtherOpT, *OtherOpF;
8671 bool MatchIsOpZero;
8672 if (TI->getOperand(0) == FI->getOperand(0)) {
8673 MatchOp = TI->getOperand(0);
8674 OtherOpT = TI->getOperand(1);
8675 OtherOpF = FI->getOperand(1);
8676 MatchIsOpZero = true;
8677 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8678 MatchOp = TI->getOperand(1);
8679 OtherOpT = TI->getOperand(0);
8680 OtherOpF = FI->getOperand(0);
8681 MatchIsOpZero = false;
8682 } else if (!TI->isCommutative()) {
8683 return 0;
8684 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8685 MatchOp = TI->getOperand(0);
8686 OtherOpT = TI->getOperand(1);
8687 OtherOpF = FI->getOperand(0);
8688 MatchIsOpZero = true;
8689 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8690 MatchOp = TI->getOperand(1);
8691 OtherOpT = TI->getOperand(0);
8692 OtherOpF = FI->getOperand(1);
8693 MatchIsOpZero = true;
8694 } else {
8695 return 0;
8696 }
8697
8698 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008699 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8700 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008701 InsertNewInstBefore(NewSI, SI);
8702
8703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8704 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008705 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008706 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008707 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008708 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008709 assert(0 && "Shouldn't get here");
8710 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008711}
8712
Dan Gohman81b28ce2008-09-16 18:46:06 +00008713/// visitSelectInstWithICmp - Visit a SelectInst that has an
8714/// ICmpInst as its first operand.
8715///
8716Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8717 ICmpInst *ICI) {
8718 bool Changed = false;
8719 ICmpInst::Predicate Pred = ICI->getPredicate();
8720 Value *CmpLHS = ICI->getOperand(0);
8721 Value *CmpRHS = ICI->getOperand(1);
8722 Value *TrueVal = SI.getTrueValue();
8723 Value *FalseVal = SI.getFalseValue();
8724
8725 // Check cases where the comparison is with a constant that
8726 // can be adjusted to fit the min/max idiom. We may edit ICI in
8727 // place here, so make sure the select is the only user.
8728 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008729 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008730 switch (Pred) {
8731 default: break;
8732 case ICmpInst::ICMP_ULT:
8733 case ICmpInst::ICMP_SLT: {
8734 // X < MIN ? T : F --> F
8735 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8736 return ReplaceInstUsesWith(SI, FalseVal);
8737 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8738 Constant *AdjustedRHS = SubOne(CI);
8739 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8740 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8741 Pred = ICmpInst::getSwappedPredicate(Pred);
8742 CmpRHS = AdjustedRHS;
8743 std::swap(FalseVal, TrueVal);
8744 ICI->setPredicate(Pred);
8745 ICI->setOperand(1, CmpRHS);
8746 SI.setOperand(1, TrueVal);
8747 SI.setOperand(2, FalseVal);
8748 Changed = true;
8749 }
8750 break;
8751 }
8752 case ICmpInst::ICMP_UGT:
8753 case ICmpInst::ICMP_SGT: {
8754 // X > MAX ? T : F --> F
8755 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8756 return ReplaceInstUsesWith(SI, FalseVal);
8757 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8758 Constant *AdjustedRHS = AddOne(CI);
8759 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8760 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8761 Pred = ICmpInst::getSwappedPredicate(Pred);
8762 CmpRHS = AdjustedRHS;
8763 std::swap(FalseVal, TrueVal);
8764 ICI->setPredicate(Pred);
8765 ICI->setOperand(1, CmpRHS);
8766 SI.setOperand(1, TrueVal);
8767 SI.setOperand(2, FalseVal);
8768 Changed = true;
8769 }
8770 break;
8771 }
8772 }
8773
Dan Gohman1975d032008-10-30 20:40:10 +00008774 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8775 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008776 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00008777 if (match(TrueVal, m_ConstantInt<-1>()) &&
8778 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008779 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00008780 else if (match(TrueVal, m_ConstantInt<0>()) &&
8781 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008782 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8783
Dan Gohman1975d032008-10-30 20:40:10 +00008784 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8785 // If we are just checking for a icmp eq of a single bit and zext'ing it
8786 // to an integer, then shift the bit to the appropriate place and then
8787 // cast to integer to avoid the comparison.
8788 const APInt &Op1CV = CI->getValue();
8789
8790 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8791 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8792 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008793 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008794 Value *In = ICI->getOperand(0);
8795 Value *Sh = ConstantInt::get(In->getType(),
8796 In->getType()->getPrimitiveSizeInBits()-1);
8797 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8798 In->getName()+".lobit"),
8799 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00008800 if (In->getType() != SI.getType())
8801 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00008802 true/*SExt*/, "tmp", ICI);
8803
8804 if (Pred == ICmpInst::ICMP_SGT)
8805 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8806 In->getName()+".not"), *ICI);
8807
8808 return ReplaceInstUsesWith(SI, In);
8809 }
8810 }
8811 }
8812
Dan Gohman81b28ce2008-09-16 18:46:06 +00008813 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8814 // Transform (X == Y) ? X : Y -> Y
8815 if (Pred == ICmpInst::ICMP_EQ)
8816 return ReplaceInstUsesWith(SI, FalseVal);
8817 // Transform (X != Y) ? X : Y -> X
8818 if (Pred == ICmpInst::ICMP_NE)
8819 return ReplaceInstUsesWith(SI, TrueVal);
8820 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8821
8822 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8823 // Transform (X == Y) ? Y : X -> X
8824 if (Pred == ICmpInst::ICMP_EQ)
8825 return ReplaceInstUsesWith(SI, FalseVal);
8826 // Transform (X != Y) ? Y : X -> Y
8827 if (Pred == ICmpInst::ICMP_NE)
8828 return ReplaceInstUsesWith(SI, TrueVal);
8829 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8830 }
8831
8832 /// NOTE: if we wanted to, this is where to detect integer ABS
8833
8834 return Changed ? &SI : 0;
8835}
8836
Chris Lattner3d69f462004-03-12 05:52:32 +00008837Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008838 Value *CondVal = SI.getCondition();
8839 Value *TrueVal = SI.getTrueValue();
8840 Value *FalseVal = SI.getFalseValue();
8841
8842 // select true, X, Y -> X
8843 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008844 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008845 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008846
8847 // select C, X, X -> X
8848 if (TrueVal == FalseVal)
8849 return ReplaceInstUsesWith(SI, TrueVal);
8850
Chris Lattnere87597f2004-10-16 18:11:37 +00008851 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8852 return ReplaceInstUsesWith(SI, FalseVal);
8853 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8854 return ReplaceInstUsesWith(SI, TrueVal);
8855 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8856 if (isa<Constant>(TrueVal))
8857 return ReplaceInstUsesWith(SI, TrueVal);
8858 else
8859 return ReplaceInstUsesWith(SI, FalseVal);
8860 }
8861
Reid Spencer4fe16d62007-01-11 18:21:29 +00008862 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008863 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008864 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008865 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008866 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008867 } else {
8868 // Change: A = select B, false, C --> A = and !B, C
8869 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008870 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008871 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008872 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008873 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008874 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008875 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008876 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008877 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008878 } else {
8879 // Change: A = select B, C, true --> A = or !B, C
8880 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008881 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008882 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008883 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008884 }
8885 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008886
8887 // select a, b, a -> a&b
8888 // select a, a, b -> a|b
8889 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008890 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008891 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008892 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008893 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008894
Chris Lattner2eefe512004-04-09 19:05:30 +00008895 // Selecting between two integer constants?
8896 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8897 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008898 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008899 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008900 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008901 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008902 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008903 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008904 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008905 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008906 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008907 }
Chris Lattner457dd822004-06-09 07:59:58 +00008908
Reid Spencere4d87aa2006-12-23 06:05:41 +00008909 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008910
Reid Spencere4d87aa2006-12-23 06:05:41 +00008911 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008912 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008913 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008914 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008915 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008916 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008917 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008918 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008919 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008920 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008921 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008922 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008923
8924 // Then cast to the appropriate width.
8925 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00008926 }
8927 }
8928
8929
8930 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008931 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008932 // non-constant value, eliminate this whole mess. This corresponds to
8933 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008934 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008935 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008936 cast<Constant>(IC->getOperand(1))->isNullValue())
8937 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8938 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008939 isa<ConstantInt>(ICA->getOperand(1)) &&
8940 (ICA->getOperand(1) == TrueValC ||
8941 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008942 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8943 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008944 // know whether we have a icmp_ne or icmp_eq and whether the
8945 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008946 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008947 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008948 Value *V = ICA;
8949 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008950 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008951 Instruction::Xor, V, ICA->getOperand(1)), SI);
8952 return ReplaceInstUsesWith(SI, V);
8953 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008954 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008955 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008956
8957 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008958 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8959 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008960 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008961 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8962 // This is not safe in general for floating point:
8963 // consider X== -0, Y== +0.
8964 // It becomes safe if either operand is a nonzero constant.
8965 ConstantFP *CFPt, *CFPf;
8966 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8967 !CFPt->getValueAPF().isZero()) ||
8968 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8969 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008970 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008971 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008972 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008973 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008974 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008975 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00008976
Reid Spencere4d87aa2006-12-23 06:05:41 +00008977 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008978 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008979 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8980 // This is not safe in general for floating point:
8981 // consider X== -0, Y== +0.
8982 // It becomes safe if either operand is a nonzero constant.
8983 ConstantFP *CFPt, *CFPf;
8984 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8985 !CFPt->getValueAPF().isZero()) ||
8986 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8987 !CFPf->getValueAPF().isZero()))
8988 return ReplaceInstUsesWith(SI, FalseVal);
8989 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008990 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008991 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8992 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00008993 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00008994 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00008995 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00008996 }
8997
8998 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00008999 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9000 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9001 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009002
Chris Lattner87875da2005-01-13 22:52:24 +00009003 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9004 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9005 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009006 Instruction *AddOp = 0, *SubOp = 0;
9007
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009008 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9009 if (TI->getOpcode() == FI->getOpcode())
9010 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9011 return IV;
9012
9013 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9014 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00009015 if (TI->getOpcode() == Instruction::Sub &&
9016 FI->getOpcode() == Instruction::Add) {
9017 AddOp = FI; SubOp = TI;
9018 } else if (FI->getOpcode() == Instruction::Sub &&
9019 TI->getOpcode() == Instruction::Add) {
9020 AddOp = TI; SubOp = FI;
9021 }
9022
9023 if (AddOp) {
9024 Value *OtherAddOp = 0;
9025 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9026 OtherAddOp = AddOp->getOperand(1);
9027 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9028 OtherAddOp = AddOp->getOperand(0);
9029 }
9030
9031 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009032 // So at this point we know we have (Y -> OtherAddOp):
9033 // select C, (add X, Y), (sub X, Z)
9034 Value *NegVal; // Compute -Z
9035 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9036 NegVal = ConstantExpr::getNeg(C);
9037 } else {
9038 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009039 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009040 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009041
9042 Value *NewTrueOp = OtherAddOp;
9043 Value *NewFalseOp = NegVal;
9044 if (AddOp != TI)
9045 std::swap(NewTrueOp, NewFalseOp);
9046 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009047 SelectInst::Create(CondVal, NewTrueOp,
9048 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009049
9050 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009051 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009052 }
9053 }
9054 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009055
Chris Lattnere576b912004-04-09 23:46:01 +00009056 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009057 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00009058 // See the comment above GetSelectFoldableOperands for a description of the
9059 // transformation we are doing here.
9060 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9061 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9062 !isa<Constant>(FalseVal))
9063 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9064 unsigned OpToFold = 0;
9065 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9066 OpToFold = 1;
9067 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9068 OpToFold = 2;
9069 }
9070
9071 if (OpToFold) {
9072 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009073 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009074 SelectInst::Create(SI.getCondition(),
9075 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00009076 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009077 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009079 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00009080 else {
9081 assert(0 && "Unknown instruction!!");
9082 }
9083 }
9084 }
Chris Lattnera96879a2004-09-29 17:40:11 +00009085
Chris Lattnere576b912004-04-09 23:46:01 +00009086 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9087 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9088 !isa<Constant>(TrueVal))
9089 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9090 unsigned OpToFold = 0;
9091 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9092 OpToFold = 1;
9093 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9094 OpToFold = 2;
9095 }
9096
9097 if (OpToFold) {
9098 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009099 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009100 SelectInst::Create(SI.getCondition(), C,
9101 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00009102 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009103 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009105 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00009106 else
Chris Lattnere576b912004-04-09 23:46:01 +00009107 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00009108 }
9109 }
9110 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009111
9112 if (BinaryOperator::isNot(CondVal)) {
9113 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9114 SI.setOperand(1, FalseVal);
9115 SI.setOperand(2, TrueVal);
9116 return &SI;
9117 }
9118
Chris Lattner3d69f462004-03-12 05:52:32 +00009119 return 0;
9120}
9121
Dan Gohmaneee962e2008-04-10 18:43:06 +00009122/// EnforceKnownAlignment - If the specified pointer points to an object that
9123/// we control, modify the object's alignment to PrefAlign. This isn't
9124/// often possible though. If alignment is important, a more reliable approach
9125/// is to simply align all global variables and allocation instructions to
9126/// their preferred alignment from the beginning.
9127///
9128static unsigned EnforceKnownAlignment(Value *V,
9129 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009130
Dan Gohmaneee962e2008-04-10 18:43:06 +00009131 User *U = dyn_cast<User>(V);
9132 if (!U) return Align;
9133
9134 switch (getOpcode(U)) {
9135 default: break;
9136 case Instruction::BitCast:
9137 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9138 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009139 // If all indexes are zero, it is just the alignment of the base pointer.
9140 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009141 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009142 if (!isa<Constant>(*i) ||
9143 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009144 AllZeroOperands = false;
9145 break;
9146 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009147
9148 if (AllZeroOperands) {
9149 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009150 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009151 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009152 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009153 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009154 }
9155
9156 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9157 // If there is a large requested alignment and we can, bump up the alignment
9158 // of the global.
9159 if (!GV->isDeclaration()) {
9160 GV->setAlignment(PrefAlign);
9161 Align = PrefAlign;
9162 }
9163 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9164 // If there is a requested alignment and if this is an alloca, round up. We
9165 // don't do this for malloc, because some systems can't respect the request.
9166 if (isa<AllocaInst>(AI)) {
9167 AI->setAlignment(PrefAlign);
9168 Align = PrefAlign;
9169 }
9170 }
9171
9172 return Align;
9173}
9174
9175/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9176/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9177/// and it is more than the alignment of the ultimate object, see if we can
9178/// increase the alignment of the ultimate object, making this check succeed.
9179unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9180 unsigned PrefAlign) {
9181 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9182 sizeof(PrefAlign) * CHAR_BIT;
9183 APInt Mask = APInt::getAllOnesValue(BitWidth);
9184 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9185 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9186 unsigned TrailZ = KnownZero.countTrailingOnes();
9187 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9188
9189 if (PrefAlign > Align)
9190 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9191
9192 // We don't need to make any adjustment.
9193 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009194}
9195
Chris Lattnerf497b022008-01-13 23:50:23 +00009196Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009197 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9198 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009199 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9200 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9201
9202 if (CopyAlign < MinAlign) {
9203 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9204 return MI;
9205 }
9206
9207 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9208 // load/store.
9209 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9210 if (MemOpLength == 0) return 0;
9211
Chris Lattner37ac6082008-01-14 00:28:35 +00009212 // Source and destination pointer types are always "i8*" for intrinsic. See
9213 // if the size is something we can handle with a single primitive load/store.
9214 // A single load+store correctly handles overlapping memory in the memmove
9215 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009216 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009217 if (Size == 0) return MI; // Delete this mem transfer.
9218
9219 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009220 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009221
Chris Lattner37ac6082008-01-14 00:28:35 +00009222 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009223 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009224
9225 // Memcpy forces the use of i8* for the source and destination. That means
9226 // that if you're using memcpy to move one double around, you'll get a cast
9227 // from double* to i8*. We'd much rather use a double load+store rather than
9228 // an i64 load+store, here because this improves the odds that the source or
9229 // dest address will be promotable. See if we can find a better type than the
9230 // integer datatype.
9231 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9232 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9233 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9234 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9235 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009236 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009237 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9238 if (STy->getNumElements() == 1)
9239 SrcETy = STy->getElementType(0);
9240 else
9241 break;
9242 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9243 if (ATy->getNumElements() == 1)
9244 SrcETy = ATy->getElementType();
9245 else
9246 break;
9247 } else
9248 break;
9249 }
9250
Dan Gohman8f8e2692008-05-23 01:52:21 +00009251 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009252 NewPtrTy = PointerType::getUnqual(SrcETy);
9253 }
9254 }
9255
9256
Chris Lattnerf497b022008-01-13 23:50:23 +00009257 // If the memcpy/memmove provides better alignment info than we can
9258 // infer, use it.
9259 SrcAlign = std::max(SrcAlign, CopyAlign);
9260 DstAlign = std::max(DstAlign, CopyAlign);
9261
9262 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9263 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009264 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9265 InsertNewInstBefore(L, *MI);
9266 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9267
9268 // Set the size of the copy to 0, it will be deleted on the next iteration.
9269 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9270 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009271}
Chris Lattner3d69f462004-03-12 05:52:32 +00009272
Chris Lattner69ea9d22008-04-30 06:39:11 +00009273Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9274 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9275 if (MI->getAlignment()->getZExtValue() < Alignment) {
9276 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9277 return MI;
9278 }
9279
9280 // Extract the length and alignment and fill if they are constant.
9281 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9282 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9283 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9284 return 0;
9285 uint64_t Len = LenC->getZExtValue();
9286 Alignment = MI->getAlignment()->getZExtValue();
9287
9288 // If the length is zero, this is a no-op
9289 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9290
9291 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9292 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9293 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9294
9295 Value *Dest = MI->getDest();
9296 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9297
9298 // Alignment 0 is identity for alignment 1 for memset, but not store.
9299 if (Alignment == 0) Alignment = 1;
9300
9301 // Extract the fill value and store.
9302 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9303 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9304 Alignment), *MI);
9305
9306 // Set the size of the copy to 0, it will be deleted on the next iteration.
9307 MI->setLength(Constant::getNullValue(LenC->getType()));
9308 return MI;
9309 }
9310
9311 return 0;
9312}
9313
9314
Chris Lattner8b0ea312006-01-13 20:11:04 +00009315/// visitCallInst - CallInst simplification. This mostly only handles folding
9316/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9317/// the heavy lifting.
9318///
Chris Lattner9fe38862003-06-19 17:00:31 +00009319Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009320 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9321 if (!II) return visitCallSite(&CI);
9322
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009323 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9324 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009325 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009326 bool Changed = false;
9327
9328 // memmove/cpy/set of zero bytes is a noop.
9329 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9330 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9331
Chris Lattner35b9e482004-10-12 04:52:52 +00009332 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009333 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009334 // Replace the instruction with just byte operations. We would
9335 // transform other cases to loads/stores, but we don't know if
9336 // alignment is sufficient.
9337 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009338 }
9339
Chris Lattner35b9e482004-10-12 04:52:52 +00009340 // If we have a memmove and the source operation is a constant global,
9341 // then the source and dest pointers can't alias, so we can change this
9342 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009343 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009344 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9345 if (GVSrc->isConstant()) {
9346 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009347 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9348 const Type *Tys[1];
9349 Tys[0] = CI.getOperand(3)->getType();
9350 CI.setOperand(0,
9351 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009352 Changed = true;
9353 }
Chris Lattnera935db82008-05-28 05:30:41 +00009354
9355 // memmove(x,x,size) -> noop.
9356 if (MMI->getSource() == MMI->getDest())
9357 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009358 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009359
Chris Lattner95a959d2006-03-06 20:18:44 +00009360 // If we can determine a pointer alignment that is bigger than currently
9361 // set, update the alignment.
9362 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009363 if (Instruction *I = SimplifyMemTransfer(MI))
9364 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009365 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9366 if (Instruction *I = SimplifyMemSet(MSI))
9367 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009368 }
9369
Chris Lattner8b0ea312006-01-13 20:11:04 +00009370 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009371 }
9372
9373 switch (II->getIntrinsicID()) {
9374 default: break;
9375 case Intrinsic::bswap:
9376 // bswap(bswap(x)) -> x
9377 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9378 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9379 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9380 break;
9381 case Intrinsic::ppc_altivec_lvx:
9382 case Intrinsic::ppc_altivec_lvxl:
9383 case Intrinsic::x86_sse_loadu_ps:
9384 case Intrinsic::x86_sse2_loadu_pd:
9385 case Intrinsic::x86_sse2_loadu_dq:
9386 // Turn PPC lvx -> load if the pointer is known aligned.
9387 // Turn X86 loadups -> load if the pointer is known aligned.
9388 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9389 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9390 PointerType::getUnqual(II->getType()),
9391 CI);
9392 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009393 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009394 break;
9395 case Intrinsic::ppc_altivec_stvx:
9396 case Intrinsic::ppc_altivec_stvxl:
9397 // Turn stvx -> store if the pointer is known aligned.
9398 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9399 const Type *OpPtrTy =
9400 PointerType::getUnqual(II->getOperand(1)->getType());
9401 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9402 return new StoreInst(II->getOperand(1), Ptr);
9403 }
9404 break;
9405 case Intrinsic::x86_sse_storeu_ps:
9406 case Intrinsic::x86_sse2_storeu_pd:
9407 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009408 // Turn X86 storeu -> store if the pointer is known aligned.
9409 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9410 const Type *OpPtrTy =
9411 PointerType::getUnqual(II->getOperand(2)->getType());
9412 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9413 return new StoreInst(II->getOperand(2), Ptr);
9414 }
9415 break;
9416
9417 case Intrinsic::x86_sse_cvttss2si: {
9418 // These intrinsics only demands the 0th element of its input vector. If
9419 // we can simplify the input based on that, do so now.
9420 uint64_t UndefElts;
9421 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9422 UndefElts)) {
9423 II->setOperand(1, V);
9424 return II;
9425 }
9426 break;
9427 }
9428
9429 case Intrinsic::ppc_altivec_vperm:
9430 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9431 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9432 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009433
Chris Lattner0521e3c2008-06-18 04:33:20 +00009434 // Check that all of the elements are integer constants or undefs.
9435 bool AllEltsOk = true;
9436 for (unsigned i = 0; i != 16; ++i) {
9437 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9438 !isa<UndefValue>(Mask->getOperand(i))) {
9439 AllEltsOk = false;
9440 break;
9441 }
9442 }
9443
9444 if (AllEltsOk) {
9445 // Cast the input vectors to byte vectors.
9446 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9447 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9448 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009449
Chris Lattner0521e3c2008-06-18 04:33:20 +00009450 // Only extract each element once.
9451 Value *ExtractedElts[32];
9452 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9453
Chris Lattnere2ed0572006-04-06 19:19:17 +00009454 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009455 if (isa<UndefValue>(Mask->getOperand(i)))
9456 continue;
9457 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9458 Idx &= 31; // Match the hardware behavior.
9459
9460 if (ExtractedElts[Idx] == 0) {
9461 Instruction *Elt =
9462 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9463 InsertNewInstBefore(Elt, CI);
9464 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009465 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009466
Chris Lattner0521e3c2008-06-18 04:33:20 +00009467 // Insert this value into the result vector.
9468 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9469 i, "tmp");
9470 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009471 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009472 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009473 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009474 }
9475 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009476
Chris Lattner0521e3c2008-06-18 04:33:20 +00009477 case Intrinsic::stackrestore: {
9478 // If the save is right next to the restore, remove the restore. This can
9479 // happen when variable allocas are DCE'd.
9480 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9481 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9482 BasicBlock::iterator BI = SS;
9483 if (&*++BI == II)
9484 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009485 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009486 }
9487
9488 // Scan down this block to see if there is another stack restore in the
9489 // same block without an intervening call/alloca.
9490 BasicBlock::iterator BI = II;
9491 TerminatorInst *TI = II->getParent()->getTerminator();
9492 bool CannotRemove = false;
9493 for (++BI; &*BI != TI; ++BI) {
9494 if (isa<AllocaInst>(BI)) {
9495 CannotRemove = true;
9496 break;
9497 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009498 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9499 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9500 // If there is a stackrestore below this one, remove this one.
9501 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9502 return EraseInstFromFunction(CI);
9503 // Otherwise, ignore the intrinsic.
9504 } else {
9505 // If we found a non-intrinsic call, we can't remove the stack
9506 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009507 CannotRemove = true;
9508 break;
9509 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009510 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009511 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009512
9513 // If the stack restore is in a return/unwind block and if there are no
9514 // allocas or calls between the restore and the return, nuke the restore.
9515 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9516 return EraseInstFromFunction(CI);
9517 break;
9518 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009519 }
9520
Chris Lattner8b0ea312006-01-13 20:11:04 +00009521 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009522}
9523
9524// InvokeInst simplification
9525//
9526Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009527 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009528}
9529
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009530/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9531/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009532static bool isSafeToEliminateVarargsCast(const CallSite CS,
9533 const CastInst * const CI,
9534 const TargetData * const TD,
9535 const int ix) {
9536 if (!CI->isLosslessCast())
9537 return false;
9538
9539 // The size of ByVal arguments is derived from the type, so we
9540 // can't change to a type with a different size. If the size were
9541 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009542 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009543 return true;
9544
9545 const Type* SrcTy =
9546 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9547 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9548 if (!SrcTy->isSized() || !DstTy->isSized())
9549 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009550 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009551 return false;
9552 return true;
9553}
9554
Chris Lattnera44d8a22003-10-07 22:32:43 +00009555// visitCallSite - Improvements for call and invoke instructions.
9556//
9557Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009558 bool Changed = false;
9559
9560 // If the callee is a constexpr cast of a function, attempt to move the cast
9561 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009562 if (transformConstExprCastCall(CS)) return 0;
9563
Chris Lattner6c266db2003-10-07 22:54:13 +00009564 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009565
Chris Lattner08b22ec2005-05-13 07:09:09 +00009566 if (Function *CalleeF = dyn_cast<Function>(Callee))
9567 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9568 Instruction *OldCall = CS.getInstruction();
9569 // If the call and callee calling conventions don't match, this call must
9570 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009571 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009572 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9573 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009574 if (!OldCall->use_empty())
9575 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9576 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9577 return EraseInstFromFunction(*OldCall);
9578 return 0;
9579 }
9580
Chris Lattner17be6352004-10-18 02:59:09 +00009581 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9582 // This instruction is not reachable, just remove it. We insert a store to
9583 // undef so that we know that this code is not reachable, despite the fact
9584 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009585 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009586 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009587 CS.getInstruction());
9588
9589 if (!CS.getInstruction()->use_empty())
9590 CS.getInstruction()->
9591 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9592
9593 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9594 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009595 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9596 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009597 }
Chris Lattner17be6352004-10-18 02:59:09 +00009598 return EraseInstFromFunction(*CS.getInstruction());
9599 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009600
Duncan Sandscdb6d922007-09-17 10:26:40 +00009601 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9602 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9603 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9604 return transformCallThroughTrampoline(CS);
9605
Chris Lattner6c266db2003-10-07 22:54:13 +00009606 const PointerType *PTy = cast<PointerType>(Callee->getType());
9607 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9608 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009609 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009610 // See if we can optimize any arguments passed through the varargs area of
9611 // the call.
9612 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009613 E = CS.arg_end(); I != E; ++I, ++ix) {
9614 CastInst *CI = dyn_cast<CastInst>(*I);
9615 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9616 *I = CI->getOperand(0);
9617 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009618 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009619 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009620 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009621
Duncan Sandsf0c33542007-12-19 21:13:37 +00009622 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009623 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009624 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009625 Changed = true;
9626 }
9627
Chris Lattner6c266db2003-10-07 22:54:13 +00009628 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009629}
9630
Chris Lattner9fe38862003-06-19 17:00:31 +00009631// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9632// attempt to move the cast to the arguments of the call/invoke.
9633//
9634bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9635 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9636 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009637 if (CE->getOpcode() != Instruction::BitCast ||
9638 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009639 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009640 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009641 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009642 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009643
9644 // Okay, this is a cast from a function to a different type. Unless doing so
9645 // would cause a type conversion of one of our arguments, change this call to
9646 // be a direct call with arguments casted to the appropriate types.
9647 //
9648 const FunctionType *FT = Callee->getFunctionType();
9649 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009650 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009651
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009652 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009653 return false; // TODO: Handle multiple return values.
9654
Chris Lattnerf78616b2004-01-14 06:06:08 +00009655 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009656 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009657 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009658 // Conversion is ok if changing from one pointer type to another or from
9659 // a pointer to an integer of the same size.
9660 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009661 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009662 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009663
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009664 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009665 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009666 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009667 return false; // Cannot transform this return value.
9668
Chris Lattner58d74912008-03-12 17:45:29 +00009669 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009670 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009671 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009672 return false; // Attribute not compatible with transformed value.
9673 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009674
Chris Lattnerf78616b2004-01-14 06:06:08 +00009675 // If the callsite is an invoke instruction, and the return value is used by
9676 // a PHI node in a successor, we cannot change the return type of the call
9677 // because there is no place to put the cast instruction (without breaking
9678 // the critical edge). Bail out in this case.
9679 if (!Caller->use_empty())
9680 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9681 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9682 UI != E; ++UI)
9683 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9684 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009685 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009686 return false;
9687 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009688
9689 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9690 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009691
Chris Lattner9fe38862003-06-19 17:00:31 +00009692 CallSite::arg_iterator AI = CS.arg_begin();
9693 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9694 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009695 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009696
9697 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009698 return false; // Cannot transform this parameter value.
9699
Devang Patel19c87462008-09-26 22:53:05 +00009700 if (CallerPAL.getParamAttributes(i + 1)
9701 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009702 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009703
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009704 // Converting from one pointer type to another or between a pointer and an
9705 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009706 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009707 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9708 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009709 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009710 }
9711
9712 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009713 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009714 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009715
Chris Lattner58d74912008-03-12 17:45:29 +00009716 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9717 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009718 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009719 // won't be dropping them. Check that these extra arguments have attributes
9720 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009721 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9722 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009723 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009724 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009725 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009726 return false;
9727 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009728
Chris Lattner9fe38862003-06-19 17:00:31 +00009729 // Okay, we decided that this is a safe thing to do: go ahead and start
9730 // inserting cast instructions as necessary...
9731 std::vector<Value*> Args;
9732 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009733 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009734 attrVec.reserve(NumCommonArgs);
9735
9736 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009737 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009738
9739 // If the return value is not being used, the type may not be compatible
9740 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009741 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009742
9743 // Add the new return attributes.
9744 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009745 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009746
9747 AI = CS.arg_begin();
9748 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9749 const Type *ParamTy = FT->getParamType(i);
9750 if ((*AI)->getType() == ParamTy) {
9751 Args.push_back(*AI);
9752 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009753 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009754 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009755 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009756 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009757 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009758
9759 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009760 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009761 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009762 }
9763
9764 // If the function takes more arguments than the call was taking, add them
9765 // now...
9766 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9767 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9768
9769 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009770 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009771 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009772 cerr << "WARNING: While resolving call to function '"
9773 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009774 } else {
9775 // Add all of the arguments in their promoted form to the arg list...
9776 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9777 const Type *PTy = getPromotedType((*AI)->getType());
9778 if (PTy != (*AI)->getType()) {
9779 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009780 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9781 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009782 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009783 InsertNewInstBefore(Cast, *Caller);
9784 Args.push_back(Cast);
9785 } else {
9786 Args.push_back(*AI);
9787 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009788
Duncan Sandse1e520f2008-01-13 08:02:44 +00009789 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009790 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009791 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009792 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009793 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009794 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009795
Devang Patel19c87462008-09-26 22:53:05 +00009796 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9797 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9798
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009799 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009800 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009801
Devang Patel05988662008-09-25 21:00:45 +00009802 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009803
Chris Lattner9fe38862003-06-19 17:00:31 +00009804 Instruction *NC;
9805 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009806 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009807 Args.begin(), Args.end(),
9808 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009809 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009810 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009811 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009812 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9813 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009814 CallInst *CI = cast<CallInst>(Caller);
9815 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009816 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009817 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009818 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009819 }
9820
Chris Lattner6934a042007-02-11 01:23:03 +00009821 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009822 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009823 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009824 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009825 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009826 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009827 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009828
9829 // If this is an invoke instruction, we should insert it after the first
9830 // non-phi, instruction in the normal successor block.
9831 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009832 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009833 InsertNewInstBefore(NC, *I);
9834 } else {
9835 // Otherwise, it's a call, just insert cast right after the call instr
9836 InsertNewInstBefore(NC, *Caller);
9837 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009838 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009839 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009840 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009841 }
9842 }
9843
9844 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9845 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009846 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009847 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009848 return true;
9849}
9850
Duncan Sandscdb6d922007-09-17 10:26:40 +00009851// transformCallThroughTrampoline - Turn a call to a function created by the
9852// init_trampoline intrinsic into a direct call to the underlying function.
9853//
9854Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9855 Value *Callee = CS.getCalledValue();
9856 const PointerType *PTy = cast<PointerType>(Callee->getType());
9857 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009858 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009859
9860 // If the call already has the 'nest' attribute somewhere then give up -
9861 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009862 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009863 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009864
9865 IntrinsicInst *Tramp =
9866 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9867
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009868 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009869 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9870 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9871
Devang Patel05988662008-09-25 21:00:45 +00009872 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009873 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009874 unsigned NestIdx = 1;
9875 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009876 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009877
9878 // Look for a parameter marked with the 'nest' attribute.
9879 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9880 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00009881 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009882 // Record the parameter type and any other attributes.
9883 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00009884 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009885 break;
9886 }
9887
9888 if (NestTy) {
9889 Instruction *Caller = CS.getInstruction();
9890 std::vector<Value*> NewArgs;
9891 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9892
Devang Patel05988662008-09-25 21:00:45 +00009893 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00009894 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009895
Duncan Sandscdb6d922007-09-17 10:26:40 +00009896 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009897 // mean appending it. Likewise for attributes.
9898
Devang Patel19c87462008-09-26 22:53:05 +00009899 // Add any result attributes.
9900 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00009901 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009902
Duncan Sandscdb6d922007-09-17 10:26:40 +00009903 {
9904 unsigned Idx = 1;
9905 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9906 do {
9907 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009908 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009909 Value *NestVal = Tramp->getOperand(3);
9910 if (NestVal->getType() != NestTy)
9911 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9912 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00009913 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009914 }
9915
9916 if (I == E)
9917 break;
9918
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009919 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009920 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +00009921 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009922 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +00009923 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009924
9925 ++Idx, ++I;
9926 } while (1);
9927 }
9928
Devang Patel19c87462008-09-26 22:53:05 +00009929 // Add any function attributes.
9930 if (Attributes Attr = Attrs.getFnAttributes())
9931 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9932
Duncan Sandscdb6d922007-09-17 10:26:40 +00009933 // The trampoline may have been bitcast to a bogus type (FTy).
9934 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009935 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009936
Duncan Sandscdb6d922007-09-17 10:26:40 +00009937 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009938 NewTypes.reserve(FTy->getNumParams()+1);
9939
Duncan Sandscdb6d922007-09-17 10:26:40 +00009940 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009941 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009942 {
9943 unsigned Idx = 1;
9944 FunctionType::param_iterator I = FTy->param_begin(),
9945 E = FTy->param_end();
9946
9947 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009948 if (Idx == NestIdx)
9949 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009950 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009951
9952 if (I == E)
9953 break;
9954
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009955 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009956 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009957
9958 ++Idx, ++I;
9959 } while (1);
9960 }
9961
9962 // Replace the trampoline call with a direct call. Let the generic
9963 // code sort out any function type mismatches.
9964 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009965 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009966 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9967 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +00009968 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009969
9970 Instruction *NewCaller;
9971 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009972 NewCaller = InvokeInst::Create(NewCallee,
9973 II->getNormalDest(), II->getUnwindDest(),
9974 NewArgs.begin(), NewArgs.end(),
9975 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009976 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009977 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009978 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009979 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9980 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009981 if (cast<CallInst>(Caller)->isTailCall())
9982 cast<CallInst>(NewCaller)->setTailCall();
9983 cast<CallInst>(NewCaller)->
9984 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009985 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009986 }
9987 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9988 Caller->replaceAllUsesWith(NewCaller);
9989 Caller->eraseFromParent();
9990 RemoveFromWorkList(Caller);
9991 return 0;
9992 }
9993 }
9994
9995 // Replace the trampoline call with a direct call. Since there is no 'nest'
9996 // parameter, there is no need to adjust the argument list. Let the generic
9997 // code sort out any function type mismatches.
9998 Constant *NewCallee =
9999 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10000 CS.setCalledFunction(NewCallee);
10001 return CS.getInstruction();
10002}
10003
Chris Lattner7da52b22006-11-01 04:51:18 +000010004/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10005/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10006/// and a single binop.
10007Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10008 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010009 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010010 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010011 Value *LHSVal = FirstInst->getOperand(0);
10012 Value *RHSVal = FirstInst->getOperand(1);
10013
10014 const Type *LHSType = LHSVal->getType();
10015 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010016
10017 // Scan to see if all operands are the same opcode, all have one use, and all
10018 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010019 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010020 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010021 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010022 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010023 // types or GEP's with different index types.
10024 I->getOperand(0)->getType() != LHSType ||
10025 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010026 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010027
10028 // If they are CmpInst instructions, check their predicates
10029 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10030 if (cast<CmpInst>(I)->getPredicate() !=
10031 cast<CmpInst>(FirstInst)->getPredicate())
10032 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010033
10034 // Keep track of which operand needs a phi node.
10035 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10036 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010037 }
10038
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010039 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010040
Chris Lattner7da52b22006-11-01 04:51:18 +000010041 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010042 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010043 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010044 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010045 NewLHS = PHINode::Create(LHSType,
10046 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010047 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10048 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010049 InsertNewInstBefore(NewLHS, PN);
10050 LHSVal = NewLHS;
10051 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010052
10053 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010054 NewRHS = PHINode::Create(RHSType,
10055 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010056 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10057 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010058 InsertNewInstBefore(NewRHS, PN);
10059 RHSVal = NewRHS;
10060 }
10061
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010062 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010063 if (NewLHS || NewRHS) {
10064 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10065 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10066 if (NewLHS) {
10067 Value *NewInLHS = InInst->getOperand(0);
10068 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10069 }
10070 if (NewRHS) {
10071 Value *NewInRHS = InInst->getOperand(1);
10072 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10073 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010074 }
10075 }
10076
Chris Lattner7da52b22006-11-01 04:51:18 +000010077 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010078 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010079 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10080 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10081 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010082}
10083
Chris Lattner05f18922008-12-01 02:34:36 +000010084Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10085 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10086
10087 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10088 FirstInst->op_end());
10089
10090 // Scan to see if all operands are the same opcode, all have one use, and all
10091 // kill their operands (i.e. the operands have one use).
10092 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10093 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10094 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10095 GEP->getNumOperands() != FirstInst->getNumOperands())
10096 return 0;
10097
10098 // Compare the operand lists.
10099 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10100 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10101 continue;
10102
10103 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10104 // if one of the PHIs has a constant for the index. The index may be
10105 // substantially cheaper to compute for the constants, so making it a
10106 // variable index could pessimize the path. This also handles the case
10107 // for struct indices, which must always be constant.
10108 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10109 isa<ConstantInt>(GEP->getOperand(op)))
10110 return 0;
10111
10112 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10113 return 0;
10114 FixedOperands[op] = 0; // Needs a PHI.
10115 }
10116 }
10117
10118 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10119 // that is variable.
10120 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10121
10122 bool HasAnyPHIs = false;
10123 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10124 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10125 Value *FirstOp = FirstInst->getOperand(i);
10126 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10127 FirstOp->getName()+".pn");
10128 InsertNewInstBefore(NewPN, PN);
10129
10130 NewPN->reserveOperandSpace(e);
10131 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10132 OperandPhis[i] = NewPN;
10133 FixedOperands[i] = NewPN;
10134 HasAnyPHIs = true;
10135 }
10136
10137
10138 // Add all operands to the new PHIs.
10139 if (HasAnyPHIs) {
10140 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10141 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10142 BasicBlock *InBB = PN.getIncomingBlock(i);
10143
10144 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10145 if (PHINode *OpPhi = OperandPhis[op])
10146 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10147 }
10148 }
10149
10150 Value *Base = FixedOperands[0];
10151 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10152 FixedOperands.end());
10153}
10154
10155
Chris Lattner76c73142006-11-01 07:13:54 +000010156/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10157/// of the block that defines it. This means that it must be obvious the value
10158/// of the load is not changed from the point of the load to the end of the
10159/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010160///
10161/// Finally, it is safe, but not profitable, to sink a load targetting a
10162/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10163/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +000010164static bool isSafeToSinkLoad(LoadInst *L) {
10165 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10166
10167 for (++BBI; BBI != E; ++BBI)
10168 if (BBI->mayWriteToMemory())
10169 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010170
10171 // Check for non-address taken alloca. If not address-taken already, it isn't
10172 // profitable to do this xform.
10173 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10174 bool isAddressTaken = false;
10175 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10176 UI != E; ++UI) {
10177 if (isa<LoadInst>(UI)) continue;
10178 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10179 // If storing TO the alloca, then the address isn't taken.
10180 if (SI->getOperand(1) == AI) continue;
10181 }
10182 isAddressTaken = true;
10183 break;
10184 }
10185
10186 if (!isAddressTaken)
10187 return false;
10188 }
10189
Chris Lattner76c73142006-11-01 07:13:54 +000010190 return true;
10191}
10192
Chris Lattner9fe38862003-06-19 17:00:31 +000010193
Chris Lattnerbac32862004-11-14 19:13:23 +000010194// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10195// operator and they all are only used by the PHI, PHI together their
10196// inputs, and do the operation once, to the result of the PHI.
10197Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10198 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10199
10200 // Scan the instruction, looking for input operations that can be folded away.
10201 // If all input operands to the phi are the same instruction (e.g. a cast from
10202 // the same type or "+42") we can pull the operation through the PHI, reducing
10203 // code size and simplifying code.
10204 Constant *ConstantOp = 0;
10205 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010206 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010207 if (isa<CastInst>(FirstInst)) {
10208 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010209 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010210 // Can fold binop, compare or shift here if the RHS is a constant,
10211 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010212 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010213 if (ConstantOp == 0)
10214 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010215 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10216 isVolatile = LI->isVolatile();
10217 // We can't sink the load if the loaded value could be modified between the
10218 // load and the PHI.
10219 if (LI->getParent() != PN.getIncomingBlock(0) ||
10220 !isSafeToSinkLoad(LI))
10221 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010222
10223 // If the PHI is of volatile loads and the load block has multiple
10224 // successors, sinking it would remove a load of the volatile value from
10225 // the path through the other successor.
10226 if (isVolatile &&
10227 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10228 return 0;
10229
Chris Lattner9c080502006-11-01 07:43:41 +000010230 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010231 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010232 } else {
10233 return 0; // Cannot fold this operation.
10234 }
10235
10236 // Check to see if all arguments are the same operation.
10237 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10238 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10239 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010240 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010241 return 0;
10242 if (CastSrcTy) {
10243 if (I->getOperand(0)->getType() != CastSrcTy)
10244 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010245 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010246 // We can't sink the load if the loaded value could be modified between
10247 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010248 if (LI->isVolatile() != isVolatile ||
10249 LI->getParent() != PN.getIncomingBlock(i) ||
10250 !isSafeToSinkLoad(LI))
10251 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010252
Chris Lattner71042962008-07-08 17:18:32 +000010253 // If the PHI is of volatile loads and the load block has multiple
10254 // successors, sinking it would remove a load of the volatile value from
10255 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010256 if (isVolatile &&
10257 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10258 return 0;
10259
10260
Chris Lattnerbac32862004-11-14 19:13:23 +000010261 } else if (I->getOperand(1) != ConstantOp) {
10262 return 0;
10263 }
10264 }
10265
10266 // Okay, they are all the same operation. Create a new PHI node of the
10267 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010268 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10269 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010270 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010271
10272 Value *InVal = FirstInst->getOperand(0);
10273 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010274
10275 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010276 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10277 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10278 if (NewInVal != InVal)
10279 InVal = 0;
10280 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10281 }
10282
10283 Value *PhiVal;
10284 if (InVal) {
10285 // The new PHI unions all of the same values together. This is really
10286 // common, so we handle it intelligently here for compile-time speed.
10287 PhiVal = InVal;
10288 delete NewPN;
10289 } else {
10290 InsertNewInstBefore(NewPN, PN);
10291 PhiVal = NewPN;
10292 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010293
Chris Lattnerbac32862004-11-14 19:13:23 +000010294 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010295 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010296 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010297 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010298 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010299 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010300 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010301 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010302 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10303
10304 // If this was a volatile load that we are merging, make sure to loop through
10305 // and mark all the input loads as non-volatile. If we don't do this, we will
10306 // insert a new volatile load and the old ones will not be deletable.
10307 if (isVolatile)
10308 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10309 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10310
10311 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010312}
Chris Lattnera1be5662002-05-02 17:06:02 +000010313
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010314/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10315/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010316static bool DeadPHICycle(PHINode *PN,
10317 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010318 if (PN->use_empty()) return true;
10319 if (!PN->hasOneUse()) return false;
10320
10321 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010322 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010323 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010324
10325 // Don't scan crazily complex things.
10326 if (PotentiallyDeadPHIs.size() == 16)
10327 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010328
10329 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10330 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010331
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010332 return false;
10333}
10334
Chris Lattnercf5008a2007-11-06 21:52:06 +000010335/// PHIsEqualValue - Return true if this phi node is always equal to
10336/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10337/// z = some value; x = phi (y, z); y = phi (x, z)
10338static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10339 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10340 // See if we already saw this PHI node.
10341 if (!ValueEqualPHIs.insert(PN))
10342 return true;
10343
10344 // Don't scan crazily complex things.
10345 if (ValueEqualPHIs.size() == 16)
10346 return false;
10347
10348 // Scan the operands to see if they are either phi nodes or are equal to
10349 // the value.
10350 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10351 Value *Op = PN->getIncomingValue(i);
10352 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10353 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10354 return false;
10355 } else if (Op != NonPhiInVal)
10356 return false;
10357 }
10358
10359 return true;
10360}
10361
10362
Chris Lattner473945d2002-05-06 18:06:38 +000010363// PHINode simplification
10364//
Chris Lattner7e708292002-06-25 16:13:24 +000010365Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010366 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010367 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010368
Owen Anderson7e057142006-07-10 22:03:18 +000010369 if (Value *V = PN.hasConstantValue())
10370 return ReplaceInstUsesWith(PN, V);
10371
Owen Anderson7e057142006-07-10 22:03:18 +000010372 // If all PHI operands are the same operation, pull them through the PHI,
10373 // reducing code size.
10374 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010375 isa<Instruction>(PN.getIncomingValue(1)) &&
10376 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10377 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10378 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10379 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010380 PN.getIncomingValue(0)->hasOneUse())
10381 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10382 return Result;
10383
10384 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10385 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10386 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010387 if (PN.hasOneUse()) {
10388 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10389 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010390 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010391 PotentiallyDeadPHIs.insert(&PN);
10392 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10393 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10394 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010395
10396 // If this phi has a single use, and if that use just computes a value for
10397 // the next iteration of a loop, delete the phi. This occurs with unused
10398 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10399 // common case here is good because the only other things that catch this
10400 // are induction variable analysis (sometimes) and ADCE, which is only run
10401 // late.
10402 if (PHIUser->hasOneUse() &&
10403 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10404 PHIUser->use_back() == &PN) {
10405 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10406 }
10407 }
Owen Anderson7e057142006-07-10 22:03:18 +000010408
Chris Lattnercf5008a2007-11-06 21:52:06 +000010409 // We sometimes end up with phi cycles that non-obviously end up being the
10410 // same value, for example:
10411 // z = some value; x = phi (y, z); y = phi (x, z)
10412 // where the phi nodes don't necessarily need to be in the same block. Do a
10413 // quick check to see if the PHI node only contains a single non-phi value, if
10414 // so, scan to see if the phi cycle is actually equal to that value.
10415 {
10416 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10417 // Scan for the first non-phi operand.
10418 while (InValNo != NumOperandVals &&
10419 isa<PHINode>(PN.getIncomingValue(InValNo)))
10420 ++InValNo;
10421
10422 if (InValNo != NumOperandVals) {
10423 Value *NonPhiInVal = PN.getOperand(InValNo);
10424
10425 // Scan the rest of the operands to see if there are any conflicts, if so
10426 // there is no need to recursively scan other phis.
10427 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10428 Value *OpVal = PN.getIncomingValue(InValNo);
10429 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10430 break;
10431 }
10432
10433 // If we scanned over all operands, then we have one unique value plus
10434 // phi values. Scan PHI nodes to see if they all merge in each other or
10435 // the value.
10436 if (InValNo == NumOperandVals) {
10437 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10438 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10439 return ReplaceInstUsesWith(PN, NonPhiInVal);
10440 }
10441 }
10442 }
Chris Lattner60921c92003-12-19 05:58:40 +000010443 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010444}
10445
Reid Spencer17212df2006-12-12 09:18:51 +000010446static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10447 Instruction *InsertPoint,
10448 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010449 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10450 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010451 // We must cast correctly to the pointer type. Ensure that we
10452 // sign extend the integer value if it is smaller as this is
10453 // used for address computation.
10454 Instruction::CastOps opcode =
10455 (VTySize < PtrSize ? Instruction::SExt :
10456 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10457 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010458}
10459
Chris Lattnera1be5662002-05-02 17:06:02 +000010460
Chris Lattner7e708292002-06-25 16:13:24 +000010461Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010462 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010463 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010464 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010465 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010466 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010467
Chris Lattnere87597f2004-10-16 18:11:37 +000010468 if (isa<UndefValue>(GEP.getOperand(0)))
10469 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10470
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010471 bool HasZeroPointerIndex = false;
10472 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10473 HasZeroPointerIndex = C->isNullValue();
10474
10475 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010476 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010477
Chris Lattner28977af2004-04-05 01:30:19 +000010478 // Eliminate unneeded casts for indices.
10479 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010480
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010481 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010482 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10483 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010484 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010485 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010486 if (CI->getOpcode() == Instruction::ZExt ||
10487 CI->getOpcode() == Instruction::SExt) {
10488 const Type *SrcTy = CI->getOperand(0)->getType();
10489 // We can eliminate a cast from i32 to i64 iff the target
10490 // is a 32-bit pointer target.
10491 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10492 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010493 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010494 }
10495 }
10496 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010497 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010498 // to what we need. If narrower, sign-extend it to what we need.
10499 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010500 // insert it. This explicit cast can make subsequent optimizations more
10501 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010502 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010503 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010504 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010505 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010506 MadeChange = true;
10507 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010508 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10509 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010510 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010511 MadeChange = true;
10512 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010513 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10514 if (Constant *C = dyn_cast<Constant>(Op)) {
10515 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10516 MadeChange = true;
10517 } else {
10518 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10519 GEP);
10520 *i = Op;
10521 MadeChange = true;
10522 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010523 }
Chris Lattner28977af2004-04-05 01:30:19 +000010524 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010525 }
Chris Lattner28977af2004-04-05 01:30:19 +000010526 if (MadeChange) return &GEP;
10527
Chris Lattner90ac28c2002-08-02 19:29:35 +000010528 // Combine Indices - If the source pointer to this getelementptr instruction
10529 // is a getelementptr instruction, combine the indices of the two
10530 // getelementptr instructions into a single instruction.
10531 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010532 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010533 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010534 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010535
10536 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010537 // Note that if our source is a gep chain itself that we wait for that
10538 // chain to be resolved before we perform this transformation. This
10539 // avoids us creating a TON of code in some cases.
10540 //
10541 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10542 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10543 return 0; // Wait until our source is folded to completion.
10544
Chris Lattner72588fc2007-02-15 22:48:32 +000010545 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010546
10547 // Find out whether the last index in the source GEP is a sequential idx.
10548 bool EndsWithSequential = false;
10549 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10550 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010551 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010552
Chris Lattner90ac28c2002-08-02 19:29:35 +000010553 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010554 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010555 // Replace: gep (gep %P, long B), long A, ...
10556 // With: T = long A+B; gep %P, T, ...
10557 //
Chris Lattner620ce142004-05-07 22:09:22 +000010558 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010559 if (SO1 == Constant::getNullValue(SO1->getType())) {
10560 Sum = GO1;
10561 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10562 Sum = SO1;
10563 } else {
10564 // If they aren't the same type, convert both to an integer of the
10565 // target's pointer size.
10566 if (SO1->getType() != GO1->getType()) {
10567 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010568 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010569 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010570 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010571 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010572 unsigned PS = TD->getPointerSizeInBits();
10573 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010574 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010575 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010576
Duncan Sands514ab342007-11-01 20:53:16 +000010577 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010578 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010579 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010580 } else {
10581 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010582 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10583 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010584 }
10585 }
10586 }
Chris Lattner620ce142004-05-07 22:09:22 +000010587 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10588 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10589 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010590 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010591 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010592 }
Chris Lattner28977af2004-04-05 01:30:19 +000010593 }
Chris Lattner620ce142004-05-07 22:09:22 +000010594
10595 // Recycle the GEP we already have if possible.
10596 if (SrcGEPOperands.size() == 2) {
10597 GEP.setOperand(0, SrcGEPOperands[0]);
10598 GEP.setOperand(1, Sum);
10599 return &GEP;
10600 } else {
10601 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10602 SrcGEPOperands.end()-1);
10603 Indices.push_back(Sum);
10604 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10605 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010606 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010607 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010608 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010609 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010610 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10611 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010612 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10613 }
10614
10615 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010616 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10617 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010618
Chris Lattner620ce142004-05-07 22:09:22 +000010619 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010620 // GEP of global variable. If all of the indices for this GEP are
10621 // constants, we can promote this to a constexpr instead of an instruction.
10622
10623 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010624 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010625 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10626 for (; I != E && isa<Constant>(*I); ++I)
10627 Indices.push_back(cast<Constant>(*I));
10628
10629 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010630 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10631 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010632
10633 // Replace all uses of the GEP with the new constexpr...
10634 return ReplaceInstUsesWith(GEP, CE);
10635 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010636 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010637 if (!isa<PointerType>(X->getType())) {
10638 // Not interesting. Source pointer must be a cast from pointer.
10639 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010640 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10641 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010642 //
10643 // This occurs when the program declares an array extern like "int X[];"
10644 //
10645 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10646 const PointerType *XTy = cast<PointerType>(X->getType());
10647 if (const ArrayType *XATy =
10648 dyn_cast<ArrayType>(XTy->getElementType()))
10649 if (const ArrayType *CATy =
10650 dyn_cast<ArrayType>(CPTy->getElementType()))
10651 if (CATy->getElementType() == XATy->getElementType()) {
10652 // At this point, we know that the cast source type is a pointer
10653 // to an array of the same type as the destination pointer
10654 // array. Because the array type is never stepped over (there
10655 // is a leading zero) we can fold the cast into this GEP.
10656 GEP.setOperand(0, X);
10657 return &GEP;
10658 }
10659 } else if (GEP.getNumOperands() == 2) {
10660 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010661 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10662 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010663 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10664 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10665 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010666 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10667 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010668 Value *Idx[2];
10669 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10670 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010671 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010672 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010673 // V and GEP are both pointer types --> BitCast
10674 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010675 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010676
10677 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010678 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010679 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010680 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010681
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010682 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010683 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010684 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010685
10686 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10687 // allow either a mul, shift, or constant here.
10688 Value *NewIdx = 0;
10689 ConstantInt *Scale = 0;
10690 if (ArrayEltSize == 1) {
10691 NewIdx = GEP.getOperand(1);
10692 Scale = ConstantInt::get(NewIdx->getType(), 1);
10693 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010694 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010695 Scale = CI;
10696 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10697 if (Inst->getOpcode() == Instruction::Shl &&
10698 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010699 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10700 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10701 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010702 NewIdx = Inst->getOperand(0);
10703 } else if (Inst->getOpcode() == Instruction::Mul &&
10704 isa<ConstantInt>(Inst->getOperand(1))) {
10705 Scale = cast<ConstantInt>(Inst->getOperand(1));
10706 NewIdx = Inst->getOperand(0);
10707 }
10708 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010709
Chris Lattner7835cdd2005-09-13 18:36:04 +000010710 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010711 // out, perform the transformation. Note, we don't know whether Scale is
10712 // signed or not. We'll use unsigned version of division/modulo
10713 // operation after making sure Scale doesn't have the sign bit set.
10714 if (Scale && Scale->getSExtValue() >= 0LL &&
10715 Scale->getZExtValue() % ArrayEltSize == 0) {
10716 Scale = ConstantInt::get(Scale->getType(),
10717 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010718 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010719 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010720 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010721 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010722 NewIdx = InsertNewInstBefore(Sc, GEP);
10723 }
10724
10725 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010726 Value *Idx[2];
10727 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10728 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010729 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010730 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010731 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10732 // The NewGEP must be pointer typed, so must the old one -> BitCast
10733 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010734 }
10735 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010736 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010737 }
Chris Lattner58407792009-01-09 04:53:57 +000010738
Chris Lattner46cd5a12009-01-09 05:44:56 +000010739 /// See if we can simplify:
10740 /// X = bitcast A to B*
10741 /// Y = gep X, <...constant indices...>
10742 /// into a gep of the original struct. This is important for SROA and alias
10743 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010744 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010745 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10746 // Determine how much the GEP moves the pointer. We are guaranteed to get
10747 // a constant back from EmitGEPOffset.
10748 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10749 int64_t Offset = OffsetV->getSExtValue();
10750
10751 // If this GEP instruction doesn't move the pointer, just replace the GEP
10752 // with a bitcast of the real input to the dest type.
10753 if (Offset == 0) {
10754 // If the bitcast is of an allocation, and the allocation will be
10755 // converted to match the type of the cast, don't touch this.
10756 if (isa<AllocationInst>(BCI->getOperand(0))) {
10757 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10758 if (Instruction *I = visitBitCast(*BCI)) {
10759 if (I != BCI) {
10760 I->takeName(BCI);
10761 BCI->getParent()->getInstList().insert(BCI, I);
10762 ReplaceInstUsesWith(*BCI, I);
10763 }
10764 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010765 }
Chris Lattner58407792009-01-09 04:53:57 +000010766 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010767 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010768 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010769
10770 // Otherwise, if the offset is non-zero, we need to find out if there is a
10771 // field at Offset in 'A's type. If so, we can pull the cast through the
10772 // GEP.
10773 SmallVector<Value*, 8> NewIndices;
10774 const Type *InTy =
10775 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10776 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10777 Instruction *NGEP =
10778 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10779 NewIndices.end());
10780 if (NGEP->getType() == GEP.getType()) return NGEP;
10781 InsertNewInstBefore(NGEP, GEP);
10782 NGEP->takeName(&GEP);
10783 return new BitCastInst(NGEP, GEP.getType());
10784 }
Chris Lattner58407792009-01-09 04:53:57 +000010785 }
10786 }
10787
Chris Lattner8a2a3112001-12-14 16:52:21 +000010788 return 0;
10789}
10790
Chris Lattner0864acf2002-11-04 16:18:53 +000010791Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10792 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010793 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010794 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10795 const Type *NewTy =
10796 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010797 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010798
10799 // Create and insert the replacement instruction...
10800 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010801 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010802 else {
10803 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010804 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010805 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010806
10807 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010808
Chris Lattner0864acf2002-11-04 16:18:53 +000010809 // Scan to the end of the allocation instructions, to skip over a block of
10810 // allocas if possible...
10811 //
10812 BasicBlock::iterator It = New;
10813 while (isa<AllocationInst>(*It)) ++It;
10814
10815 // Now that I is pointing to the first non-allocation-inst in the block,
10816 // insert our getelementptr instruction...
10817 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010818 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010819 Value *Idx[2];
10820 Idx[0] = NullIdx;
10821 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010822 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10823 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010824
10825 // Now make everything use the getelementptr instead of the original
10826 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010827 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010828 } else if (isa<UndefValue>(AI.getArraySize())) {
10829 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010830 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010831 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010832
Dan Gohman6893cd72009-01-13 20:18:38 +000010833 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10834 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10835 // Note that we only do this for alloca's, because malloc should allocate and
10836 // return a unique pointer, even for a zero byte allocation.
10837 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10838 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10839
10840 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10841 if (AI.getAlignment() == 0)
10842 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10843 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010844
Chris Lattner0864acf2002-11-04 16:18:53 +000010845 return 0;
10846}
10847
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010848Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10849 Value *Op = FI.getOperand(0);
10850
Chris Lattner17be6352004-10-18 02:59:09 +000010851 // free undef -> unreachable.
10852 if (isa<UndefValue>(Op)) {
10853 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010854 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010855 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010856 return EraseInstFromFunction(FI);
10857 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010858
Chris Lattner6160e852004-02-28 04:57:37 +000010859 // If we have 'free null' delete the instruction. This can happen in stl code
10860 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010861 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010862 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010863
10864 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10865 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10866 FI.setOperand(0, CI->getOperand(0));
10867 return &FI;
10868 }
10869
10870 // Change free (gep X, 0,0,0,0) into free(X)
10871 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10872 if (GEPI->hasAllZeroIndices()) {
10873 AddToWorkList(GEPI);
10874 FI.setOperand(0, GEPI->getOperand(0));
10875 return &FI;
10876 }
10877 }
10878
10879 // Change free(malloc) into nothing, if the malloc has a single use.
10880 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10881 if (MI->hasOneUse()) {
10882 EraseInstFromFunction(FI);
10883 return EraseInstFromFunction(*MI);
10884 }
Chris Lattner6160e852004-02-28 04:57:37 +000010885
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010886 return 0;
10887}
10888
10889
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010890/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010891static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010892 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010893 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010894 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010895
Devang Patel99db6ad2007-10-18 19:52:32 +000010896 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10897 // Instead of loading constant c string, use corresponding integer value
10898 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010899 std::string Str;
10900 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010901 unsigned len = Str.length();
10902 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10903 unsigned numBits = Ty->getPrimitiveSizeInBits();
10904 // Replace LI with immediate integer store.
10905 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010906 APInt StrVal(numBits, 0);
10907 APInt SingleChar(numBits, 0);
10908 if (TD->isLittleEndian()) {
10909 for (signed i = len-1; i >= 0; i--) {
10910 SingleChar = (uint64_t) Str[i];
10911 StrVal = (StrVal << 8) | SingleChar;
10912 }
10913 } else {
10914 for (unsigned i = 0; i < len; i++) {
10915 SingleChar = (uint64_t) Str[i];
10916 StrVal = (StrVal << 8) | SingleChar;
10917 }
10918 // Append NULL at the end.
10919 SingleChar = 0;
10920 StrVal = (StrVal << 8) | SingleChar;
10921 }
10922 Value *NL = ConstantInt::get(StrVal);
10923 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010924 }
10925 }
10926 }
10927
Chris Lattnerb89e0712004-07-13 01:49:43 +000010928 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010929 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010930 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010931
Reid Spencer42230162007-01-22 05:51:25 +000010932 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010933 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010934 // If the source is an array, the code below will not succeed. Check to
10935 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10936 // constants.
10937 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10938 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10939 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010940 Value *Idxs[2];
10941 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10942 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010943 SrcTy = cast<PointerType>(CastOp->getType());
10944 SrcPTy = SrcTy->getElementType();
10945 }
10946
Reid Spencer42230162007-01-22 05:51:25 +000010947 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010948 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010949 // Do not allow turning this into a load of an integer, which is then
10950 // casted to a pointer, this pessimizes pointer analysis a lot.
10951 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010952 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10953 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010954
Chris Lattnerf9527852005-01-31 04:50:46 +000010955 // Okay, we are casting from one integer or pointer type to another of
10956 // the same size. Instead of casting the pointer before the load, cast
10957 // the result of the loaded value.
10958 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10959 CI->getName(),
10960 LI.isVolatile()),LI);
10961 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010962 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010963 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010964 }
10965 }
10966 return 0;
10967}
10968
Chris Lattnerc10aced2004-09-19 18:43:46 +000010969/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010970/// from this value cannot trap. If it is not obviously safe to load from the
10971/// specified pointer, we do a quick local scan of the basic block containing
10972/// ScanFrom, to determine if the address is already accessed.
10973static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010974 // If it is an alloca it is always safe to load from.
10975 if (isa<AllocaInst>(V)) return true;
10976
Duncan Sands46318cd2007-09-19 10:25:38 +000010977 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010978 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010979 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010980 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010981
10982 // Otherwise, be a little bit agressive by scanning the local block where we
10983 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010984 // from/to. If so, the previous load or store would have already trapped,
10985 // so there is no harm doing an extra load (also, CSE will later eliminate
10986 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010987 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10988
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010989 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010990 --BBI;
10991
Chris Lattner2de3fec2008-06-20 05:12:56 +000010992 // If we see a free or a call (which might do a free) the pointer could be
10993 // marked invalid.
10994 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10995 return false;
10996
Chris Lattner8a375202004-09-19 19:18:10 +000010997 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10998 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000010999 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011000 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011001 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011002
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011003 }
Chris Lattner8a375202004-09-19 19:18:10 +000011004 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011005}
11006
Chris Lattner833b8a42003-06-26 05:06:25 +000011007Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11008 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011009
Dan Gohman9941f742007-07-20 16:34:21 +000011010 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000011011 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
11012 if (KnownAlign >
11013 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11014 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011015 LI.setAlignment(KnownAlign);
11016
Chris Lattner37366c12005-05-01 04:24:53 +000011017 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011018 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011019 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011020 return Res;
11021
11022 // None of the following transforms are legal for volatile loads.
11023 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011024
Dan Gohman2276a7b2008-10-15 23:19:35 +000011025 // Do really simple store-to-load forwarding and load CSE, to catch cases
11026 // where there are several consequtive memory accesses to the same location,
11027 // separated by a few arithmetic operations.
11028 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011029 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11030 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011031
Christopher Lambb15147e2007-12-29 07:56:53 +000011032 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11033 const Value *GEPI0 = GEPI->getOperand(0);
11034 // TODO: Consider a target hook for valid address spaces for this xform.
11035 if (isa<ConstantPointerNull>(GEPI0) &&
11036 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011037 // Insert a new store to null instruction before the load to indicate
11038 // that this code is not reachable. We do this instead of inserting
11039 // an unreachable instruction directly because we cannot modify the
11040 // CFG.
11041 new StoreInst(UndefValue::get(LI.getType()),
11042 Constant::getNullValue(Op->getType()), &LI);
11043 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11044 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011045 }
Chris Lattner37366c12005-05-01 04:24:53 +000011046
Chris Lattnere87597f2004-10-16 18:11:37 +000011047 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011048 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011049 // TODO: Consider a target hook for valid address spaces for this xform.
11050 if (isa<UndefValue>(C) || (C->isNullValue() &&
11051 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011052 // Insert a new store to null instruction before the load to indicate that
11053 // this code is not reachable. We do this instead of inserting an
11054 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011055 new StoreInst(UndefValue::get(LI.getType()),
11056 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011057 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011058 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011059
Chris Lattnere87597f2004-10-16 18:11:37 +000011060 // Instcombine load (constant global) into the value loaded.
11061 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011062 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000011063 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011064
Chris Lattnere87597f2004-10-16 18:11:37 +000011065 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011066 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011067 if (CE->getOpcode() == Instruction::GetElementPtr) {
11068 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011069 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000011070 if (Constant *V =
11071 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011072 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011073 if (CE->getOperand(0)->isNullValue()) {
11074 // Insert a new store to null instruction before the load to indicate
11075 // that this code is not reachable. We do this instead of inserting
11076 // an unreachable instruction directly because we cannot modify the
11077 // CFG.
11078 new StoreInst(UndefValue::get(LI.getType()),
11079 Constant::getNullValue(Op->getType()), &LI);
11080 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11081 }
11082
Reid Spencer3da59db2006-11-27 01:05:10 +000011083 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011084 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011085 return Res;
11086 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011087 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011088 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011089
11090 // If this load comes from anywhere in a constant global, and if the global
11091 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011092 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner8d2e8882007-08-11 18:48:48 +000011093 if (GV->isConstant() && GV->hasInitializer()) {
11094 if (GV->getInitializer()->isNullValue())
11095 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11096 else if (isa<UndefValue>(GV->getInitializer()))
11097 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11098 }
11099 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011100
Chris Lattner37366c12005-05-01 04:24:53 +000011101 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011102 // Change select and PHI nodes to select values instead of addresses: this
11103 // helps alias analysis out a lot, allows many others simplifications, and
11104 // exposes redundancy in the code.
11105 //
11106 // Note that we cannot do the transformation unless we know that the
11107 // introduced loads cannot trap! Something like this is valid as long as
11108 // the condition is always false: load (select bool %C, int* null, int* %G),
11109 // but it would not be valid if we transformed it to load from null
11110 // unconditionally.
11111 //
11112 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11113 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011114 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11115 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011116 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011117 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011118 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011119 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011120 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011121 }
11122
Chris Lattner684fe212004-09-23 15:46:00 +000011123 // load (select (cond, null, P)) -> load P
11124 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11125 if (C->isNullValue()) {
11126 LI.setOperand(0, SI->getOperand(2));
11127 return &LI;
11128 }
11129
11130 // load (select (cond, P, null)) -> load P
11131 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11132 if (C->isNullValue()) {
11133 LI.setOperand(0, SI->getOperand(1));
11134 return &LI;
11135 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011136 }
11137 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011138 return 0;
11139}
11140
Reid Spencer55af2b52007-01-19 21:20:31 +000011141/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011142/// when possible. This makes it generally easy to do alias analysis and/or
11143/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011144static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11145 User *CI = cast<User>(SI.getOperand(1));
11146 Value *CastOp = CI->getOperand(0);
11147
11148 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011149 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11150 if (SrcTy == 0) return 0;
11151
11152 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011153
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011154 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11155 return 0;
11156
Chris Lattner3914f722009-01-24 01:00:13 +000011157 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11158 /// to its first element. This allows us to handle things like:
11159 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11160 /// on 32-bit hosts.
11161 SmallVector<Value*, 4> NewGEPIndices;
11162
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011163 // If the source is an array, the code below will not succeed. Check to
11164 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11165 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011166 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11167 // Index through pointer.
11168 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11169 NewGEPIndices.push_back(Zero);
11170
11171 while (1) {
11172 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011173 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011174 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011175 NewGEPIndices.push_back(Zero);
11176 SrcPTy = STy->getElementType(0);
11177 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11178 NewGEPIndices.push_back(Zero);
11179 SrcPTy = ATy->getElementType();
11180 } else {
11181 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011182 }
Chris Lattner3914f722009-01-24 01:00:13 +000011183 }
11184
11185 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11186 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011187
11188 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11189 return 0;
11190
Chris Lattner71759c42009-01-16 20:12:52 +000011191 // If the pointers point into different address spaces or if they point to
11192 // values with different sizes, we can't do the transformation.
11193 if (SrcTy->getAddressSpace() !=
11194 cast<PointerType>(CI->getType())->getAddressSpace() ||
11195 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011196 IC.getTargetData().getTypeSizeInBits(DestPTy))
11197 return 0;
11198
11199 // Okay, we are casting from one integer or pointer type to another of
11200 // the same size. Instead of casting the pointer before
11201 // the store, cast the value to be stored.
11202 Value *NewCast;
11203 Value *SIOp0 = SI.getOperand(0);
11204 Instruction::CastOps opcode = Instruction::BitCast;
11205 const Type* CastSrcTy = SIOp0->getType();
11206 const Type* CastDstTy = SrcPTy;
11207 if (isa<PointerType>(CastDstTy)) {
11208 if (CastSrcTy->isInteger())
11209 opcode = Instruction::IntToPtr;
11210 } else if (isa<IntegerType>(CastDstTy)) {
11211 if (isa<PointerType>(SIOp0->getType()))
11212 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011213 }
Chris Lattner3914f722009-01-24 01:00:13 +000011214
11215 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11216 // emit a GEP to index into its first field.
11217 if (!NewGEPIndices.empty()) {
11218 if (Constant *C = dyn_cast<Constant>(CastOp))
11219 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11220 NewGEPIndices.size());
11221 else
11222 CastOp = IC.InsertNewInstBefore(
11223 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11224 NewGEPIndices.end()), SI);
11225 }
11226
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011227 if (Constant *C = dyn_cast<Constant>(SIOp0))
11228 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11229 else
11230 NewCast = IC.InsertNewInstBefore(
11231 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11232 SI);
11233 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011234}
11235
Chris Lattner4aebaee2008-11-27 08:56:30 +000011236/// equivalentAddressValues - Test if A and B will obviously have the same
11237/// value. This includes recognizing that %t0 and %t1 will have the same
11238/// value in code like this:
11239/// %t0 = getelementptr @a, 0, 3
11240/// store i32 0, i32* %t0
11241/// %t1 = getelementptr @a, 0, 3
11242/// %t2 = load i32* %t1
11243///
11244static bool equivalentAddressValues(Value *A, Value *B) {
11245 // Test if the values are trivially equivalent.
11246 if (A == B) return true;
11247
11248 // Test if the values come form identical arithmetic instructions.
11249 if (isa<BinaryOperator>(A) ||
11250 isa<CastInst>(A) ||
11251 isa<PHINode>(A) ||
11252 isa<GetElementPtrInst>(A))
11253 if (Instruction *BI = dyn_cast<Instruction>(B))
11254 if (cast<Instruction>(A)->isIdenticalTo(BI))
11255 return true;
11256
11257 // Otherwise they may not be equivalent.
11258 return false;
11259}
11260
Chris Lattner2f503e62005-01-31 05:36:43 +000011261Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11262 Value *Val = SI.getOperand(0);
11263 Value *Ptr = SI.getOperand(1);
11264
11265 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011266 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011267 ++NumCombined;
11268 return 0;
11269 }
Chris Lattner836692d2007-01-15 06:51:56 +000011270
11271 // If the RHS is an alloca with a single use, zapify the store, making the
11272 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000011273 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000011274 if (isa<AllocaInst>(Ptr)) {
11275 EraseInstFromFunction(SI);
11276 ++NumCombined;
11277 return 0;
11278 }
11279
11280 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11281 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11282 GEP->getOperand(0)->hasOneUse()) {
11283 EraseInstFromFunction(SI);
11284 ++NumCombined;
11285 return 0;
11286 }
11287 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011288
Dan Gohman9941f742007-07-20 16:34:21 +000011289 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000011290 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11291 if (KnownAlign >
11292 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11293 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011294 SI.setAlignment(KnownAlign);
11295
Chris Lattner9ca96412006-02-08 03:25:32 +000011296 // Do really simple DSE, to catch cases where there are several consequtive
11297 // stores to the same location, separated by a few arithmetic operations. This
11298 // situation often occurs with bitfield accesses.
11299 BasicBlock::iterator BBI = &SI;
11300 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11301 --ScanInsts) {
11302 --BBI;
11303
11304 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11305 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011306 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11307 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011308 ++NumDeadStore;
11309 ++BBI;
11310 EraseInstFromFunction(*PrevSI);
11311 continue;
11312 }
11313 break;
11314 }
11315
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011316 // If this is a load, we have to stop. However, if the loaded value is from
11317 // the pointer we're loading and is producing the pointer we're storing,
11318 // then *this* store is dead (X = load P; store X -> P).
11319 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011320 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11321 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011322 EraseInstFromFunction(SI);
11323 ++NumCombined;
11324 return 0;
11325 }
11326 // Otherwise, this is a load from some other location. Stores before it
11327 // may not be dead.
11328 break;
11329 }
11330
Chris Lattner9ca96412006-02-08 03:25:32 +000011331 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011332 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011333 break;
11334 }
11335
11336
11337 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011338
11339 // store X, null -> turns into 'unreachable' in SimplifyCFG
11340 if (isa<ConstantPointerNull>(Ptr)) {
11341 if (!isa<UndefValue>(Val)) {
11342 SI.setOperand(0, UndefValue::get(Val->getType()));
11343 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011344 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011345 ++NumCombined;
11346 }
11347 return 0; // Do not modify these!
11348 }
11349
11350 // store undef, Ptr -> noop
11351 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011352 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011353 ++NumCombined;
11354 return 0;
11355 }
11356
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011357 // If the pointer destination is a cast, see if we can fold the cast into the
11358 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011359 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011360 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11361 return Res;
11362 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011363 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011364 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11365 return Res;
11366
Chris Lattner408902b2005-09-12 23:23:25 +000011367
11368 // If this store is the last instruction in the basic block, and if the block
11369 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000011370 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000011371 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011372 if (BI->isUnconditional())
11373 if (SimplifyStoreAtEndOfBlock(SI))
11374 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011375
Chris Lattner2f503e62005-01-31 05:36:43 +000011376 return 0;
11377}
11378
Chris Lattner3284d1f2007-04-15 00:07:55 +000011379/// SimplifyStoreAtEndOfBlock - Turn things like:
11380/// if () { *P = v1; } else { *P = v2 }
11381/// into a phi node with a store in the successor.
11382///
Chris Lattner31755a02007-04-15 01:02:18 +000011383/// Simplify things like:
11384/// *P = v1; if () { *P = v2; }
11385/// into a phi node with a store in the successor.
11386///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011387bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11388 BasicBlock *StoreBB = SI.getParent();
11389
11390 // Check to see if the successor block has exactly two incoming edges. If
11391 // so, see if the other predecessor contains a store to the same location.
11392 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011393 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011394
11395 // Determine whether Dest has exactly two predecessors and, if so, compute
11396 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011397 pred_iterator PI = pred_begin(DestBB);
11398 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011399 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011400 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011401 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011402 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011403 return false;
11404
11405 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011406 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011407 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011408 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011409 }
Chris Lattner31755a02007-04-15 01:02:18 +000011410 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011411 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011412
11413 // Bail out if all the relevant blocks aren't distinct (this can happen,
11414 // for example, if SI is in an infinite loop)
11415 if (StoreBB == DestBB || OtherBB == DestBB)
11416 return false;
11417
Chris Lattner31755a02007-04-15 01:02:18 +000011418 // Verify that the other block ends in a branch and is not otherwise empty.
11419 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011420 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011421 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011422 return false;
11423
Chris Lattner31755a02007-04-15 01:02:18 +000011424 // If the other block ends in an unconditional branch, check for the 'if then
11425 // else' case. there is an instruction before the branch.
11426 StoreInst *OtherStore = 0;
11427 if (OtherBr->isUnconditional()) {
11428 // If this isn't a store, or isn't a store to the same location, bail out.
11429 --BBI;
11430 OtherStore = dyn_cast<StoreInst>(BBI);
11431 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11432 return false;
11433 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011434 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011435 // destinations is StoreBB, then we have the if/then case.
11436 if (OtherBr->getSuccessor(0) != StoreBB &&
11437 OtherBr->getSuccessor(1) != StoreBB)
11438 return false;
11439
11440 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011441 // if/then triangle. See if there is a store to the same ptr as SI that
11442 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011443 for (;; --BBI) {
11444 // Check to see if we find the matching store.
11445 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11446 if (OtherStore->getOperand(1) != SI.getOperand(1))
11447 return false;
11448 break;
11449 }
Eli Friedman6903a242008-06-13 22:02:12 +000011450 // If we find something that may be using or overwriting the stored
11451 // value, or if we run out of instructions, we can't do the xform.
11452 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011453 BBI == OtherBB->begin())
11454 return false;
11455 }
11456
11457 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011458 // make sure nothing reads or overwrites the stored value in
11459 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011460 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11461 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011462 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011463 return false;
11464 }
11465 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011466
Chris Lattner31755a02007-04-15 01:02:18 +000011467 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011468 Value *MergedVal = OtherStore->getOperand(0);
11469 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011470 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011471 PN->reserveOperandSpace(2);
11472 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011473 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11474 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011475 }
11476
11477 // Advance to a place where it is safe to insert the new store and
11478 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011479 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011480 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11481 OtherStore->isVolatile()), *BBI);
11482
11483 // Nuke the old stores.
11484 EraseInstFromFunction(SI);
11485 EraseInstFromFunction(*OtherStore);
11486 ++NumCombined;
11487 return true;
11488}
11489
Chris Lattner2f503e62005-01-31 05:36:43 +000011490
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011491Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11492 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011493 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011494 BasicBlock *TrueDest;
11495 BasicBlock *FalseDest;
11496 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11497 !isa<Constant>(X)) {
11498 // Swap Destinations and condition...
11499 BI.setCondition(X);
11500 BI.setSuccessor(0, FalseDest);
11501 BI.setSuccessor(1, TrueDest);
11502 return &BI;
11503 }
11504
Reid Spencere4d87aa2006-12-23 06:05:41 +000011505 // Cannonicalize fcmp_one -> fcmp_oeq
11506 FCmpInst::Predicate FPred; Value *Y;
11507 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11508 TrueDest, FalseDest)))
11509 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11510 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11511 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011512 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011513 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11514 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011515 // Swap Destinations and condition...
11516 BI.setCondition(NewSCC);
11517 BI.setSuccessor(0, FalseDest);
11518 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011519 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011520 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011521 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011522 return &BI;
11523 }
11524
11525 // Cannonicalize icmp_ne -> icmp_eq
11526 ICmpInst::Predicate IPred;
11527 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11528 TrueDest, FalseDest)))
11529 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11530 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11531 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11532 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011533 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011534 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11535 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011536 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011537 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011538 BI.setSuccessor(0, FalseDest);
11539 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011540 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011541 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011542 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011543 return &BI;
11544 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011545
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011546 return 0;
11547}
Chris Lattner0864acf2002-11-04 16:18:53 +000011548
Chris Lattner46238a62004-07-03 00:26:11 +000011549Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11550 Value *Cond = SI.getCondition();
11551 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11552 if (I->getOpcode() == Instruction::Add)
11553 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11554 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11555 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011556 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011557 AddRHS));
11558 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011559 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011560 return &SI;
11561 }
11562 }
11563 return 0;
11564}
11565
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011566Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011567 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011568
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011569 if (!EV.hasIndices())
11570 return ReplaceInstUsesWith(EV, Agg);
11571
11572 if (Constant *C = dyn_cast<Constant>(Agg)) {
11573 if (isa<UndefValue>(C))
11574 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11575
11576 if (isa<ConstantAggregateZero>(C))
11577 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11578
11579 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11580 // Extract the element indexed by the first index out of the constant
11581 Value *V = C->getOperand(*EV.idx_begin());
11582 if (EV.getNumIndices() > 1)
11583 // Extract the remaining indices out of the constant indexed by the
11584 // first index
11585 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11586 else
11587 return ReplaceInstUsesWith(EV, V);
11588 }
11589 return 0; // Can't handle other constants
11590 }
11591 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11592 // We're extracting from an insertvalue instruction, compare the indices
11593 const unsigned *exti, *exte, *insi, *inse;
11594 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11595 exte = EV.idx_end(), inse = IV->idx_end();
11596 exti != exte && insi != inse;
11597 ++exti, ++insi) {
11598 if (*insi != *exti)
11599 // The insert and extract both reference distinctly different elements.
11600 // This means the extract is not influenced by the insert, and we can
11601 // replace the aggregate operand of the extract with the aggregate
11602 // operand of the insert. i.e., replace
11603 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11604 // %E = extractvalue { i32, { i32 } } %I, 0
11605 // with
11606 // %E = extractvalue { i32, { i32 } } %A, 0
11607 return ExtractValueInst::Create(IV->getAggregateOperand(),
11608 EV.idx_begin(), EV.idx_end());
11609 }
11610 if (exti == exte && insi == inse)
11611 // Both iterators are at the end: Index lists are identical. Replace
11612 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11613 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11614 // with "i32 42"
11615 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11616 if (exti == exte) {
11617 // The extract list is a prefix of the insert list. i.e. replace
11618 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11619 // %E = extractvalue { i32, { i32 } } %I, 1
11620 // with
11621 // %X = extractvalue { i32, { i32 } } %A, 1
11622 // %E = insertvalue { i32 } %X, i32 42, 0
11623 // by switching the order of the insert and extract (though the
11624 // insertvalue should be left in, since it may have other uses).
11625 Value *NewEV = InsertNewInstBefore(
11626 ExtractValueInst::Create(IV->getAggregateOperand(),
11627 EV.idx_begin(), EV.idx_end()),
11628 EV);
11629 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11630 insi, inse);
11631 }
11632 if (insi == inse)
11633 // The insert list is a prefix of the extract list
11634 // We can simply remove the common indices from the extract and make it
11635 // operate on the inserted value instead of the insertvalue result.
11636 // i.e., replace
11637 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11638 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11639 // with
11640 // %E extractvalue { i32 } { i32 42 }, 0
11641 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11642 exti, exte);
11643 }
11644 // Can't simplify extracts from other values. Note that nested extracts are
11645 // already simplified implicitely by the above (extract ( extract (insert) )
11646 // will be translated into extract ( insert ( extract ) ) first and then just
11647 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011648 return 0;
11649}
11650
Chris Lattner220b0cf2006-03-05 00:22:33 +000011651/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11652/// is to leave as a vector operation.
11653static bool CheapToScalarize(Value *V, bool isConstant) {
11654 if (isa<ConstantAggregateZero>(V))
11655 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011656 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011657 if (isConstant) return true;
11658 // If all elts are the same, we can extract.
11659 Constant *Op0 = C->getOperand(0);
11660 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11661 if (C->getOperand(i) != Op0)
11662 return false;
11663 return true;
11664 }
11665 Instruction *I = dyn_cast<Instruction>(V);
11666 if (!I) return false;
11667
11668 // Insert element gets simplified to the inserted element or is deleted if
11669 // this is constant idx extract element and its a constant idx insertelt.
11670 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11671 isa<ConstantInt>(I->getOperand(2)))
11672 return true;
11673 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11674 return true;
11675 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11676 if (BO->hasOneUse() &&
11677 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11678 CheapToScalarize(BO->getOperand(1), isConstant)))
11679 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011680 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11681 if (CI->hasOneUse() &&
11682 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11683 CheapToScalarize(CI->getOperand(1), isConstant)))
11684 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011685
11686 return false;
11687}
11688
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011689/// Read and decode a shufflevector mask.
11690///
11691/// It turns undef elements into values that are larger than the number of
11692/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011693static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11694 unsigned NElts = SVI->getType()->getNumElements();
11695 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11696 return std::vector<unsigned>(NElts, 0);
11697 if (isa<UndefValue>(SVI->getOperand(2)))
11698 return std::vector<unsigned>(NElts, 2*NElts);
11699
11700 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011701 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011702 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11703 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011704 Result.push_back(NElts*2); // undef -> 8
11705 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011706 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011707 return Result;
11708}
11709
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011710/// FindScalarElement - Given a vector and an element number, see if the scalar
11711/// value is already around as a register, for example if it were inserted then
11712/// extracted from the vector.
11713static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011714 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11715 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011716 unsigned Width = PTy->getNumElements();
11717 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011718 return UndefValue::get(PTy->getElementType());
11719
11720 if (isa<UndefValue>(V))
11721 return UndefValue::get(PTy->getElementType());
11722 else if (isa<ConstantAggregateZero>(V))
11723 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011724 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011725 return CP->getOperand(EltNo);
11726 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11727 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011728 if (!isa<ConstantInt>(III->getOperand(2)))
11729 return 0;
11730 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011731
11732 // If this is an insert to the element we are looking for, return the
11733 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011734 if (EltNo == IIElt)
11735 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011736
11737 // Otherwise, the insertelement doesn't modify the value, recurse on its
11738 // vector input.
11739 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011740 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000011741 unsigned LHSWidth =
11742 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000011743 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000011744 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011745 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011746 else if (InEl < LHSWidth*2)
11747 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000011748 else
11749 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011750 }
11751
11752 // Otherwise, we don't know.
11753 return 0;
11754}
11755
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011756Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011757 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011758 if (isa<UndefValue>(EI.getOperand(0)))
11759 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11760
Dan Gohman07a96762007-07-16 14:29:03 +000011761 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011762 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11763 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11764
Reid Spencer9d6565a2007-02-15 02:26:10 +000011765 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011766 // If vector val is constant with all elements the same, replace EI with
11767 // that element. When the elements are not identical, we cannot replace yet
11768 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011769 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011770 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011771 if (C->getOperand(i) != op0) {
11772 op0 = 0;
11773 break;
11774 }
11775 if (op0)
11776 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011777 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011778
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011779 // If extracting a specified index from the vector, see if we can recursively
11780 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011781 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011782 unsigned IndexVal = IdxC->getZExtValue();
11783 unsigned VectorWidth =
11784 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11785
11786 // If this is extracting an invalid index, turn this into undef, to avoid
11787 // crashing the code below.
11788 if (IndexVal >= VectorWidth)
11789 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11790
Chris Lattner867b99f2006-10-05 06:55:50 +000011791 // This instruction only demands the single element from the input vector.
11792 // If the input vector has a single use, simplify it based on this use
11793 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011794 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011795 uint64_t UndefElts;
11796 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011797 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011798 UndefElts)) {
11799 EI.setOperand(0, V);
11800 return &EI;
11801 }
11802 }
11803
Reid Spencerb83eb642006-10-20 07:07:24 +000011804 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011805 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011806
11807 // If the this extractelement is directly using a bitcast from a vector of
11808 // the same number of elements, see if we can find the source element from
11809 // it. In this case, we will end up needing to bitcast the scalars.
11810 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11811 if (const VectorType *VT =
11812 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11813 if (VT->getNumElements() == VectorWidth)
11814 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11815 return new BitCastInst(Elt, EI.getType());
11816 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011817 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011818
Chris Lattner73fa49d2006-05-25 22:53:38 +000011819 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011820 if (I->hasOneUse()) {
11821 // Push extractelement into predecessor operation if legal and
11822 // profitable to do so
11823 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011824 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11825 if (CheapToScalarize(BO, isConstantElt)) {
11826 ExtractElementInst *newEI0 =
11827 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11828 EI.getName()+".lhs");
11829 ExtractElementInst *newEI1 =
11830 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11831 EI.getName()+".rhs");
11832 InsertNewInstBefore(newEI0, EI);
11833 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011834 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011835 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011836 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011837 unsigned AS =
11838 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011839 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11840 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011841 GetElementPtrInst *GEP =
11842 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011843 InsertNewInstBefore(GEP, EI);
11844 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011845 }
11846 }
11847 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11848 // Extracting the inserted element?
11849 if (IE->getOperand(2) == EI.getOperand(1))
11850 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11851 // If the inserted and extracted elements are constants, they must not
11852 // be the same value, extract from the pre-inserted value instead.
11853 if (isa<Constant>(IE->getOperand(2)) &&
11854 isa<Constant>(EI.getOperand(1))) {
11855 AddUsesToWorkList(EI);
11856 EI.setOperand(0, IE->getOperand(0));
11857 return &EI;
11858 }
11859 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11860 // If this is extracting an element from a shufflevector, figure out where
11861 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011862 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11863 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011864 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000011865 unsigned LHSWidth =
11866 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11867
11868 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011869 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011870 else if (SrcIdx < LHSWidth*2) {
11871 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000011872 Src = SVI->getOperand(1);
11873 } else {
11874 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011875 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011876 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011877 }
11878 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011879 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011880 return 0;
11881}
11882
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011883/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11884/// elements from either LHS or RHS, return the shuffle mask and true.
11885/// Otherwise, return false.
11886static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11887 std::vector<Constant*> &Mask) {
11888 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11889 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011890 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011891
11892 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011893 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011894 return true;
11895 } else if (V == LHS) {
11896 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011897 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011898 return true;
11899 } else if (V == RHS) {
11900 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011901 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011902 return true;
11903 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11904 // If this is an insert of an extract from some other vector, include it.
11905 Value *VecOp = IEI->getOperand(0);
11906 Value *ScalarOp = IEI->getOperand(1);
11907 Value *IdxOp = IEI->getOperand(2);
11908
Chris Lattnerd929f062006-04-27 21:14:21 +000011909 if (!isa<ConstantInt>(IdxOp))
11910 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011911 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011912
11913 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11914 // Okay, we can handle this if the vector we are insertinting into is
11915 // transitively ok.
11916 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11917 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011918 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011919 return true;
11920 }
11921 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11922 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011923 EI->getOperand(0)->getType() == V->getType()) {
11924 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011925 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011926
11927 // This must be extracting from either LHS or RHS.
11928 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11929 // Okay, we can handle this if the vector we are insertinting into is
11930 // transitively ok.
11931 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11932 // If so, update the mask to reflect the inserted value.
11933 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011934 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011935 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011936 } else {
11937 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011938 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011939 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011940
11941 }
11942 return true;
11943 }
11944 }
11945 }
11946 }
11947 }
11948 // TODO: Handle shufflevector here!
11949
11950 return false;
11951}
11952
11953/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11954/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11955/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011956static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011957 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011958 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011959 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011960 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011961 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011962
11963 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011964 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011965 return V;
11966 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011967 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011968 return V;
11969 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11970 // If this is an insert of an extract from some other vector, include it.
11971 Value *VecOp = IEI->getOperand(0);
11972 Value *ScalarOp = IEI->getOperand(1);
11973 Value *IdxOp = IEI->getOperand(2);
11974
11975 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11976 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11977 EI->getOperand(0)->getType() == V->getType()) {
11978 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011979 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11980 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011981
11982 // Either the extracted from or inserted into vector must be RHSVec,
11983 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011984 if (EI->getOperand(0) == RHS || RHS == 0) {
11985 RHS = EI->getOperand(0);
11986 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000011987 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011988 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011989 return V;
11990 }
11991
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011992 if (VecOp == RHS) {
11993 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011994 // Everything but the extracted element is replaced with the RHS.
11995 for (unsigned i = 0; i != NumElts; ++i) {
11996 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011997 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011998 }
11999 return V;
12000 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012001
12002 // If this insertelement is a chain that comes from exactly these two
12003 // vectors, return the vector and the effective shuffle.
12004 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12005 return EI->getOperand(0);
12006
Chris Lattnerefb47352006-04-15 01:39:45 +000012007 }
12008 }
12009 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012010 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012011
12012 // Otherwise, can't do anything fancy. Return an identity vector.
12013 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012014 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012015 return V;
12016}
12017
12018Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12019 Value *VecOp = IE.getOperand(0);
12020 Value *ScalarOp = IE.getOperand(1);
12021 Value *IdxOp = IE.getOperand(2);
12022
Chris Lattner599ded12007-04-09 01:11:16 +000012023 // Inserting an undef or into an undefined place, remove this.
12024 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12025 ReplaceInstUsesWith(IE, VecOp);
12026
Chris Lattnerefb47352006-04-15 01:39:45 +000012027 // If the inserted element was extracted from some other vector, and if the
12028 // indexes are constant, try to turn this into a shufflevector operation.
12029 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12030 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12031 EI->getOperand(0)->getType() == IE.getType()) {
12032 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012033 unsigned ExtractedIdx =
12034 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012035 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012036
12037 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12038 return ReplaceInstUsesWith(IE, VecOp);
12039
12040 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12041 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12042
12043 // If we are extracting a value from a vector, then inserting it right
12044 // back into the same place, just use the input vector.
12045 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12046 return ReplaceInstUsesWith(IE, VecOp);
12047
12048 // We could theoretically do this for ANY input. However, doing so could
12049 // turn chains of insertelement instructions into a chain of shufflevector
12050 // instructions, and right now we do not merge shufflevectors. As such,
12051 // only do this in a situation where it is clear that there is benefit.
12052 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12053 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12054 // the values of VecOp, except then one read from EIOp0.
12055 // Build a new shuffle mask.
12056 std::vector<Constant*> Mask;
12057 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012058 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012059 else {
12060 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012061 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012062 NumVectorElts));
12063 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012064 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012065 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012066 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012067 }
12068
12069 // If this insertelement isn't used by some other insertelement, turn it
12070 // (and any insertelements it points to), into one big shuffle.
12071 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12072 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012073 Value *RHS = 0;
12074 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12075 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12076 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012077 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012078 }
12079 }
12080 }
12081
12082 return 0;
12083}
12084
12085
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012086Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12087 Value *LHS = SVI.getOperand(0);
12088 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012089 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012090
12091 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012092
Chris Lattner867b99f2006-10-05 06:55:50 +000012093 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012094 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012095 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012096
12097 uint64_t UndefElts;
12098 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012099
12100 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12101 return 0;
12102
Dan Gohman488fbfc2008-09-09 18:11:14 +000012103 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12104 if (VWidth <= 64 &&
Dan Gohman3139ff82008-09-11 22:47:57 +000012105 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12106 LHS = SVI.getOperand(0);
12107 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012108 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012109 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012110
Chris Lattner863bcff2006-05-25 23:48:38 +000012111 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12112 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12113 if (LHS == RHS || isa<UndefValue>(LHS)) {
12114 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012115 // shuffle(undef,undef,mask) -> undef.
12116 return ReplaceInstUsesWith(SVI, LHS);
12117 }
12118
Chris Lattner863bcff2006-05-25 23:48:38 +000012119 // Remap any references to RHS to use LHS.
12120 std::vector<Constant*> Elts;
12121 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012122 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012123 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012124 else {
12125 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012126 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012127 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012128 Elts.push_back(UndefValue::get(Type::Int32Ty));
12129 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012130 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012131 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12132 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012133 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012134 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012135 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012136 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012137 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012138 LHS = SVI.getOperand(0);
12139 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012140 MadeChange = true;
12141 }
12142
Chris Lattner7b2e27922006-05-26 00:29:06 +000012143 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012144 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012145
Chris Lattner863bcff2006-05-25 23:48:38 +000012146 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12147 if (Mask[i] >= e*2) continue; // Ignore undef values.
12148 // Is this an identity shuffle of the LHS value?
12149 isLHSID &= (Mask[i] == i);
12150
12151 // Is this an identity shuffle of the RHS value?
12152 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012153 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012154
Chris Lattner863bcff2006-05-25 23:48:38 +000012155 // Eliminate identity shuffles.
12156 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12157 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012158
Chris Lattner7b2e27922006-05-26 00:29:06 +000012159 // If the LHS is a shufflevector itself, see if we can combine it with this
12160 // one without producing an unusual shuffle. Here we are really conservative:
12161 // we are absolutely afraid of producing a shuffle mask not in the input
12162 // program, because the code gen may not be smart enough to turn a merged
12163 // shuffle into two specific shuffles: it may produce worse code. As such,
12164 // we only merge two shuffles if the result is one of the two input shuffle
12165 // masks. In this case, merging the shuffles just removes one instruction,
12166 // which we know is safe. This is good for things like turning:
12167 // (splat(splat)) -> splat.
12168 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12169 if (isa<UndefValue>(RHS)) {
12170 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12171
12172 std::vector<unsigned> NewMask;
12173 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12174 if (Mask[i] >= 2*e)
12175 NewMask.push_back(2*e);
12176 else
12177 NewMask.push_back(LHSMask[Mask[i]]);
12178
12179 // If the result mask is equal to the src shuffle or this shuffle mask, do
12180 // the replacement.
12181 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012182 unsigned LHSInNElts =
12183 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012184 std::vector<Constant*> Elts;
12185 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012186 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012187 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012188 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012189 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012190 }
12191 }
12192 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12193 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012194 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012195 }
12196 }
12197 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012198
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012199 return MadeChange ? &SVI : 0;
12200}
12201
12202
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012203
Chris Lattnerea1c4542004-12-08 23:43:58 +000012204
12205/// TryToSinkInstruction - Try to move the specified instruction from its
12206/// current block into the beginning of DestBlock, which can only happen if it's
12207/// safe to move the instruction past all of the instructions between it and the
12208/// end of its block.
12209static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12210 assert(I->hasOneUse() && "Invariants didn't hold!");
12211
Chris Lattner108e9022005-10-27 17:13:11 +000012212 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012213 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12214 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012215
Chris Lattnerea1c4542004-12-08 23:43:58 +000012216 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012217 if (isa<AllocaInst>(I) && I->getParent() ==
12218 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012219 return false;
12220
Chris Lattner96a52a62004-12-09 07:14:34 +000012221 // We can only sink load instructions if there is nothing between the load and
12222 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012223 if (I->mayReadFromMemory()) {
12224 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012225 Scan != E; ++Scan)
12226 if (Scan->mayWriteToMemory())
12227 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012228 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012229
Dan Gohman02dea8b2008-05-23 21:05:58 +000012230 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012231
Chris Lattner4bc5f802005-08-08 19:11:57 +000012232 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012233 ++NumSunkInst;
12234 return true;
12235}
12236
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012237
12238/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12239/// all reachable code to the worklist.
12240///
12241/// This has a couple of tricks to make the code faster and more powerful. In
12242/// particular, we constant fold and DCE instructions as we go, to avoid adding
12243/// them to the worklist (this significantly speeds up instcombine on code where
12244/// many instructions are dead or constant). Additionally, if we find a branch
12245/// whose condition is a known constant, we only visit the reachable successors.
12246///
12247static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012248 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012249 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012250 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012251 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012252 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012253
Chris Lattner2c7718a2007-03-23 19:17:18 +000012254 while (!Worklist.empty()) {
12255 BB = Worklist.back();
12256 Worklist.pop_back();
12257
12258 // We have now visited this block! If we've already been here, ignore it.
12259 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012260
12261 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012262 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12263 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012264
Chris Lattner2c7718a2007-03-23 19:17:18 +000012265 // DCE instruction if trivially dead.
12266 if (isInstructionTriviallyDead(Inst)) {
12267 ++NumDeadInst;
12268 DOUT << "IC: DCE: " << *Inst;
12269 Inst->eraseFromParent();
12270 continue;
12271 }
12272
12273 // ConstantProp instruction if trivially constant.
12274 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12275 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12276 Inst->replaceAllUsesWith(C);
12277 ++NumConstProp;
12278 Inst->eraseFromParent();
12279 continue;
12280 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012281
Devang Patel7fe1dec2008-11-19 18:56:50 +000012282 // If there are two consecutive llvm.dbg.stoppoint calls then
12283 // it is likely that the optimizer deleted code in between these
12284 // two intrinsics.
12285 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12286 if (DBI_Next) {
12287 if (DBI_Prev
12288 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12289 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12290 IC.RemoveFromWorkList(DBI_Prev);
12291 DBI_Prev->eraseFromParent();
12292 }
12293 DBI_Prev = DBI_Next;
12294 }
12295
Chris Lattner2c7718a2007-03-23 19:17:18 +000012296 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012297 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012298
12299 // Recursively visit successors. If this is a branch or switch on a
12300 // constant, only visit the reachable successor.
12301 TerminatorInst *TI = BB->getTerminator();
12302 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12303 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12304 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012305 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012306 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012307 continue;
12308 }
12309 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12310 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12311 // See if this is an explicit destination.
12312 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12313 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012314 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012315 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012316 continue;
12317 }
12318
12319 // Otherwise it is the default destination.
12320 Worklist.push_back(SI->getSuccessor(0));
12321 continue;
12322 }
12323 }
12324
12325 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12326 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012327 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012328}
12329
Chris Lattnerec9c3582007-03-03 02:04:50 +000012330bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012331 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012332 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012333
12334 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12335 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012336
Chris Lattnerb3d59702005-07-07 20:40:38 +000012337 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012338 // Do a depth-first traversal of the function, populate the worklist with
12339 // the reachable instructions. Ignore blocks that are not reachable. Keep
12340 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012341 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012342 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012343
Chris Lattnerb3d59702005-07-07 20:40:38 +000012344 // Do a quick scan over the function. If we find any blocks that are
12345 // unreachable, remove any instructions inside of them. This prevents
12346 // the instcombine code from having to deal with some bad special cases.
12347 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12348 if (!Visited.count(BB)) {
12349 Instruction *Term = BB->getTerminator();
12350 while (Term != BB->begin()) { // Remove instrs bottom-up
12351 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012352
Bill Wendlingb7427032006-11-26 09:46:52 +000012353 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012354 ++NumDeadInst;
12355
12356 if (!I->use_empty())
12357 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12358 I->eraseFromParent();
12359 }
12360 }
12361 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012362
Chris Lattnerdbab3862007-03-02 21:28:56 +000012363 while (!Worklist.empty()) {
12364 Instruction *I = RemoveOneFromWorkList();
12365 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012366
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012367 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012368 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012369 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012370 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012371 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012372 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012373
Bill Wendlingb7427032006-11-26 09:46:52 +000012374 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012375
12376 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012377 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012378 continue;
12379 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012380
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012381 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012382 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012383 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012384
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012385 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012386 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012387 ReplaceInstUsesWith(*I, C);
12388
Chris Lattner62b14df2002-09-02 04:59:56 +000012389 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012390 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012391 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012392 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012393 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012394
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012395 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12396 // See if we can constant fold its operands.
12397 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12398 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12399 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12400 i->set(NewC);
12401 }
12402 }
12403 }
12404
Chris Lattnerea1c4542004-12-08 23:43:58 +000012405 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012406 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012407 BasicBlock *BB = I->getParent();
12408 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12409 if (UserParent != BB) {
12410 bool UserIsSuccessor = false;
12411 // See if the user is one of our successors.
12412 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12413 if (*SI == UserParent) {
12414 UserIsSuccessor = true;
12415 break;
12416 }
12417
12418 // If the user is one of our immediate successors, and if that successor
12419 // only has us as a predecessors (we'd have to split the critical edge
12420 // otherwise), we can keep going.
12421 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12422 next(pred_begin(UserParent)) == pred_end(UserParent))
12423 // Okay, the CFG is simple enough, try to sink this instruction.
12424 Changed |= TryToSinkInstruction(I, UserParent);
12425 }
12426 }
12427
Chris Lattner8a2a3112001-12-14 16:52:21 +000012428 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012429#ifndef NDEBUG
12430 std::string OrigI;
12431#endif
12432 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012433 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012434 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012435 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012436 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012437 DOUT << "IC: Old = " << *I
12438 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012439
Chris Lattnerf523d062004-06-09 05:08:07 +000012440 // Everything uses the new instruction now.
12441 I->replaceAllUsesWith(Result);
12442
12443 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012444 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012445 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012446
Chris Lattner6934a042007-02-11 01:23:03 +000012447 // Move the name to the new instruction first.
12448 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012449
12450 // Insert the new instruction into the basic block...
12451 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012452 BasicBlock::iterator InsertPos = I;
12453
12454 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12455 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12456 ++InsertPos;
12457
12458 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012459
Chris Lattner00d51312004-05-01 23:27:23 +000012460 // Make sure that we reprocess all operands now that we reduced their
12461 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012462 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012463
Chris Lattnerf523d062004-06-09 05:08:07 +000012464 // Instructions can end up on the worklist more than once. Make sure
12465 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012466 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012467
12468 // Erase the old instruction.
12469 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012470 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012471#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012472 DOUT << "IC: Mod = " << OrigI
12473 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012474#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012475
Chris Lattner90ac28c2002-08-02 19:29:35 +000012476 // If the instruction was modified, it's possible that it is now dead.
12477 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012478 if (isInstructionTriviallyDead(I)) {
12479 // Make sure we process all operands now that we are reducing their
12480 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012481 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012482
Chris Lattner00d51312004-05-01 23:27:23 +000012483 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012484 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012485 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012486 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012487 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012488 AddToWorkList(I);
12489 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012490 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012491 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012492 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012493 }
12494 }
12495
Chris Lattnerec9c3582007-03-03 02:04:50 +000012496 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012497
12498 // Do an explicit clear, this shrinks the map if needed.
12499 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012500 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012501}
12502
Chris Lattnerec9c3582007-03-03 02:04:50 +000012503
12504bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012505 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12506
Chris Lattnerec9c3582007-03-03 02:04:50 +000012507 bool EverMadeChange = false;
12508
12509 // Iterate while there is work to do.
12510 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012511 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012512 EverMadeChange = true;
12513 return EverMadeChange;
12514}
12515
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012516FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012517 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012518}