blob: 97af83f4e5de11ba61306ed5073043f830ce8552 [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
306 // EraseInstFromFunction - When dealing with an instruction that has side
307 // effects or produces a void value, we can't rely on DCE to delete the
308 // instruction. Instead, visit methods should return the value returned by
309 // this function.
310 Instruction *EraseInstFromFunction(Instruction &I) {
311 assert(I.use_empty() && "Cannot erase instruction that is used!");
312 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000313 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000314 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 return 0; // Don't do anything with FI
316 }
Chris Lattner173234a2008-06-02 01:18:21 +0000317
318 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319 APInt &KnownOne, unsigned Depth = 0) const {
320 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321 }
322
323 bool MaskedValueIsZero(Value *V, const APInt &Mask,
324 unsigned Depth = 0) const {
325 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326 }
327 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328 return llvm::ComputeNumSignBits(Op, TD, Depth);
329 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000330
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000331 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000332
Reid Spencere4d87aa2006-12-23 06:05:41 +0000333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000335 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000336
Reid Spencere4d87aa2006-12-23 06:05:41 +0000337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Chris Lattner886ab6c2009-01-31 08:15:18 +0000341 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342 /// based on the demanded bits.
343 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth);
346 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000347 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000348 unsigned Depth=0);
349
350 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351 /// SimplifyDemandedBits knows about. See if the instruction has any
352 /// properties that allow us to simplify its operands.
353 bool SimplifyDemandedInstructionBits(Instruction &Inst);
354
Evan Cheng388df622009-02-03 10:05:09 +0000355 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
356 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000357
Chris Lattner4e998b22004-09-29 05:07:12 +0000358 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359 // PHI node as operand #0, see if we can fold the instruction into the PHI
360 // (which is only possible if all operands to the PHI are constants).
361 Instruction *FoldOpIntoPhi(Instruction &I);
362
Chris Lattnerbac32862004-11-14 19:13:23 +0000363 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364 // operator and they all are only used by the PHI, PHI together their
365 // inputs, and do the operation once, to the result of the PHI.
366 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000367 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000368 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
Chris Lattner7da52b22006-11-01 04:51:18 +0000370
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000371 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000373
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000374 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000375 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000376 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000377 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000378 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000379 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000380 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000381 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000382 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000383
Chris Lattnerafe91a52006-06-15 19:07:26 +0000384
Reid Spencerc55b2432006-12-13 18:21:21 +0000385 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000386
Dan Gohmaneee962e2008-04-10 18:43:06 +0000387 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000388 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000389 unsigned GetOrEnforceKnownAlignment(Value *V,
390 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000391
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000392 };
393}
394
Dan Gohman844731a2008-05-13 00:00:25 +0000395char InstCombiner::ID = 0;
396static RegisterPass<InstCombiner>
397X("instcombine", "Combine redundant instructions");
398
Chris Lattner4f98c562003-03-10 21:43:22 +0000399// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000400// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000401static unsigned getComplexity(Value *V) {
402 if (isa<Instruction>(V)) {
403 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000404 return 3;
405 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000406 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000407 if (isa<Argument>(V)) return 3;
408 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000409}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000410
Chris Lattnerc8802d22003-03-11 00:12:48 +0000411// isOnlyUse - Return true if this instruction will be deleted if we stop using
412// it.
413static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000414 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000415}
416
Chris Lattner4cb170c2004-02-23 06:38:22 +0000417// getPromotedType - Return the specified type promoted as it would be to pass
418// though a va_arg area...
419static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000420 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421 if (ITy->getBitWidth() < 32)
422 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000423 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000424 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000425}
426
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000427/// getBitCastOperand - If the specified operand is a CastInst, a constant
428/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000430static Value *getBitCastOperand(Value *V) {
431 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000432 // BitCastInst?
Chris Lattnereed48272005-09-13 00:40:14 +0000433 return I->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000434 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435 // GetElementPtrInst?
436 if (GEP->hasAllZeroIndices())
437 return GEP->getOperand(0);
438 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Reid Spencer3da59db2006-11-27 01:05:10 +0000439 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000440 // BitCast ConstantExp?
Chris Lattnereed48272005-09-13 00:40:14 +0000441 return CE->getOperand(0);
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000442 else if (CE->getOpcode() == Instruction::GetElementPtr) {
443 // GetElementPtr ConstantExp?
444 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445 I != E; ++I) {
446 ConstantInt *CI = dyn_cast<ConstantInt>(I);
447 if (!CI || !CI->isZero())
448 // Any non-zero indices? Not cast-like.
449 return 0;
450 }
451 // All-zero indices? This is just like casting.
452 return CE->getOperand(0);
453 }
454 }
Chris Lattnereed48272005-09-13 00:40:14 +0000455 return 0;
456}
457
Reid Spencer3da59db2006-11-27 01:05:10 +0000458/// This function is a wrapper around CastInst::isEliminableCastPair. It
459/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000460static Instruction::CastOps
461isEliminableCastPair(
462 const CastInst *CI, ///< The first cast instruction
463 unsigned opcode, ///< The opcode of the second cast instruction
464 const Type *DstTy, ///< The target type for the second cast instruction
465 TargetData *TD ///< The target data for pointer size
466) {
467
468 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
469 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000470
Reid Spencer3da59db2006-11-27 01:05:10 +0000471 // Get the opcodes of the two Cast instructions
472 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000474
Reid Spencer3da59db2006-11-27 01:05:10 +0000475 return Instruction::CastOps(
476 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000478}
479
480/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481/// in any code being generated. It does not require codegen if V is simple
482/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000483static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
484 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000485 if (V->getType() == Ty || isa<Constant>(V)) return false;
486
Chris Lattner01575b72006-05-25 23:24:33 +0000487 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000488 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000489 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000490 return false;
491 return true;
492}
493
Chris Lattner4f98c562003-03-10 21:43:22 +0000494// SimplifyCommutative - This performs a few simplifications for commutative
495// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000496//
Chris Lattner4f98c562003-03-10 21:43:22 +0000497// 1. Order operands such that they are listed from right (least complex) to
498// left (most complex). This puts constants before unary operators before
499// binary operators.
500//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000501// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000503//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000505 bool Changed = false;
506 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000508
Chris Lattner4f98c562003-03-10 21:43:22 +0000509 if (!I.isAssociative()) return Changed;
510 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000511 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000514 Constant *Folded = ConstantExpr::get(I.getOpcode(),
515 cast<Constant>(I.getOperand(1)),
516 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 I.setOperand(0, Op->getOperand(0));
518 I.setOperand(1, Folded);
519 return true;
520 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522 isOnlyUse(Op) && isOnlyUse(Op1)) {
523 Constant *C1 = cast<Constant>(Op->getOperand(1));
524 Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000527 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000528 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000529 Op1->getOperand(0),
530 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000531 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000532 I.setOperand(0, New);
533 I.setOperand(1, Folded);
534 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000535 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000536 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000537 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000538}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000539
Reid Spencere4d87aa2006-12-23 06:05:41 +0000540/// SimplifyCompare - For a CmpInst this function just orders the operands
541/// so that theyare listed from right (least complex) to left (most complex).
542/// This puts constants before unary operators before binary operators.
543bool InstCombiner::SimplifyCompare(CmpInst &I) {
544 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545 return false;
546 I.swapOperands();
547 // Compare instructions are not associative so there's nothing else we can do.
548 return true;
549}
550
Chris Lattner8d969642003-03-10 23:06:50 +0000551// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000553//
Chris Lattner8d969642003-03-10 23:06:50 +0000554static inline Value *dyn_castNegVal(Value *V) {
555 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000556 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000557
Chris Lattner0ce85802004-12-14 20:08:06 +0000558 // Constants can be considered to be negated values if they can be folded.
559 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000561
562 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563 if (C->getType()->getElementType()->isInteger())
564 return ConstantExpr::getNeg(C);
565
Chris Lattner8d969642003-03-10 23:06:50 +0000566 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000567}
568
Chris Lattner8d969642003-03-10 23:06:50 +0000569static inline Value *dyn_castNotVal(Value *V) {
570 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000571 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000572
573 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000574 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000575 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000576 return 0;
577}
578
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579// dyn_castFoldableMul - If this value is a multiply that can be folded into
580// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000581// non-constant operand of the multiply, and set CST to point to the multiplier.
582// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000583//
Chris Lattner50af16a2004-11-13 19:50:12 +0000584static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000585 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000586 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000587 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000588 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000589 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000590 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000591 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000592 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000593 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000594 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000595 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000596 return I->getOperand(0);
597 }
598 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000599 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000600}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000601
Chris Lattner574da9b2005-01-13 20:14:25 +0000602/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603/// expression, return it.
604static User *dyn_castGetElementPtr(Value *V) {
605 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607 if (CE->getOpcode() == Instruction::GetElementPtr)
608 return cast<User>(V);
609 return false;
610}
611
Dan Gohmaneee962e2008-04-10 18:43:06 +0000612/// getOpcode - If this is an Instruction or a ConstantExpr, return the
613/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000614static unsigned getOpcode(const Value *V) {
615 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000616 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000617 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000618 return CE->getOpcode();
619 // Use UserOp1 to mean there's no opcode.
620 return Instruction::UserOp1;
621}
622
Reid Spencer7177c3a2007-03-25 05:33:51 +0000623/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000624static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000625 APInt Val(C->getValue());
626 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000627}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000628/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000629static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000630 APInt Val(C->getValue());
631 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000632}
633/// Add - Add two ConstantInts together
634static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() + C2->getValue());
636}
637/// And - Bitwise AND two ConstantInts together
638static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() & C2->getValue());
640}
641/// Subtract - Subtract one ConstantInt from another
642static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() - C2->getValue());
644}
645/// Multiply - Multiply two ConstantInts together
646static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000648}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000649/// MultiplyOverflows - True if the multiply can not be expressed in an int
650/// this size.
651static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652 uint32_t W = C1->getBitWidth();
653 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654 if (sign) {
655 LHSExt.sext(W * 2);
656 RHSExt.sext(W * 2);
657 } else {
658 LHSExt.zext(W * 2);
659 RHSExt.zext(W * 2);
660 }
661
662 APInt MulExt = LHSExt * RHSExt;
663
664 if (sign) {
665 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667 return MulExt.slt(Min) || MulExt.sgt(Max);
668 } else
669 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670}
Chris Lattner955f3312004-09-28 21:48:02 +0000671
Reid Spencere7816b52007-03-08 01:52:58 +0000672
Chris Lattner255d8912006-02-11 09:31:47 +0000673/// ShrinkDemandedConstant - Check to see if the specified operand of the
674/// specified instruction is a constant integer. If so, check to see if there
675/// are any bits set in the constant that are not demanded. If so, shrink the
676/// constant and return true.
677static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000678 APInt Demanded) {
679 assert(I && "No instruction?");
680 assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682 // If the operand is not a constant integer, nothing to do.
683 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684 if (!OpC) return false;
685
686 // If there are no bits set that aren't demanded, nothing to do.
687 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688 if ((~Demanded & OpC->getValue()) == 0)
689 return false;
690
691 // This instruction is producing bits that are not demanded. Shrink the RHS.
692 Demanded &= OpC->getValue();
693 I->setOperand(OpNo, ConstantInt::get(Demanded));
694 return true;
695}
696
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000697// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
698// set of known zero and one bits, compute the maximum and minimum values that
699// could have the specified known zero and known one bits, returning them in
700// min/max.
701static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000702 const APInt& KnownZero,
703 const APInt& KnownOne,
704 APInt& Min, APInt& Max) {
705 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706 assert(KnownZero.getBitWidth() == BitWidth &&
707 KnownOne.getBitWidth() == BitWidth &&
708 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000710 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000711
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713 // bit if it is unknown.
714 Min = KnownOne;
715 Max = KnownOne|UnknownBits;
716
Zhou Sheng4acf1552007-03-28 05:15:57 +0000717 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000718 Min.set(BitWidth-1);
719 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721}
722
723// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724// a set of known zero and one bits, compute the maximum and minimum values that
725// could have the specified known zero and known one bits, returning them in
726// min/max.
727static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000728 const APInt &KnownZero,
729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
731 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000732 assert(KnownZero.getBitWidth() == BitWidth &&
733 KnownOne.getBitWidth() == BitWidth &&
734 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000736 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000737
738 // The minimum value is when the unknown bits are all zeros.
739 Min = KnownOne;
740 // The maximum value is when the unknown bits are all ones.
741 Max = KnownOne|UnknownBits;
742}
Chris Lattner255d8912006-02-11 09:31:47 +0000743
Chris Lattner886ab6c2009-01-31 08:15:18 +0000744/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745/// SimplifyDemandedBits knows about. See if the instruction has any
746/// properties that allow us to simplify its operands.
747bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748 unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751
752 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
753 KnownZero, KnownOne, 0);
754 if (V == 0) return false;
755 if (V == &Inst) return true;
756 ReplaceInstUsesWith(Inst, V);
757 return true;
758}
759
760/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761/// specified instruction operand if possible, updating it in place. It returns
762/// true if it made any change and false otherwise.
763bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
764 APInt &KnownZero, APInt &KnownOne,
765 unsigned Depth) {
766 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767 KnownZero, KnownOne, Depth);
768 if (NewVal == 0) return false;
769 U.set(NewVal);
770 return true;
771}
772
773
774/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000776/// that only the bits set in DemandedMask of the result of V are ever used
777/// downstream. Consequently, depending on the mask and V, it may be possible
778/// to replace V with a constant or one of its operands. In such cases, this
779/// function does the replacement and returns true. In all other cases, it
780/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000781/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000782/// to be zero in the expression. These are provided to potentially allow the
783/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784/// the expression. KnownOne and KnownZero always follow the invariant that
785/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786/// the bits in KnownOne and KnownZero may only be accurate for those bits set
787/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000789///
790/// This returns null if it did not change anything and it permits no
791/// simplification. This returns V itself if it did some simplification of V's
792/// operands based on the information about what bits are demanded. This returns
793/// some other non-null value if it found out that V is equal to another value
794/// in the context where the specified bits are demanded, but not for all users.
795Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796 APInt &KnownZero, APInt &KnownOne,
797 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000798 assert(V != 0 && "Null pointer of Value???");
799 assert(Depth <= 6 && "Limit Search Depth");
800 uint32_t BitWidth = DemandedMask.getBitWidth();
801 const IntegerType *VTy = cast<IntegerType>(V->getType());
802 assert(VTy->getBitWidth() == BitWidth &&
803 KnownZero.getBitWidth() == BitWidth &&
804 KnownOne.getBitWidth() == BitWidth &&
805 "Value *V, DemandedMask, KnownZero and KnownOne \
806 must have same BitWidth");
807 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808 // We know all of the bits for a constant!
809 KnownOne = CI->getValue() & DemandedMask;
810 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000811 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000812 }
813
Chris Lattner08d2cc72009-01-31 07:26:06 +0000814 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000815 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000816 if (DemandedMask == 0) { // Not demanding any bits from V.
817 if (isa<UndefValue>(V))
818 return 0;
819 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 }
821
Chris Lattner4598c942009-01-31 08:24:16 +0000822 if (Depth == 6) // Limit search depth.
823 return 0;
824
Reid Spencer8cb68342007-03-12 17:25:59 +0000825 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattner886ab6c2009-01-31 08:15:18 +0000826 if (!I) return 0; // Only analyze instructions.
Chris Lattner4598c942009-01-31 08:24:16 +0000827
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000828 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
829 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
830
Chris Lattner4598c942009-01-31 08:24:16 +0000831 // If there are multiple uses of this value and we aren't at the root, then
832 // we can't do any simplifications of the operands, because DemandedMask
833 // only reflects the bits demanded by *one* of the users.
834 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000835 // Despite the fact that we can't simplify this instruction in all User's
836 // context, we can at least compute the knownzero/knownone bits, and we can
837 // do simplifications that apply to *just* the one user if we know that
838 // this instruction has a simpler value in that context.
839 if (I->getOpcode() == Instruction::And) {
840 // If either the LHS or the RHS are Zero, the result is zero.
841 ComputeMaskedBits(I->getOperand(1), DemandedMask,
842 RHSKnownZero, RHSKnownOne, Depth+1);
843 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
844 LHSKnownZero, LHSKnownOne, Depth+1);
845
846 // If all of the demanded bits are known 1 on one side, return the other.
847 // These bits cannot contribute to the result of the 'and' in this
848 // context.
849 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
850 (DemandedMask & ~LHSKnownZero))
851 return I->getOperand(0);
852 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
853 (DemandedMask & ~RHSKnownZero))
854 return I->getOperand(1);
855
856 // If all of the demanded bits in the inputs are known zeros, return zero.
857 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
858 return Constant::getNullValue(VTy);
859
860 } else if (I->getOpcode() == Instruction::Or) {
861 // We can simplify (X|Y) -> X or Y in the user's context if we know that
862 // only bits from X or Y are demanded.
863
864 // If either the LHS or the RHS are One, the result is One.
865 ComputeMaskedBits(I->getOperand(1), DemandedMask,
866 RHSKnownZero, RHSKnownOne, Depth+1);
867 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
868 LHSKnownZero, LHSKnownOne, Depth+1);
869
870 // If all of the demanded bits are known zero on one side, return the
871 // other. These bits cannot contribute to the result of the 'or' in this
872 // context.
873 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
874 (DemandedMask & ~LHSKnownOne))
875 return I->getOperand(0);
876 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
877 (DemandedMask & ~RHSKnownOne))
878 return I->getOperand(1);
879
880 // If all of the potentially set bits on one side are known to be set on
881 // the other side, just use the 'other' side.
882 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
883 (DemandedMask & (~RHSKnownZero)))
884 return I->getOperand(0);
885 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
886 (DemandedMask & (~LHSKnownZero)))
887 return I->getOperand(1);
888 }
889
Chris Lattner4598c942009-01-31 08:24:16 +0000890 // Compute the KnownZero/KnownOne bits to simplify things downstream.
891 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
892 return 0;
893 }
894
895 // If this is the root being simplified, allow it to have multiple uses,
896 // just set the DemandedMask to all bits so that we can try to simplify the
897 // operands. This allows visitTruncInst (for example) to simplify the
898 // operand of a trunc without duplicating all the logic below.
899 if (Depth == 0 && !V->hasOneUse())
900 DemandedMask = APInt::getAllOnesValue(BitWidth);
901
Reid Spencer8cb68342007-03-12 17:25:59 +0000902 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000903 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000904 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000905 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000906 case Instruction::And:
907 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000908 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
909 RHSKnownZero, RHSKnownOne, Depth+1) ||
910 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000911 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000912 return I;
913 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
914 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000915
916 // If all of the demanded bits are known 1 on one side, return the other.
917 // These bits cannot contribute to the result of the 'and'.
918 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
919 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000921 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
922 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000923 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000924
925 // If all of the demanded bits in the inputs are known zeros, return zero.
926 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000927 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000928
929 // If the RHS is a constant, see if we can simplify it.
930 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000931 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000932
933 // Output known-1 bits are only known if set in both the LHS & RHS.
934 RHSKnownOne &= LHSKnownOne;
935 // Output known-0 are known to be clear if zero in either the LHS | RHS.
936 RHSKnownZero |= LHSKnownZero;
937 break;
938 case Instruction::Or:
939 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
941 RHSKnownZero, RHSKnownOne, Depth+1) ||
942 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000943 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 return I;
945 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
946 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000947
948 // If all of the demanded bits are known zero on one side, return the other.
949 // These bits cannot contribute to the result of the 'or'.
950 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
951 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
954 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000956
957 // If all of the potentially set bits on one side are known to be set on
958 // the other side, just use the 'other' side.
959 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
960 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000962 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
963 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000965
966 // If the RHS is a constant, see if we can simplify it.
967 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000968 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000969
970 // Output known-0 bits are only known if clear in both the LHS & RHS.
971 RHSKnownZero &= LHSKnownZero;
972 // Output known-1 are known to be set if set in either the LHS | RHS.
973 RHSKnownOne |= LHSKnownOne;
974 break;
975 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
977 RHSKnownZero, RHSKnownOne, Depth+1) ||
978 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000979 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I;
981 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
982 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000983
984 // If all of the demanded bits are known zero on one side, return the other.
985 // These bits cannot contribute to the result of the 'xor'.
986 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // Output known-0 bits are known if clear or set in both the LHS & RHS.
992 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
993 (RHSKnownOne & LHSKnownOne);
994 // Output known-1 are known to be set if set in only one of the LHS, RHS.
995 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
996 (RHSKnownOne & LHSKnownZero);
997
998 // If all of the demanded bits are known to be zero on one side or the
999 // other, turn this into an *inclusive* or.
1000 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1001 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1002 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001003 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001004 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001005 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001006 }
1007
1008 // If all of the demanded bits on one side are known, and all of the set
1009 // bits on that side are also known to be set on the other side, turn this
1010 // into an AND, as we know the bits will be cleared.
1011 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1012 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1013 // all known
1014 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1015 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1016 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001017 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 }
1020 }
1021
1022 // If the RHS is a constant, see if we can simplify it.
1023 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1024 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001025 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001026
1027 RHSKnownZero = KnownZeroOut;
1028 RHSKnownOne = KnownOneOut;
1029 break;
1030 }
1031 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001032 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1033 RHSKnownZero, RHSKnownOne, Depth+1) ||
1034 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001035 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 return I;
1037 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1038 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001039
1040 // If the operands are constants, see if we can simplify them.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1042 ShrinkDemandedConstant(I, 2, DemandedMask))
1043 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001044
1045 // Only known if known in both the LHS and RHS.
1046 RHSKnownOne &= LHSKnownOne;
1047 RHSKnownZero &= LHSKnownZero;
1048 break;
1049 case Instruction::Trunc: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001051 DemandedMask.zext(truncBf);
1052 RHSKnownZero.zext(truncBf);
1053 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001055 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 DemandedMask.trunc(BitWidth);
1058 RHSKnownZero.trunc(BitWidth);
1059 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001061 break;
1062 }
1063 case Instruction::BitCast:
1064 if (!I->getOperand(0)->getType()->isInteger())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 return false; // vector->int or fp->int?
1066 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001067 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001068 return I;
1069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 break;
1071 case Instruction::ZExt: {
1072 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001073 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001074
Zhou Shengd48653a2007-03-29 04:45:55 +00001075 DemandedMask.trunc(SrcBitWidth);
1076 RHSKnownZero.trunc(SrcBitWidth);
1077 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001079 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001080 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001081 DemandedMask.zext(BitWidth);
1082 RHSKnownZero.zext(BitWidth);
1083 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001085 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001086 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001087 break;
1088 }
1089 case Instruction::SExt: {
1090 // Compute the bits in the result that are not present in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001092
Reid Spencer8cb68342007-03-12 17:25:59 +00001093 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001094 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001095
Zhou Sheng01542f32007-03-29 02:26:30 +00001096 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 // If any of the sign extended bits are demanded, we know that the sign
1098 // bit is demanded.
1099 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001100 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001101
Zhou Shengd48653a2007-03-29 04:45:55 +00001102 InputDemandedBits.trunc(SrcBitWidth);
1103 RHSKnownZero.trunc(SrcBitWidth);
1104 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001105 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001106 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 InputDemandedBits.zext(BitWidth);
1109 RHSKnownZero.zext(BitWidth);
1110 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
1113 // If the sign bit of the input is known set or clear, then we know the
1114 // top bits of the result.
1115
1116 // If the input sign bit is known zero, or if the NewBits are not demanded
1117 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001118 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1121 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 }
1125 break;
1126 }
1127 case Instruction::Add: {
1128 // Figure out what the input bits are. If the top bits of the and result
1129 // are not demanded, then the add doesn't demand them from its input
1130 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001131 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001132
1133 // If there is a constant on the RHS, there are a variety of xformations
1134 // we can do.
1135 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1136 // If null, this should be simplified elsewhere. Some of the xforms here
1137 // won't work if the RHS is zero.
1138 if (RHS->isZero())
1139 break;
1140
1141 // If the top bit of the output is demanded, demand everything from the
1142 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001143 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001144
1145 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001146 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001149
1150 // If the RHS of the add has bits set that can't affect the input, reduce
1151 // the constant.
1152 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // Avoid excess work.
1156 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1157 break;
1158
1159 // Turn it into OR if input bits are zero.
1160 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1161 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001162 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 }
1166
1167 // We can say something about the output known-zero and known-one bits,
1168 // depending on potential carries from the input constant and the
1169 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1170 // bits set and the RHS constant is 0x01001, then we know we have a known
1171 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1172
1173 // To compute this, we first compute the potential carry bits. These are
1174 // the bits which may be modified. I'm not aware of a better way to do
1175 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001176 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001177 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001178
1179 // Now that we know which bits have carries, compute the known-1/0 sets.
1180
1181 // Bits are known one if they are known zero in one operand and one in the
1182 // other, and there is no input carry.
1183 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1184 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1185
1186 // Bits are known zero if they are known zero in both operands and there
1187 // is no input carry.
1188 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1189 } else {
1190 // If the high-bits of this ADD are not demanded, then it does not demand
1191 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001192 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 // Right fill the mask of bits for this ADD to demand the most
1194 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001195 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001196 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1197 LHSKnownZero, LHSKnownOne, Depth+1) ||
1198 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 }
1202 }
1203 break;
1204 }
1205 case Instruction::Sub:
1206 // If the high-bits of this SUB are not demanded, then it does not demand
1207 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 // Right fill the mask of bits for this SUB to demand the most
1210 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001211 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001212 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1214 LHSKnownZero, LHSKnownOne, Depth+1) ||
1215 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001217 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001219 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1220 // the known zeros and ones.
1221 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 break;
1223 case Instruction::Shl:
1224 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001225 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 return I;
1230 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 RHSKnownZero <<= ShiftAmt;
1232 RHSKnownOne <<= ShiftAmt;
1233 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001234 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001235 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 }
1237 break;
1238 case Instruction::LShr:
1239 // For a logical shift right
1240 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001241 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001242
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001247 return I;
1248 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001249 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1250 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001251 if (ShiftAmt) {
1252 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001253 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001254 RHSKnownZero |= HighBits; // high bits known zero.
1255 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 }
1257 break;
1258 case Instruction::AShr:
1259 // If this is an arithmetic shift right and only the low-bit is set, we can
1260 // always convert this into a logical shr, even if the shift amount is
1261 // variable. The low bit of the shift cannot be an input sign bit unless
1262 // the shift amount is >= the size of the datatype, which is undefined.
1263 if (DemandedMask == 1) {
1264 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001265 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001269
1270 // If the sign bit is the only bit demanded by this ashr, then there is no
1271 // need to do it, the shift doesn't change the high bit.
1272 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001274
1275 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001276 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001277
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001279 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001280 // If any of the "high bits" are demanded, we should set the sign bit as
1281 // demanded.
1282 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1283 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 return I;
1287 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1291 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1292
1293 // Handle the sign bits.
1294 APInt SignBit(APInt::getSignBit(BitWidth));
1295 // Adjust to where it is now in the mask.
1296 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1297
1298 // If the input sign bit is known to be zero, or if none of the top bits
1299 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001300 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 (HighBits & ~DemandedMask) == HighBits) {
1302 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001303 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001306 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1307 RHSKnownOne |= HighBits;
1308 }
1309 }
1310 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001311 case Instruction::SRem:
1312 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001313 APInt RA = Rem->getValue().abs();
1314 if (RA.isPowerOf2()) {
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001315 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001317
Nick Lewycky8e394322008-11-02 02:41:50 +00001318 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001319 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001320 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001321 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001323
1324 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1325 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001326
1327 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001328
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001330 }
1331 }
1332 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001333 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001334 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1335 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1337 KnownZero2, KnownOne2, Depth+1) ||
1338 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001339 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001340 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001341
Chris Lattner455e9ab2009-01-21 18:09:24 +00001342 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001343 Leaders = std::max(Leaders,
1344 KnownZero2.countLeadingOnes());
1345 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001348 case Instruction::Call:
1349 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1350 switch (II->getIntrinsicID()) {
1351 default: break;
1352 case Intrinsic::bswap: {
1353 // If the only bits demanded come from one byte of the bswap result,
1354 // just shift the input byte into position to eliminate the bswap.
1355 unsigned NLZ = DemandedMask.countLeadingZeros();
1356 unsigned NTZ = DemandedMask.countTrailingZeros();
1357
1358 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1359 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1360 // have 14 leading zeros, round to 8.
1361 NLZ &= ~7;
1362 NTZ &= ~7;
1363 // If we need exactly one byte, we can do this transformation.
1364 if (BitWidth-NLZ-NTZ == 8) {
1365 unsigned ResultBit = NTZ;
1366 unsigned InputBit = BitWidth-NTZ-8;
1367
1368 // Replace this with either a left or right shift to get the byte into
1369 // the right place.
1370 Instruction *NewVal;
1371 if (InputBit > ResultBit)
1372 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1373 ConstantInt::get(I->getType(), InputBit-ResultBit));
1374 else
1375 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1376 ConstantInt::get(I->getType(), ResultBit-InputBit));
1377 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001379 }
1380
1381 // TODO: Could compute known zero/one bits based on the input.
1382 break;
1383 }
1384 }
1385 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001386 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001387 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001388 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001389
1390 // If the client is only demanding bits that we know, return the known
1391 // constant.
1392 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001393 return ConstantInt::get(RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001394 return false;
1395}
1396
Chris Lattner867b99f2006-10-05 06:55:50 +00001397
Mon P Wangaeb06d22008-11-10 04:46:22 +00001398/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001399/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001400/// actually used by the caller. This method analyzes which elements of the
1401/// operand are undef and returns that information in UndefElts.
1402///
1403/// If the information about demanded elements can be used to simplify the
1404/// operation, the operation is simplified, then the resultant value is
1405/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001406Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1407 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001408 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001409 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001410 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001411 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001412
1413 if (isa<UndefValue>(V)) {
1414 // If the entire vector is undefined, just return this info.
1415 UndefElts = EltMask;
1416 return 0;
1417 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1418 UndefElts = EltMask;
1419 return UndefValue::get(V->getType());
1420 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001421
Chris Lattner867b99f2006-10-05 06:55:50 +00001422 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001423 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1424 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001425 Constant *Undef = UndefValue::get(EltTy);
1426
1427 std::vector<Constant*> Elts;
1428 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001429 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001430 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001431 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001432 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1433 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001434 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001435 } else { // Otherwise, defined.
1436 Elts.push_back(CP->getOperand(i));
1437 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001438
Chris Lattner867b99f2006-10-05 06:55:50 +00001439 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001440 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001441 return NewCP != CP ? NewCP : 0;
1442 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001443 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001444 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001445
1446 // Check if this is identity. If so, return 0 since we are not simplifying
1447 // anything.
1448 if (DemandedElts == ((1ULL << VWidth) -1))
1449 return 0;
1450
Reid Spencer9d6565a2007-02-15 02:26:10 +00001451 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001452 Constant *Zero = Constant::getNullValue(EltTy);
1453 Constant *Undef = UndefValue::get(EltTy);
1454 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001455 for (unsigned i = 0; i != VWidth; ++i) {
1456 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1457 Elts.push_back(Elt);
1458 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001459 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001460 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001461 }
1462
Dan Gohman488fbfc2008-09-09 18:11:14 +00001463 // Limit search depth.
1464 if (Depth == 10)
1465 return false;
1466
1467 // If multiple users are using the root value, procede with
1468 // simplification conservatively assuming that all elements
1469 // are needed.
1470 if (!V->hasOneUse()) {
1471 // Quit if we find multiple users of a non-root value though.
1472 // They'll be handled when it's their turn to be visited by
1473 // the main instcombine process.
1474 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 // TODO: Just compute the UndefElts information recursively.
1476 return false;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001477
1478 // Conservatively assume that all elements are needed.
1479 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001480 }
1481
1482 Instruction *I = dyn_cast<Instruction>(V);
1483 if (!I) return false; // Only analyze instructions.
1484
1485 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001486 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 Value *TmpV;
1488 switch (I->getOpcode()) {
1489 default: break;
1490
1491 case Instruction::InsertElement: {
1492 // If this is a variable index, we don't know which element it overwrites.
1493 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001494 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001495 if (Idx == 0) {
1496 // Note that we can't propagate undef elt info, because we don't know
1497 // which elt is getting updated.
1498 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1499 UndefElts2, Depth+1);
1500 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1501 break;
1502 }
1503
1504 // If this is inserting an element that isn't demanded, remove this
1505 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001506 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng388df622009-02-03 10:05:09 +00001507 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Chris Lattner867b99f2006-10-05 06:55:50 +00001508 return AddSoonDeadInstToWorklist(*I, 0);
1509
1510 // Otherwise, the element inserted overwrites whatever was there, so the
1511 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001512 APInt DemandedElts2 = DemandedElts;
1513 DemandedElts2.clear(IdxNo);
1514 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001515 UndefElts, Depth+1);
1516 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517
1518 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001519 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001520 break;
1521 }
1522 case Instruction::ShuffleVector: {
1523 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001524 uint64_t LHSVWidth =
1525 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001526 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001527 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001528 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001529 unsigned MaskVal = Shuffle->getMaskValue(i);
1530 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001531 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001532 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001533 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001534 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001535 else
Evan Cheng388df622009-02-03 10:05:09 +00001536 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001537 }
1538 }
1539 }
1540
1541 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1542 UndefElts2, Depth+1);
1543 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544
Evan Cheng388df622009-02-03 10:05:09 +00001545 APInt UndefElts3(VWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001546 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1547 UndefElts3, Depth+1);
1548 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1549
1550 bool NewUndefElts = false;
1551 for (unsigned i = 0; i < VWidth; i++) {
1552 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001553 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001554 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001555 } else if (MaskVal < LHSVWidth) {
Evan Cheng388df622009-02-03 10:05:09 +00001556 if (UndefElts2[MaskVal]) {
1557 NewUndefElts = true;
1558 UndefElts.set(i);
1559 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001561 if (UndefElts3[MaskVal - LHSVWidth]) {
1562 NewUndefElts = true;
1563 UndefElts.set(i);
1564 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 }
1566 }
1567
1568 if (NewUndefElts) {
1569 // Add additional discovered undefs.
1570 std::vector<Constant*> Elts;
1571 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001572 if (UndefElts[i])
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 Elts.push_back(UndefValue::get(Type::Int32Ty));
1574 else
1575 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1576 Shuffle->getMaskValue(i)));
1577 }
1578 I->setOperand(2, ConstantVector::get(Elts));
1579 MadeChange = true;
1580 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001581 break;
1582 }
Chris Lattner69878332007-04-14 22:29:23 +00001583 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001584 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001585 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1586 if (!VTy) break;
1587 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001588 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001589 unsigned Ratio;
1590
1591 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001592 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001593 // elements as are demanded of us.
1594 Ratio = 1;
1595 InputDemandedElts = DemandedElts;
1596 } else if (VWidth > InVWidth) {
1597 // Untested so far.
1598 break;
1599
1600 // If there are more elements in the result than there are in the source,
1601 // then an input element is live if any of the corresponding output
1602 // elements are live.
1603 Ratio = VWidth/InVWidth;
1604 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001605 if (DemandedElts[OutIdx])
1606 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001607 }
1608 } else {
1609 // Untested so far.
1610 break;
1611
1612 // If there are more elements in the source than there are in the result,
1613 // then an input element is live if the corresponding output element is
1614 // live.
1615 Ratio = InVWidth/VWidth;
1616 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001617 if (DemandedElts[InIdx/Ratio])
1618 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001619 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001620
Chris Lattner69878332007-04-14 22:29:23 +00001621 // div/rem demand all inputs, because they don't want divide by zero.
1622 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1623 UndefElts2, Depth+1);
1624 if (TmpV) {
1625 I->setOperand(0, TmpV);
1626 MadeChange = true;
1627 }
1628
1629 UndefElts = UndefElts2;
1630 if (VWidth > InVWidth) {
1631 assert(0 && "Unimp");
1632 // If there are more elements in the result than there are in the source,
1633 // then an output element is undef if the corresponding input element is
1634 // undef.
1635 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001636 if (UndefElts2[OutIdx/Ratio])
1637 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001638 } else if (VWidth < InVWidth) {
1639 assert(0 && "Unimp");
1640 // If there are more elements in the source than there are in the result,
1641 // then a result element is undef if all of the corresponding input
1642 // elements are undef.
1643 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1644 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001645 if (!UndefElts2[InIdx]) // Not undef?
1646 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001647 }
1648 break;
1649 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001650 case Instruction::And:
1651 case Instruction::Or:
1652 case Instruction::Xor:
1653 case Instruction::Add:
1654 case Instruction::Sub:
1655 case Instruction::Mul:
1656 // div/rem demand all inputs, because they don't want divide by zero.
1657 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1658 UndefElts, Depth+1);
1659 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1660 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1661 UndefElts2, Depth+1);
1662 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1663
1664 // Output elements are undefined if both are undefined. Consider things
1665 // like undef&0. The result is known zero, not undef.
1666 UndefElts &= UndefElts2;
1667 break;
1668
1669 case Instruction::Call: {
1670 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1671 if (!II) break;
1672 switch (II->getIntrinsicID()) {
1673 default: break;
1674
1675 // Binary vector operations that work column-wise. A dest element is a
1676 // function of the corresponding input elements from the two inputs.
1677 case Intrinsic::x86_sse_sub_ss:
1678 case Intrinsic::x86_sse_mul_ss:
1679 case Intrinsic::x86_sse_min_ss:
1680 case Intrinsic::x86_sse_max_ss:
1681 case Intrinsic::x86_sse2_sub_sd:
1682 case Intrinsic::x86_sse2_mul_sd:
1683 case Intrinsic::x86_sse2_min_sd:
1684 case Intrinsic::x86_sse2_max_sd:
1685 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1686 UndefElts, Depth+1);
1687 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1688 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1689 UndefElts2, Depth+1);
1690 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1691
1692 // If only the low elt is demanded and this is a scalarizable intrinsic,
1693 // scalarize it now.
1694 if (DemandedElts == 1) {
1695 switch (II->getIntrinsicID()) {
1696 default: break;
1697 case Intrinsic::x86_sse_sub_ss:
1698 case Intrinsic::x86_sse_mul_ss:
1699 case Intrinsic::x86_sse2_sub_sd:
1700 case Intrinsic::x86_sse2_mul_sd:
1701 // TODO: Lower MIN/MAX/ABS/etc
1702 Value *LHS = II->getOperand(1);
1703 Value *RHS = II->getOperand(2);
1704 // Extract the element as scalars.
1705 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1706 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1707
1708 switch (II->getIntrinsicID()) {
1709 default: assert(0 && "Case stmts out of sync!");
1710 case Intrinsic::x86_sse_sub_ss:
1711 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001712 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001713 II->getName()), *II);
1714 break;
1715 case Intrinsic::x86_sse_mul_ss:
1716 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001717 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001718 II->getName()), *II);
1719 break;
1720 }
1721
1722 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00001723 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1724 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001725 InsertNewInstBefore(New, *II);
1726 AddSoonDeadInstToWorklist(*II, 0);
1727 return New;
1728 }
1729 }
1730
1731 // Output elements are undefined if both are undefined. Consider things
1732 // like undef&0. The result is known zero, not undef.
1733 UndefElts &= UndefElts2;
1734 break;
1735 }
1736 break;
1737 }
1738 }
1739 return MadeChange ? I : 0;
1740}
1741
Dan Gohman45b4e482008-05-19 22:14:15 +00001742
Chris Lattner564a7272003-08-13 19:01:45 +00001743/// AssociativeOpt - Perform an optimization on an associative operator. This
1744/// function is designed to check a chain of associative operators for a
1745/// potential to apply a certain optimization. Since the optimization may be
1746/// applicable if the expression was reassociated, this checks the chain, then
1747/// reassociates the expression as necessary to expose the optimization
1748/// opportunity. This makes use of a special Functor, which must define
1749/// 'shouldApply' and 'apply' methods.
1750///
1751template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00001752static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001753 unsigned Opcode = Root.getOpcode();
1754 Value *LHS = Root.getOperand(0);
1755
1756 // Quick check, see if the immediate LHS matches...
1757 if (F.shouldApply(LHS))
1758 return F.apply(Root);
1759
1760 // Otherwise, if the LHS is not of the same opcode as the root, return.
1761 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001762 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001763 // Should we apply this transform to the RHS?
1764 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1765
1766 // If not to the RHS, check to see if we should apply to the LHS...
1767 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1768 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1769 ShouldApply = true;
1770 }
1771
1772 // If the functor wants to apply the optimization to the RHS of LHSI,
1773 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1774 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001775 // Now all of the instructions are in the current basic block, go ahead
1776 // and perform the reassociation.
1777 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1778
1779 // First move the selected RHS to the LHS of the root...
1780 Root.setOperand(0, LHSI->getOperand(1));
1781
1782 // Make what used to be the LHS of the root be the user of the root...
1783 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001784 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001785 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1786 return 0;
1787 }
Chris Lattner65725312004-04-16 18:08:07 +00001788 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001789 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001790 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001791 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001792 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001793
1794 // Now propagate the ExtraOperand down the chain of instructions until we
1795 // get to LHSI.
1796 while (TmpLHSI != LHSI) {
1797 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001798 // Move the instruction to immediately before the chain we are
1799 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001800 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001801 ARI = NextLHSI;
1802
Chris Lattner564a7272003-08-13 19:01:45 +00001803 Value *NextOp = NextLHSI->getOperand(1);
1804 NextLHSI->setOperand(1, ExtraOperand);
1805 TmpLHSI = NextLHSI;
1806 ExtraOperand = NextOp;
1807 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001808
Chris Lattner564a7272003-08-13 19:01:45 +00001809 // Now that the instructions are reassociated, have the functor perform
1810 // the transformation...
1811 return F.apply(Root);
1812 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001813
Chris Lattner564a7272003-08-13 19:01:45 +00001814 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1815 }
1816 return 0;
1817}
1818
Dan Gohman844731a2008-05-13 00:00:25 +00001819namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001820
Nick Lewycky02d639f2008-05-23 04:34:58 +00001821// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001822struct AddRHS {
1823 Value *RHS;
1824 AddRHS(Value *rhs) : RHS(rhs) {}
1825 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1826 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001827 return BinaryOperator::CreateShl(Add.getOperand(0),
1828 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001829 }
1830};
1831
1832// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1833// iff C1&C2 == 0
1834struct AddMaskingAnd {
1835 Constant *C2;
1836 AddMaskingAnd(Constant *c) : C2(c) {}
1837 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001838 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001839 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001840 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001841 }
1842 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001843 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001844 }
1845};
1846
Dan Gohman844731a2008-05-13 00:00:25 +00001847}
1848
Chris Lattner6e7ba452005-01-01 16:22:27 +00001849static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001850 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001851 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001852 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001853 }
1854
Chris Lattner2eefe512004-04-09 19:05:30 +00001855 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001856 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1857 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001858
Chris Lattner2eefe512004-04-09 19:05:30 +00001859 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1860 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001861 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1862 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001863 }
1864
1865 Value *Op0 = SO, *Op1 = ConstOperand;
1866 if (!ConstIsRHS)
1867 std::swap(Op0, Op1);
1868 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001869 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001870 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001871 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001872 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001873 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001874 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001875 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001876 abort();
1877 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001878 return IC->InsertNewInstBefore(New, I);
1879}
1880
1881// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1882// constant as the other operand, try to fold the binary operator into the
1883// select arguments. This also works for Cast instructions, which obviously do
1884// not have a second operand.
1885static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1886 InstCombiner *IC) {
1887 // Don't modify shared select instructions
1888 if (!SI->hasOneUse()) return 0;
1889 Value *TV = SI->getOperand(1);
1890 Value *FV = SI->getOperand(2);
1891
1892 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001893 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001894 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001895
Chris Lattner6e7ba452005-01-01 16:22:27 +00001896 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1897 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1898
Gabor Greif051a9502008-04-06 20:25:17 +00001899 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1900 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001901 }
1902 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001903}
1904
Chris Lattner4e998b22004-09-29 05:07:12 +00001905
1906/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1907/// node as operand #0, see if we can fold the instruction into the PHI (which
1908/// is only possible if all operands to the PHI are constants).
1909Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1910 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001911 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001912 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001913
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001914 // Check to see if all of the operands of the PHI are constants. If there is
1915 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001916 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001917 BasicBlock *NonConstBB = 0;
1918 for (unsigned i = 0; i != NumPHIValues; ++i)
1919 if (!isa<Constant>(PN->getIncomingValue(i))) {
1920 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001921 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001922 NonConstBB = PN->getIncomingBlock(i);
1923
1924 // If the incoming non-constant value is in I's block, we have an infinite
1925 // loop.
1926 if (NonConstBB == I.getParent())
1927 return 0;
1928 }
1929
1930 // If there is exactly one non-constant value, we can insert a copy of the
1931 // operation in that block. However, if this is a critical edge, we would be
1932 // inserting the computation one some other paths (e.g. inside a loop). Only
1933 // do this if the pred block is unconditionally branching into the phi block.
1934 if (NonConstBB) {
1935 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1936 if (!BI || !BI->isUnconditional()) return 0;
1937 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001938
1939 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001940 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001941 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001942 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001943 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001944
1945 // Next, add all of the operands to the PHI.
1946 if (I.getNumOperands() == 2) {
1947 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001948 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001949 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001950 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001951 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1952 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1953 else
1954 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001955 } else {
1956 assert(PN->getIncomingBlock(i) == NonConstBB);
1957 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001958 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001959 PN->getIncomingValue(i), C, "phitmp",
1960 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001961 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001962 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001963 CI->getPredicate(),
1964 PN->getIncomingValue(i), C, "phitmp",
1965 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001966 else
1967 assert(0 && "Unknown binop!");
1968
Chris Lattnerdbab3862007-03-02 21:28:56 +00001969 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001970 }
1971 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001972 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001973 } else {
1974 CastInst *CI = cast<CastInst>(&I);
1975 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001976 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001977 Value *InV;
1978 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001979 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001980 } else {
1981 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001982 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00001983 I.getType(), "phitmp",
1984 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001985 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001986 }
1987 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001988 }
1989 }
1990 return ReplaceInstUsesWith(I, NewPN);
1991}
1992
Chris Lattner2454a2e2008-01-29 06:52:45 +00001993
Chris Lattner3d28b1b2008-05-20 05:46:13 +00001994/// WillNotOverflowSignedAdd - Return true if we can prove that:
1995/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1996/// This basically requires proving that the add in the original type would not
1997/// overflow to change the sign bit or have a carry out.
1998bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1999 // There are different heuristics we can use for this. Here are some simple
2000 // ones.
2001
2002 // Add has the property that adding any two 2's complement numbers can only
2003 // have one carry bit which can change a sign. As such, if LHS and RHS each
2004 // have at least two sign bits, we know that the addition of the two values will
2005 // sign extend fine.
2006 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2007 return true;
2008
2009
2010 // If one of the operands only has one non-zero bit, and if the other operand
2011 // has a known-zero bit in a more significant place than it (not including the
2012 // sign bit) the ripple may go up to and fill the zero, but won't change the
2013 // sign. For example, (X & ~4) + 1.
2014
2015 // TODO: Implement.
2016
2017 return false;
2018}
2019
Chris Lattner2454a2e2008-01-29 06:52:45 +00002020
Chris Lattner7e708292002-06-25 16:13:24 +00002021Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002022 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002023 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002024
Chris Lattner66331a42004-04-10 22:01:55 +00002025 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002026 // X + undef -> undef
2027 if (isa<UndefValue>(RHS))
2028 return ReplaceInstUsesWith(I, RHS);
2029
Chris Lattner66331a42004-04-10 22:01:55 +00002030 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002031 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002032 if (RHSC->isNullValue())
2033 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002034 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002035 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2036 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002037 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002038 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002039
Chris Lattner66331a42004-04-10 22:01:55 +00002040 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002041 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002042 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002043 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002044 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002045 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002046
2047 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2048 // (X & 254)+1 -> (X&254)|1
Chris Lattner886ab6c2009-01-31 08:15:18 +00002049 if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2050 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002051
2052 // zext(i1) - 1 -> select i1, 0, -1
2053 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2054 if (CI->isAllOnesValue() &&
2055 ZI->getOperand(0)->getType() == Type::Int1Ty)
2056 return SelectInst::Create(ZI->getOperand(0),
2057 Constant::getNullValue(I.getType()),
2058 ConstantInt::getAllOnesValue(I.getType()));
Chris Lattner66331a42004-04-10 22:01:55 +00002059 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002060
2061 if (isa<PHINode>(LHS))
2062 if (Instruction *NV = FoldOpIntoPhi(I))
2063 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002064
Chris Lattner4f637d42006-01-06 17:59:59 +00002065 ConstantInt *XorRHS = 0;
2066 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002067 if (isa<ConstantInt>(RHSC) &&
2068 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002069 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002070 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002071
Zhou Sheng4351c642007-04-02 08:20:41 +00002072 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002073 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2074 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002075 do {
2076 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002077 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2078 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002079 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2080 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002081 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002082 if (!MaskedValueIsZero(XorLHS,
2083 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002084 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002085 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002086 }
2087 }
2088 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002089 C0080Val = APIntOps::lshr(C0080Val, Size);
2090 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2091 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002092
Reid Spencer35c38852007-03-28 01:36:16 +00002093 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002094 // with funny bit widths then this switch statement should be removed. It
2095 // is just here to get the size of the "middle" type back up to something
2096 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002097 const Type *MiddleType = 0;
2098 switch (Size) {
2099 default: break;
2100 case 32: MiddleType = Type::Int32Ty; break;
2101 case 16: MiddleType = Type::Int16Ty; break;
2102 case 8: MiddleType = Type::Int8Ty; break;
2103 }
2104 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002105 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002106 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002107 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002108 }
2109 }
Chris Lattner66331a42004-04-10 22:01:55 +00002110 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002111
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002112 if (I.getType() == Type::Int1Ty)
2113 return BinaryOperator::CreateXor(LHS, RHS);
2114
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002115 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002116 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002117 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002118
2119 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2120 if (RHSI->getOpcode() == Instruction::Sub)
2121 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2122 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2123 }
2124 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2125 if (LHSI->getOpcode() == Instruction::Sub)
2126 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2127 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2128 }
Robert Bocchino71698282004-07-27 21:02:21 +00002129 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002130
Chris Lattner5c4afb92002-05-08 22:46:53 +00002131 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002132 // -A + -B --> -(A + B)
2133 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002134 if (LHS->getType()->isIntOrIntVector()) {
2135 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002136 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002137 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002138 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002139 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002140 }
2141
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002142 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002143 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002144
2145 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002146 if (!isa<Constant>(RHS))
2147 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002148 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002149
Misha Brukmanfd939082005-04-21 23:48:37 +00002150
Chris Lattner50af16a2004-11-13 19:50:12 +00002151 ConstantInt *C2;
2152 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2153 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002154 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002155
2156 // X*C1 + X*C2 --> X * (C1+C2)
2157 ConstantInt *C1;
2158 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002159 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002160 }
2161
2162 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002163 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002164 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002165
Chris Lattnere617c9e2007-01-05 02:17:46 +00002166 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002167 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2168 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002169
Chris Lattnerad3448c2003-02-18 19:57:07 +00002170
Chris Lattner564a7272003-08-13 19:01:45 +00002171 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002172 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002173 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2174 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002175
2176 // A+B --> A|B iff A and B have no bits set in common.
2177 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2178 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2179 APInt LHSKnownOne(IT->getBitWidth(), 0);
2180 APInt LHSKnownZero(IT->getBitWidth(), 0);
2181 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2182 if (LHSKnownZero != 0) {
2183 APInt RHSKnownOne(IT->getBitWidth(), 0);
2184 APInt RHSKnownZero(IT->getBitWidth(), 0);
2185 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2186
2187 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002188 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002189 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002190 }
2191 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002192
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002193 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002194 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002195 Value *W, *X, *Y, *Z;
2196 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2197 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2198 if (W != Y) {
2199 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002200 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002201 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002202 std::swap(W, X);
2203 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002204 std::swap(Y, Z);
2205 std::swap(W, X);
2206 }
2207 }
2208
2209 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002210 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002211 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002212 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002213 }
2214 }
2215 }
2216
Chris Lattner6b032052003-10-02 15:11:26 +00002217 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002218 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002219 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002220 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002221
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002222 // (X & FF00) + xx00 -> (X+xx00) & FF00
2223 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002224 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002225 if (Anded == CRHS) {
2226 // See if all bits from the first bit set in the Add RHS up are included
2227 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002228 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002229
2230 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002231 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002232
2233 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002234 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002235
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002236 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2237 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002238 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002239 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002240 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002241 }
2242 }
2243 }
2244
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002245 // Try to fold constant add into select arguments.
2246 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002247 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002248 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002249 }
2250
Reid Spencer1628cec2006-10-26 06:15:43 +00002251 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002252 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002253 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002254 CastInst *CI = dyn_cast<CastInst>(LHS);
2255 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002256 if (!CI) {
2257 CI = dyn_cast<CastInst>(RHS);
2258 Other = LHS;
2259 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002260 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002261 (CI->getType()->getPrimitiveSizeInBits() ==
2262 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002263 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002264 unsigned AS =
2265 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002266 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2267 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002268 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002269 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002270 }
2271 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002272
Chris Lattner42790482007-12-20 01:56:58 +00002273 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002274 {
2275 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002276 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002277 if (!SI) {
2278 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002279 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002280 }
Chris Lattner42790482007-12-20 01:56:58 +00002281 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002282 Value *TV = SI->getTrueValue();
2283 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002284 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002285
2286 // Can we fold the add into the argument of the select?
2287 // We check both true and false select arguments for a matching subtract.
Chris Lattner6046fb72008-11-16 04:46:19 +00002288 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2289 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002290 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner6046fb72008-11-16 04:46:19 +00002291 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2292 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002293 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002294 }
2295 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002296
2297 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2298 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2299 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2300 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002301
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002302 // Check for (add (sext x), y), see if we can merge this into an
2303 // integer add followed by a sext.
2304 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2305 // (add (sext x), cst) --> (sext (add x, cst'))
2306 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2307 Constant *CI =
2308 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2309 if (LHSConv->hasOneUse() &&
2310 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2311 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2312 // Insert the new, smaller add.
2313 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2314 CI, "addconv");
2315 InsertNewInstBefore(NewAdd, I);
2316 return new SExtInst(NewAdd, I.getType());
2317 }
2318 }
2319
2320 // (add (sext x), (sext y)) --> (sext (add int x, y))
2321 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2322 // Only do this if x/y have the same type, if at last one of them has a
2323 // single use (so we don't increase the number of sexts), and if the
2324 // integer add will not overflow.
2325 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2326 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2327 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2328 RHSConv->getOperand(0))) {
2329 // Insert the new integer add.
2330 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2331 RHSConv->getOperand(0),
2332 "addconv");
2333 InsertNewInstBefore(NewAdd, I);
2334 return new SExtInst(NewAdd, I.getType());
2335 }
2336 }
2337 }
2338
2339 // Check for (add double (sitofp x), y), see if we can merge this into an
2340 // integer add followed by a promotion.
2341 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2342 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2343 // ... if the constant fits in the integer value. This is useful for things
2344 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2345 // requires a constant pool load, and generally allows the add to be better
2346 // instcombined.
2347 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2348 Constant *CI =
2349 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2350 if (LHSConv->hasOneUse() &&
2351 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2352 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2353 // Insert the new integer add.
2354 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2355 CI, "addconv");
2356 InsertNewInstBefore(NewAdd, I);
2357 return new SIToFPInst(NewAdd, I.getType());
2358 }
2359 }
2360
2361 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2362 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2363 // Only do this if x/y have the same type, if at last one of them has a
2364 // single use (so we don't increase the number of int->fp conversions),
2365 // and if the integer add will not overflow.
2366 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2367 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2368 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2369 RHSConv->getOperand(0))) {
2370 // Insert the new integer add.
2371 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2372 RHSConv->getOperand(0),
2373 "addconv");
2374 InsertNewInstBefore(NewAdd, I);
2375 return new SIToFPInst(NewAdd, I.getType());
2376 }
2377 }
2378 }
2379
Chris Lattner7e708292002-06-25 16:13:24 +00002380 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002381}
2382
Chris Lattner7e708292002-06-25 16:13:24 +00002383Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002384 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002385
Chris Lattnerd137ab42008-07-17 06:07:20 +00002386 if (Op0 == Op1 && // sub X, X -> 0
2387 !I.getType()->isFPOrFPVector())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002388 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002389
Chris Lattner233f7dc2002-08-12 21:17:25 +00002390 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002391 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002392 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002393
Chris Lattnere87597f2004-10-16 18:11:37 +00002394 if (isa<UndefValue>(Op0))
2395 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2396 if (isa<UndefValue>(Op1))
2397 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2398
Chris Lattnerd65460f2003-11-05 01:06:05 +00002399 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2400 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002401 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002402 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002403
Chris Lattnerd65460f2003-11-05 01:06:05 +00002404 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002405 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002406 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002407 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002408
Chris Lattner76b7a062007-01-15 07:02:54 +00002409 // -(X >>u 31) -> (X >>s 31)
2410 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002411 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002412 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002413 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002414 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002415 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002416 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002417 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002418 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002419 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002420 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002421 }
2422 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002423 }
2424 else if (SI->getOpcode() == Instruction::AShr) {
2425 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2426 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002427 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002428 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002429 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002430 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002431 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002432 }
2433 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002434 }
2435 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002436 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002437
2438 // Try to fold constant sub into select arguments.
2439 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002440 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002441 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002442 }
2443
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002444 if (I.getType() == Type::Int1Ty)
2445 return BinaryOperator::CreateXor(Op0, Op1);
2446
Chris Lattner43d84d62005-04-07 16:15:25 +00002447 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2448 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002449 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002450 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002451 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002452 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002453 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002454 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2455 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2456 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002457 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002458 Op1I->getOperand(0));
2459 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002460 }
2461
Chris Lattnerfd059242003-10-15 16:48:29 +00002462 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002463 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2464 // is not used by anyone else...
2465 //
Chris Lattner0517e722004-02-02 20:09:56 +00002466 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002467 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002468 // Swap the two operands of the subexpr...
2469 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2470 Op1I->setOperand(0, IIOp1);
2471 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002472
Chris Lattnera2881962003-02-18 19:28:33 +00002473 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002474 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002475 }
2476
2477 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2478 //
2479 if (Op1I->getOpcode() == Instruction::And &&
2480 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2481 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2482
Chris Lattnerf523d062004-06-09 05:08:07 +00002483 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002484 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2485 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002486 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002487
Reid Spencerac5209e2006-10-16 23:08:08 +00002488 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002489 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002490 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002491 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002492 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002493 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002494 ConstantExpr::getNeg(DivRHS));
2495
Chris Lattnerad3448c2003-02-18 19:57:07 +00002496 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002497 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002498 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002499 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002500 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002501 }
Chris Lattner40371712002-05-09 01:29:19 +00002502 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002503 }
Chris Lattnera2881962003-02-18 19:28:33 +00002504
Chris Lattner9919e3d2006-12-02 00:13:08 +00002505 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002506 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002507 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002508 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2509 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2510 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2511 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002512 } else if (Op0I->getOpcode() == Instruction::Sub) {
2513 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002514 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002515 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002516 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002517
Chris Lattner50af16a2004-11-13 19:50:12 +00002518 ConstantInt *C1;
2519 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002520 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002521 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002522
Chris Lattner50af16a2004-11-13 19:50:12 +00002523 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2524 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002525 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002526 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002527 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002528}
2529
Chris Lattnera0141b92007-07-15 20:42:37 +00002530/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2531/// comparison only checks the sign bit. If it only checks the sign bit, set
2532/// TrueIfSigned if the result of the comparison is true when the input value is
2533/// signed.
2534static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2535 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002536 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002537 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2538 TrueIfSigned = true;
2539 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002540 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2541 TrueIfSigned = true;
2542 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002543 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2544 TrueIfSigned = false;
2545 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002546 case ICmpInst::ICMP_UGT:
2547 // True if LHS u> RHS and RHS == high-bit-mask - 1
2548 TrueIfSigned = true;
2549 return RHS->getValue() ==
2550 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2551 case ICmpInst::ICMP_UGE:
2552 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2553 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002554 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002555 default:
2556 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002557 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002558}
2559
Chris Lattner7e708292002-06-25 16:13:24 +00002560Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002561 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002562 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002563
Chris Lattnere87597f2004-10-16 18:11:37 +00002564 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2565 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2566
Chris Lattner233f7dc2002-08-12 21:17:25 +00002567 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002568 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2569 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002570
2571 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002572 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002573 if (SI->getOpcode() == Instruction::Shl)
2574 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002575 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002576 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002577
Zhou Sheng843f07672007-04-19 05:39:12 +00002578 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002579 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2580 if (CI->equalsInt(1)) // X * 1 == X
2581 return ReplaceInstUsesWith(I, Op0);
2582 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002583 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002584
Zhou Sheng97b52c22007-03-29 01:57:21 +00002585 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002586 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002587 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002588 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002589 }
Robert Bocchino71698282004-07-27 21:02:21 +00002590 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002591 if (Op1F->isNullValue())
2592 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002593
Chris Lattnera2881962003-02-18 19:28:33 +00002594 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2595 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002596 if (Op1F->isExactlyValue(1.0))
2597 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2598 } else if (isa<VectorType>(Op1->getType())) {
2599 if (isa<ConstantAggregateZero>(Op1))
2600 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002601
2602 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2603 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2604 return BinaryOperator::CreateNeg(Op0, I.getName());
2605
2606 // As above, vector X*splat(1.0) -> X in all defined cases.
2607 if (Constant *Splat = Op1V->getSplatValue()) {
2608 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2609 if (F->isExactlyValue(1.0))
2610 return ReplaceInstUsesWith(I, Op0);
2611 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2612 if (CI->equalsInt(1))
2613 return ReplaceInstUsesWith(I, Op0);
2614 }
2615 }
Chris Lattnera2881962003-02-18 19:28:33 +00002616 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002617
2618 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2619 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002620 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002621 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002622 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002623 Op1, "tmp");
2624 InsertNewInstBefore(Add, I);
2625 Value *C1C2 = ConstantExpr::getMul(Op1,
2626 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002627 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002628
2629 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002630
2631 // Try to fold constant mul into select arguments.
2632 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002633 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002634 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002635
2636 if (isa<PHINode>(Op0))
2637 if (Instruction *NV = FoldOpIntoPhi(I))
2638 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002639 }
2640
Chris Lattnera4f445b2003-03-10 23:23:04 +00002641 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2642 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002643 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002644
Nick Lewycky0c730792008-11-21 07:33:58 +00002645 // (X / Y) * Y = X - (X % Y)
2646 // (X / Y) * -Y = (X % Y) - X
2647 {
2648 Value *Op1 = I.getOperand(1);
2649 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2650 if (!BO ||
2651 (BO->getOpcode() != Instruction::UDiv &&
2652 BO->getOpcode() != Instruction::SDiv)) {
2653 Op1 = Op0;
2654 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2655 }
2656 Value *Neg = dyn_castNegVal(Op1);
2657 if (BO && BO->hasOneUse() &&
2658 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2659 (BO->getOpcode() == Instruction::UDiv ||
2660 BO->getOpcode() == Instruction::SDiv)) {
2661 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2662
2663 Instruction *Rem;
2664 if (BO->getOpcode() == Instruction::UDiv)
2665 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2666 else
2667 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2668
2669 InsertNewInstBefore(Rem, I);
2670 Rem->takeName(BO);
2671
2672 if (Op1BO == Op1)
2673 return BinaryOperator::CreateSub(Op0BO, Rem);
2674 else
2675 return BinaryOperator::CreateSub(Rem, Op0BO);
2676 }
2677 }
2678
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002679 if (I.getType() == Type::Int1Ty)
2680 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2681
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002682 // If one of the operands of the multiply is a cast from a boolean value, then
2683 // we know the bool is either zero or one, so this is a 'masking' multiply.
2684 // See if we can simplify things based on how the boolean was originally
2685 // formed.
2686 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002687 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002688 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002689 BoolCast = CI;
2690 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002691 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002692 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002693 BoolCast = CI;
2694 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002695 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002696 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2697 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002698 bool TIS = false;
2699
Reid Spencere4d87aa2006-12-23 06:05:41 +00002700 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002701 // multiply into a shift/and combination.
2702 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002703 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2704 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002705 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002706 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002707 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002708 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002709 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002710 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002711 BoolCast->getOperand(0)->getName()+
2712 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002713
2714 // If the multiply type is not the same as the source type, sign extend
2715 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002716 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002717 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2718 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002719 Instruction::CastOps opcode =
2720 (SrcBits == DstBits ? Instruction::BitCast :
2721 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2722 V = InsertCastBefore(opcode, V, I.getType(), I);
2723 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002724
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002725 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002726 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002727 }
2728 }
2729 }
2730
Chris Lattner7e708292002-06-25 16:13:24 +00002731 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002732}
2733
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002734/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2735/// instruction.
2736bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2737 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2738
2739 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2740 int NonNullOperand = -1;
2741 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2742 if (ST->isNullValue())
2743 NonNullOperand = 2;
2744 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2745 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2746 if (ST->isNullValue())
2747 NonNullOperand = 1;
2748
2749 if (NonNullOperand == -1)
2750 return false;
2751
2752 Value *SelectCond = SI->getOperand(0);
2753
2754 // Change the div/rem to use 'Y' instead of the select.
2755 I.setOperand(1, SI->getOperand(NonNullOperand));
2756
2757 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2758 // problem. However, the select, or the condition of the select may have
2759 // multiple uses. Based on our knowledge that the operand must be non-zero,
2760 // propagate the known value for the select into other uses of it, and
2761 // propagate a known value of the condition into its other users.
2762
2763 // If the select and condition only have a single use, don't bother with this,
2764 // early exit.
2765 if (SI->use_empty() && SelectCond->hasOneUse())
2766 return true;
2767
2768 // Scan the current block backward, looking for other uses of SI.
2769 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2770
2771 while (BBI != BBFront) {
2772 --BBI;
2773 // If we found a call to a function, we can't assume it will return, so
2774 // information from below it cannot be propagated above it.
2775 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2776 break;
2777
2778 // Replace uses of the select or its condition with the known values.
2779 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2780 I != E; ++I) {
2781 if (*I == SI) {
2782 *I = SI->getOperand(NonNullOperand);
2783 AddToWorkList(BBI);
2784 } else if (*I == SelectCond) {
2785 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2786 ConstantInt::getFalse();
2787 AddToWorkList(BBI);
2788 }
2789 }
2790
2791 // If we past the instruction, quit looking for it.
2792 if (&*BBI == SI)
2793 SI = 0;
2794 if (&*BBI == SelectCond)
2795 SelectCond = 0;
2796
2797 // If we ran out of things to eliminate, break out of the loop.
2798 if (SelectCond == 0 && SI == 0)
2799 break;
2800
2801 }
2802 return true;
2803}
2804
2805
Reid Spencer1628cec2006-10-26 06:15:43 +00002806/// This function implements the transforms on div instructions that work
2807/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2808/// used by the visitors to those instructions.
2809/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002810Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002811 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002812
Chris Lattner50b2ca42008-02-19 06:12:18 +00002813 // undef / X -> 0 for integer.
2814 // undef / X -> undef for FP (the undef could be a snan).
2815 if (isa<UndefValue>(Op0)) {
2816 if (Op0->getType()->isFPOrFPVector())
2817 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002818 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002819 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002820
2821 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002822 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002823 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002824
Reid Spencer1628cec2006-10-26 06:15:43 +00002825 return 0;
2826}
Misha Brukmanfd939082005-04-21 23:48:37 +00002827
Reid Spencer1628cec2006-10-26 06:15:43 +00002828/// This function implements the transforms common to both integer division
2829/// instructions (udiv and sdiv). It is called by the visitors to those integer
2830/// division instructions.
2831/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002832Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002833 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2834
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002835 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002836 if (Op0 == Op1) {
2837 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2838 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2839 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2840 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2841 }
2842
2843 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2844 return ReplaceInstUsesWith(I, CI);
2845 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002846
Reid Spencer1628cec2006-10-26 06:15:43 +00002847 if (Instruction *Common = commonDivTransforms(I))
2848 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002849
2850 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2851 // This does not apply for fdiv.
2852 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2853 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002854
2855 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2856 // div X, 1 == X
2857 if (RHS->equalsInt(1))
2858 return ReplaceInstUsesWith(I, Op0);
2859
2860 // (X / C1) / C2 -> X / (C1*C2)
2861 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2862 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2863 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002864 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2865 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2866 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002867 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002868 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002869 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002870
Reid Spencerbca0e382007-03-23 20:05:17 +00002871 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002872 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2873 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2874 return R;
2875 if (isa<PHINode>(Op0))
2876 if (Instruction *NV = FoldOpIntoPhi(I))
2877 return NV;
2878 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002879 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002880
Chris Lattnera2881962003-02-18 19:28:33 +00002881 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002882 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002883 if (LHS->equalsInt(0))
2884 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2885
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002886 // It can't be division by zero, hence it must be division by one.
2887 if (I.getType() == Type::Int1Ty)
2888 return ReplaceInstUsesWith(I, Op0);
2889
Nick Lewycky895f0852008-11-27 20:21:08 +00002890 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2891 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2892 // div X, 1 == X
2893 if (X->isOne())
2894 return ReplaceInstUsesWith(I, Op0);
2895 }
2896
Reid Spencer1628cec2006-10-26 06:15:43 +00002897 return 0;
2898}
2899
2900Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2902
2903 // Handle the integer div common cases
2904 if (Instruction *Common = commonIDivTransforms(I))
2905 return Common;
2906
Reid Spencer1628cec2006-10-26 06:15:43 +00002907 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002908 // X udiv C^2 -> X >> C
2909 // Check to see if this is an unsigned division with an exact power of 2,
2910 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002911 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002912 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002913 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002914
2915 // X udiv C, where C >= signbit
2916 if (C->getValue().isNegative()) {
2917 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2918 I);
2919 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2920 ConstantInt::get(I.getType(), 1));
2921 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002922 }
2923
2924 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002925 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002926 if (RHSI->getOpcode() == Instruction::Shl &&
2927 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002928 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002929 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002930 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002931 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002932 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002933 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002934 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002935 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002936 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002937 }
2938 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002939 }
2940
Reid Spencer1628cec2006-10-26 06:15:43 +00002941 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2942 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002943 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002944 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002945 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002946 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002947 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002948 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002949 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002950 // Construct the "on true" case of the select
2951 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002952 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002953 Op0, TC, SI->getName()+".t");
2954 TSI = InsertNewInstBefore(TSI, I);
2955
2956 // Construct the "on false" case of the select
2957 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002959 Op0, FC, SI->getName()+".f");
2960 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002961
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002962 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00002963 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002964 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002965 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002966 return 0;
2967}
2968
Reid Spencer1628cec2006-10-26 06:15:43 +00002969Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2971
2972 // Handle the integer div common cases
2973 if (Instruction *Common = commonIDivTransforms(I))
2974 return Common;
2975
2976 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2977 // sdiv X, -1 == -X
2978 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002979 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00002980 }
2981
2982 // If the sign bits of both operands are zero (i.e. we can prove they are
2983 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002984 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002985 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002986 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002987 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002988 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002989 }
2990 }
2991
2992 return 0;
2993}
2994
2995Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2996 return commonDivTransforms(I);
2997}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002998
Reid Spencer0a783f72006-11-02 01:53:59 +00002999/// This function implements the transforms on rem instructions that work
3000/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3001/// is used by the visitors to those instructions.
3002/// @brief Transforms common to all three rem instructions
3003Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003004 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003005
Chris Lattner50b2ca42008-02-19 06:12:18 +00003006 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3007 if (I.getType()->isFPOrFPVector())
3008 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003009 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003010 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003011 if (isa<UndefValue>(Op1))
3012 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003013
3014 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003015 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3016 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003017
Reid Spencer0a783f72006-11-02 01:53:59 +00003018 return 0;
3019}
3020
3021/// This function implements the transforms common to both integer remainder
3022/// instructions (urem and srem). It is called by the visitors to those integer
3023/// remainder instructions.
3024/// @brief Common integer remainder transforms
3025Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3027
3028 if (Instruction *common = commonRemTransforms(I))
3029 return common;
3030
Dale Johannesened6af242009-01-21 00:35:19 +00003031 // 0 % X == 0 for integer, we don't need to preserve faults!
3032 if (Constant *LHS = dyn_cast<Constant>(Op0))
3033 if (LHS->isNullValue())
3034 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3035
Chris Lattner857e8cd2004-12-12 21:48:58 +00003036 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003037 // X % 0 == undef, we don't need to preserve faults!
3038 if (RHS->equalsInt(0))
3039 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3040
Chris Lattnera2881962003-02-18 19:28:33 +00003041 if (RHS->equalsInt(1)) // X % 1 == 0
3042 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3043
Chris Lattner97943922006-02-28 05:49:21 +00003044 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3045 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3046 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3047 return R;
3048 } else if (isa<PHINode>(Op0I)) {
3049 if (Instruction *NV = FoldOpIntoPhi(I))
3050 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003051 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003052
3053 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003054 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003055 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003056 }
Chris Lattnera2881962003-02-18 19:28:33 +00003057 }
3058
Reid Spencer0a783f72006-11-02 01:53:59 +00003059 return 0;
3060}
3061
3062Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3063 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3064
3065 if (Instruction *common = commonIRemTransforms(I))
3066 return common;
3067
3068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3069 // X urem C^2 -> X and C
3070 // Check to see if this is an unsigned remainder with an exact power of 2,
3071 // if so, convert to a bitwise and.
3072 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003073 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003074 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003075 }
3076
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003077 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003078 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3079 if (RHSI->getOpcode() == Instruction::Shl &&
3080 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003081 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003082 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003083 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003084 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003085 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003086 }
3087 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003088 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003089
Reid Spencer0a783f72006-11-02 01:53:59 +00003090 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3091 // where C1&C2 are powers of two.
3092 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3093 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3094 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3095 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003096 if ((STO->getValue().isPowerOf2()) &&
3097 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003098 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003099 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003100 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003101 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003102 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003103 }
3104 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003105 }
3106
Chris Lattner3f5b8772002-05-06 16:14:14 +00003107 return 0;
3108}
3109
Reid Spencer0a783f72006-11-02 01:53:59 +00003110Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3111 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3112
Dan Gohmancff55092007-11-05 23:16:33 +00003113 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003114 if (Instruction *common = commonIRemTransforms(I))
3115 return common;
3116
3117 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003118 if (!isa<Constant>(RHSNeg) ||
3119 (isa<ConstantInt>(RHSNeg) &&
3120 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003121 // X % -Y -> X % Y
3122 AddUsesToWorkList(I);
3123 I.setOperand(1, RHSNeg);
3124 return &I;
3125 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003126
Dan Gohmancff55092007-11-05 23:16:33 +00003127 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003128 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003129 if (I.getType()->isInteger()) {
3130 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3131 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3132 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003133 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003134 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003135 }
3136
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003137 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003138 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3139 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003140
Nick Lewycky9dce8732008-12-20 16:48:00 +00003141 bool hasNegative = false;
3142 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3143 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3144 if (RHS->getValue().isNegative())
3145 hasNegative = true;
3146
3147 if (hasNegative) {
3148 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003149 for (unsigned i = 0; i != VWidth; ++i) {
3150 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3151 if (RHS->getValue().isNegative())
3152 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3153 else
3154 Elts[i] = RHS;
3155 }
3156 }
3157
3158 Constant *NewRHSV = ConstantVector::get(Elts);
3159 if (NewRHSV != RHSV) {
Nick Lewycky19c28922008-12-18 06:42:28 +00003160 AddUsesToWorkList(I);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003161 I.setOperand(1, NewRHSV);
3162 return &I;
3163 }
3164 }
3165 }
3166
Reid Spencer0a783f72006-11-02 01:53:59 +00003167 return 0;
3168}
3169
3170Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003171 return commonRemTransforms(I);
3172}
3173
Chris Lattner457dd822004-06-09 07:59:58 +00003174// isOneBitSet - Return true if there is exactly one bit set in the specified
3175// constant.
3176static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003177 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003178}
3179
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003180// isHighOnes - Return true if the constant is of the form 1+0+.
3181// This is the same as lowones(~X).
3182static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003183 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003184}
3185
Reid Spencere4d87aa2006-12-23 06:05:41 +00003186/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003187/// are carefully arranged to allow folding of expressions such as:
3188///
3189/// (A < B) | (A > B) --> (A != B)
3190///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003191/// Note that this is only valid if the first and second predicates have the
3192/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003193///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003194/// Three bits are used to represent the condition, as follows:
3195/// 0 A > B
3196/// 1 A == B
3197/// 2 A < B
3198///
3199/// <=> Value Definition
3200/// 000 0 Always false
3201/// 001 1 A > B
3202/// 010 2 A == B
3203/// 011 3 A >= B
3204/// 100 4 A < B
3205/// 101 5 A != B
3206/// 110 6 A <= B
3207/// 111 7 Always true
3208///
3209static unsigned getICmpCode(const ICmpInst *ICI) {
3210 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003211 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003212 case ICmpInst::ICMP_UGT: return 1; // 001
3213 case ICmpInst::ICMP_SGT: return 1; // 001
3214 case ICmpInst::ICMP_EQ: return 2; // 010
3215 case ICmpInst::ICMP_UGE: return 3; // 011
3216 case ICmpInst::ICMP_SGE: return 3; // 011
3217 case ICmpInst::ICMP_ULT: return 4; // 100
3218 case ICmpInst::ICMP_SLT: return 4; // 100
3219 case ICmpInst::ICMP_NE: return 5; // 101
3220 case ICmpInst::ICMP_ULE: return 6; // 110
3221 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003222 // True -> 7
3223 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003224 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003225 return 0;
3226 }
3227}
3228
Evan Cheng8db90722008-10-14 17:15:11 +00003229/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3230/// predicate into a three bit mask. It also returns whether it is an ordered
3231/// predicate by reference.
3232static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3233 isOrdered = false;
3234 switch (CC) {
3235 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3236 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003237 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3238 case FCmpInst::FCMP_UGT: return 1; // 001
3239 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3240 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003241 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3242 case FCmpInst::FCMP_UGE: return 3; // 011
3243 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3244 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003245 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3246 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003247 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3248 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003249 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003250 default:
3251 // Not expecting FCMP_FALSE and FCMP_TRUE;
3252 assert(0 && "Unexpected FCmp predicate!");
3253 return 0;
3254 }
3255}
3256
Reid Spencere4d87aa2006-12-23 06:05:41 +00003257/// getICmpValue - This is the complement of getICmpCode, which turns an
3258/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003259/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003260/// of predicate to use in the new icmp instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003261static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3262 switch (code) {
3263 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003264 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003265 case 1:
3266 if (sign)
3267 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3268 else
3269 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3270 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3271 case 3:
3272 if (sign)
3273 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3274 else
3275 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3276 case 4:
3277 if (sign)
3278 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3279 else
3280 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3281 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3282 case 6:
3283 if (sign)
3284 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3285 else
3286 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003287 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003288 }
3289}
3290
Evan Cheng8db90722008-10-14 17:15:11 +00003291/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3292/// opcode and two operands into either a FCmp instruction. isordered is passed
3293/// in to determine which kind of predicate to use in the new fcmp instruction.
3294static Value *getFCmpValue(bool isordered, unsigned code,
3295 Value *LHS, Value *RHS) {
3296 switch (code) {
Evan Cheng4990b252008-10-14 18:13:38 +00003297 default: assert(0 && "Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003298 case 0:
3299 if (isordered)
3300 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3301 else
3302 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3303 case 1:
3304 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003305 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3306 else
3307 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003308 case 2:
3309 if (isordered)
3310 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3311 else
3312 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003313 case 3:
3314 if (isordered)
3315 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3316 else
3317 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3318 case 4:
3319 if (isordered)
3320 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3321 else
3322 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3323 case 5:
3324 if (isordered)
Evan Cheng4990b252008-10-14 18:13:38 +00003325 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3326 else
3327 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3328 case 6:
3329 if (isordered)
Evan Cheng8db90722008-10-14 17:15:11 +00003330 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3331 else
3332 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng40300622008-10-14 18:44:08 +00003333 case 7: return ConstantInt::getTrue();
Evan Cheng8db90722008-10-14 17:15:11 +00003334 }
3335}
3336
Chris Lattnerb9553d62008-11-16 04:55:20 +00003337/// PredicatesFoldable - Return true if both predicates match sign or if at
3338/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003339static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3340 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003341 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3342 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003343}
3344
3345namespace {
3346// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3347struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003348 InstCombiner &IC;
3349 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003350 ICmpInst::Predicate pred;
3351 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3352 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3353 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003354 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003355 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3356 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003357 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3358 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003359 return false;
3360 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003361 Instruction *apply(Instruction &Log) const {
3362 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3363 if (ICI->getOperand(0) != LHS) {
3364 assert(ICI->getOperand(1) == LHS);
3365 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003366 }
3367
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003368 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003369 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003370 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003371 unsigned Code;
3372 switch (Log.getOpcode()) {
3373 case Instruction::And: Code = LHSCode & RHSCode; break;
3374 case Instruction::Or: Code = LHSCode | RHSCode; break;
3375 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003376 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003377 }
3378
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003379 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3380 ICmpInst::isSignedPredicate(ICI->getPredicate());
3381
3382 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003383 if (Instruction *I = dyn_cast<Instruction>(RV))
3384 return I;
3385 // Otherwise, it's a constant boolean value...
3386 return IC.ReplaceInstUsesWith(Log, RV);
3387 }
3388};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003389} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003390
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003391// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3392// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003393// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003394Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003395 ConstantInt *OpRHS,
3396 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003397 BinaryOperator &TheAnd) {
3398 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003399 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003400 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003401 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003402
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003403 switch (Op->getOpcode()) {
3404 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003405 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003406 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003407 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003408 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003409 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003410 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003411 }
3412 break;
3413 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003414 if (Together == AndRHS) // (X | C) & C --> C
3415 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003416
Chris Lattner6e7ba452005-01-01 16:22:27 +00003417 if (Op->hasOneUse() && Together != OpRHS) {
3418 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003419 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003420 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003421 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003422 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003423 }
3424 break;
3425 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003426 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003427 // Adding a one to a single bit bit-field should be turned into an XOR
3428 // of the bit. First thing to check is to see if this AND is with a
3429 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003430 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003431
3432 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003433 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003434 // Ok, at this point, we know that we are masking the result of the
3435 // ADD down to exactly one bit. If the constant we are adding has
3436 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003437 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003438
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003439 // Check to see if any bits below the one bit set in AndRHSV are set.
3440 if ((AddRHS & (AndRHSV-1)) == 0) {
3441 // If not, the only thing that can effect the output of the AND is
3442 // the bit specified by AndRHSV. If that bit is set, the effect of
3443 // the XOR is to toggle the bit. If it is clear, then the ADD has
3444 // no effect.
3445 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3446 TheAnd.setOperand(0, X);
3447 return &TheAnd;
3448 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003449 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003450 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003451 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003452 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003453 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003454 }
3455 }
3456 }
3457 }
3458 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003459
3460 case Instruction::Shl: {
3461 // We know that the AND will not produce any of the bits shifted in, so if
3462 // the anded constant includes them, clear them now!
3463 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003464 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003465 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003466 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3467 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003468
Zhou Sheng290bec52007-03-29 08:15:12 +00003469 if (CI->getValue() == ShlMask) {
3470 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003471 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3472 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003473 TheAnd.setOperand(1, CI);
3474 return &TheAnd;
3475 }
3476 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003477 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003478 case Instruction::LShr:
3479 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003480 // We know that the AND will not produce any of the bits shifted in, so if
3481 // the anded constant includes them, clear them now! This only applies to
3482 // unsigned shifts, because a signed shr may bring in set bits!
3483 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003484 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003485 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003486 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3487 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003488
Zhou Sheng290bec52007-03-29 08:15:12 +00003489 if (CI->getValue() == ShrMask) {
3490 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003491 return ReplaceInstUsesWith(TheAnd, Op);
3492 } else if (CI != AndRHS) {
3493 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3494 return &TheAnd;
3495 }
3496 break;
3497 }
3498 case Instruction::AShr:
3499 // Signed shr.
3500 // See if this is shifting in some sign extension, then masking it out
3501 // with an and.
3502 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003503 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003504 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003505 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3506 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003507 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003508 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003509 // Make the argument unsigned.
3510 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003511 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003512 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003513 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003514 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003515 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003516 }
3517 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518 }
3519 return 0;
3520}
3521
Chris Lattner8b170942002-08-09 23:47:40 +00003522
Chris Lattnera96879a2004-09-29 17:40:11 +00003523/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3524/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003525/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3526/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003527/// insert new instructions.
3528Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003529 bool isSigned, bool Inside,
3530 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003531 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003532 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003533 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003534
Chris Lattnera96879a2004-09-29 17:40:11 +00003535 if (Inside) {
3536 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003537 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003538
Reid Spencere4d87aa2006-12-23 06:05:41 +00003539 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003540 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003541 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003542 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3543 return new ICmpInst(pred, V, Hi);
3544 }
3545
3546 // Emit V-Lo <u Hi-Lo
3547 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003548 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003549 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003550 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3551 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003552 }
3553
3554 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003555 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003556
Reid Spencere4e40032007-03-21 23:19:50 +00003557 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003558 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003559 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003560 ICmpInst::Predicate pred = (isSigned ?
3561 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3562 return new ICmpInst(pred, V, Hi);
3563 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003564
Reid Spencere4e40032007-03-21 23:19:50 +00003565 // Emit V-Lo >u Hi-1-Lo
3566 // Note that Hi has already had one subtracted from it, above.
3567 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003568 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003569 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003570 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3571 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003572}
3573
Chris Lattner7203e152005-09-18 07:22:02 +00003574// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3575// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3576// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3577// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003578static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003579 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003580 uint32_t BitWidth = Val->getType()->getBitWidth();
3581 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003582
3583 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003584 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003585 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003586 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003587 return true;
3588}
3589
Chris Lattner7203e152005-09-18 07:22:02 +00003590/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3591/// where isSub determines whether the operator is a sub. If we can fold one of
3592/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003593///
3594/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3595/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3596/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3597///
3598/// return (A +/- B).
3599///
3600Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003601 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003602 Instruction &I) {
3603 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3604 if (!LHSI || LHSI->getNumOperands() != 2 ||
3605 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3606
3607 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3608
3609 switch (LHSI->getOpcode()) {
3610 default: return 0;
3611 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003612 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003613 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003614 if ((Mask->getValue().countLeadingZeros() +
3615 Mask->getValue().countPopulation()) ==
3616 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003617 break;
3618
3619 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3620 // part, we don't need any explicit masks to take them out of A. If that
3621 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003622 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003623 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003624 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003625 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003626 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003627 break;
3628 }
3629 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003630 return 0;
3631 case Instruction::Or:
3632 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003633 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003634 if ((Mask->getValue().countLeadingZeros() +
3635 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003636 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003637 break;
3638 return 0;
3639 }
3640
3641 Instruction *New;
3642 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003643 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003644 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003645 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003646 return InsertNewInstBefore(New, I);
3647}
3648
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003649/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3650Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3651 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003652 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003653 ConstantInt *LHSCst, *RHSCst;
3654 ICmpInst::Predicate LHSCC, RHSCC;
3655
Chris Lattnerea065fb2008-11-16 05:10:52 +00003656 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003657 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerea065fb2008-11-16 05:10:52 +00003658 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003659 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003660
3661 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3662 // where C is a power of 2
3663 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3664 LHSCst->getValue().isPowerOf2()) {
3665 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3666 InsertNewInstBefore(NewOr, I);
3667 return new ICmpInst(LHSCC, NewOr, LHSCst);
3668 }
3669
3670 // From here on, we only handle:
3671 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3672 if (Val != Val2) return 0;
3673
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003674 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3675 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3676 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3677 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3678 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3679 return 0;
3680
3681 // We can't fold (ugt x, C) & (sgt x, C2).
3682 if (!PredicatesFoldable(LHSCC, RHSCC))
3683 return 0;
3684
3685 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003686 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003687 if (ICmpInst::isSignedPredicate(LHSCC) ||
3688 (ICmpInst::isEquality(LHSCC) &&
3689 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003690 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003691 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003692 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3693
3694 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003695 std::swap(LHS, RHS);
3696 std::swap(LHSCst, RHSCst);
3697 std::swap(LHSCC, RHSCC);
3698 }
3699
3700 // At this point, we know we have have two icmp instructions
3701 // comparing a value against two constants and and'ing the result
3702 // together. Because of the above check, we know that we only have
3703 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3704 // (from the FoldICmpLogical check above), that the two constants
3705 // are not equal and that the larger constant is on the RHS
3706 assert(LHSCst != RHSCst && "Compares not folded above?");
3707
3708 switch (LHSCC) {
3709 default: assert(0 && "Unknown integer condition code!");
3710 case ICmpInst::ICMP_EQ:
3711 switch (RHSCC) {
3712 default: assert(0 && "Unknown integer condition code!");
3713 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3714 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3715 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3716 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3717 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3718 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3719 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3720 return ReplaceInstUsesWith(I, LHS);
3721 }
3722 case ICmpInst::ICMP_NE:
3723 switch (RHSCC) {
3724 default: assert(0 && "Unknown integer condition code!");
3725 case ICmpInst::ICMP_ULT:
3726 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3727 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3728 break; // (X != 13 & X u< 15) -> no change
3729 case ICmpInst::ICMP_SLT:
3730 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3731 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3732 break; // (X != 13 & X s< 15) -> no change
3733 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3734 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3735 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3736 return ReplaceInstUsesWith(I, RHS);
3737 case ICmpInst::ICMP_NE:
3738 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3739 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3740 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3741 Val->getName()+".off");
3742 InsertNewInstBefore(Add, I);
3743 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3744 ConstantInt::get(Add->getType(), 1));
3745 }
3746 break; // (X != 13 & X != 15) -> no change
3747 }
3748 break;
3749 case ICmpInst::ICMP_ULT:
3750 switch (RHSCC) {
3751 default: assert(0 && "Unknown integer condition code!");
3752 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3753 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3754 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3755 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3756 break;
3757 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3758 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3759 return ReplaceInstUsesWith(I, LHS);
3760 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3761 break;
3762 }
3763 break;
3764 case ICmpInst::ICMP_SLT:
3765 switch (RHSCC) {
3766 default: assert(0 && "Unknown integer condition code!");
3767 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3768 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3769 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3770 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3771 break;
3772 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3773 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3774 return ReplaceInstUsesWith(I, LHS);
3775 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3776 break;
3777 }
3778 break;
3779 case ICmpInst::ICMP_UGT:
3780 switch (RHSCC) {
3781 default: assert(0 && "Unknown integer condition code!");
3782 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3783 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3784 return ReplaceInstUsesWith(I, RHS);
3785 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3786 break;
3787 case ICmpInst::ICMP_NE:
3788 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3789 return new ICmpInst(LHSCC, Val, RHSCst);
3790 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003791 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003792 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3793 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3794 break;
3795 }
3796 break;
3797 case ICmpInst::ICMP_SGT:
3798 switch (RHSCC) {
3799 default: assert(0 && "Unknown integer condition code!");
3800 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3801 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3802 return ReplaceInstUsesWith(I, RHS);
3803 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3804 break;
3805 case ICmpInst::ICMP_NE:
3806 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3807 return new ICmpInst(LHSCC, Val, RHSCst);
3808 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003809 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003810 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3811 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3812 break;
3813 }
3814 break;
3815 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003816
3817 return 0;
3818}
3819
3820
Chris Lattner7e708292002-06-25 16:13:24 +00003821Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003822 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003823 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003824
Chris Lattnere87597f2004-10-16 18:11:37 +00003825 if (isa<UndefValue>(Op1)) // X & undef -> 0
3826 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3827
Chris Lattner6e7ba452005-01-01 16:22:27 +00003828 // and X, X = X
3829 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003830 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003831
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003832 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003833 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003834 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00003835 if (SimplifyDemandedInstructionBits(I))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003836 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003837 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003838 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003839 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003840 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003841 } else if (isa<ConstantAggregateZero>(Op1)) {
3842 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003843 }
3844 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003845
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003846 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003847 const APInt& AndRHSMask = AndRHS->getValue();
3848 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003849
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003850 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003851 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003852 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003853 Value *Op0LHS = Op0I->getOperand(0);
3854 Value *Op0RHS = Op0I->getOperand(1);
3855 switch (Op0I->getOpcode()) {
3856 case Instruction::Xor:
3857 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003858 // If the mask is only needed on one incoming arm, push it up.
3859 if (Op0I->hasOneUse()) {
3860 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3861 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003862 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003863 Op0RHS->getName()+".masked");
3864 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003865 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003866 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003867 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003868 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003869 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3870 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003871 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003872 Op0LHS->getName()+".masked");
3873 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003874 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003875 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3876 }
3877 }
3878
Chris Lattner6e7ba452005-01-01 16:22:27 +00003879 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003880 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003881 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3882 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3883 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3884 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003885 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003886 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003887 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003888 break;
3889
3890 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003891 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3892 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3893 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3894 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003895 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003896
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003897 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3898 // has 1's for all bits that the subtraction with A might affect.
3899 if (Op0I->hasOneUse()) {
3900 uint32_t BitWidth = AndRHSMask.getBitWidth();
3901 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3902 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3903
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003904 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00003905 if (!(A && A->isZero()) && // avoid infinite recursion.
3906 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00003907 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3908 InsertNewInstBefore(NewNeg, I);
3909 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3910 }
3911 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003912 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003913
3914 case Instruction::Shl:
3915 case Instruction::LShr:
3916 // (1 << x) & 1 --> zext(x == 0)
3917 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00003918 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00003919 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3920 Constant::getNullValue(I.getType()));
3921 InsertNewInstBefore(NewICmp, I);
3922 return new ZExtInst(NewICmp, I.getType());
3923 }
3924 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003925 }
3926
Chris Lattner58403262003-07-23 19:25:52 +00003927 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003928 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003929 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003930 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003931 // If this is an integer truncation or change from signed-to-unsigned, and
3932 // if the source is an and/or with immediate, transform it. This
3933 // frequently occurs for bitfield accesses.
3934 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003935 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003936 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003937 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003938 if (CastOp->getOpcode() == Instruction::And) {
3939 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003940 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3941 // This will fold the two constants together, which may allow
3942 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003943 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003944 CastOp->getOperand(0), I.getType(),
3945 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003946 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003947 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003948 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003949 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003950 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003951 } else if (CastOp->getOpcode() == Instruction::Or) {
3952 // Change: and (cast (or X, C1) to T), C2
3953 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003954 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003955 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3956 return ReplaceInstUsesWith(I, AndRHS);
3957 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003958 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003959 }
Chris Lattner06782f82003-07-23 19:36:21 +00003960 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003961
3962 // Try to fold constant and into select arguments.
3963 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003964 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003965 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003966 if (isa<PHINode>(Op0))
3967 if (Instruction *NV = FoldOpIntoPhi(I))
3968 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003969 }
3970
Chris Lattner8d969642003-03-10 23:06:50 +00003971 Value *Op0NotVal = dyn_castNotVal(Op0);
3972 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003973
Chris Lattner5b62aa72004-06-18 06:07:51 +00003974 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3976
Misha Brukmancb6267b2004-07-30 12:50:08 +00003977 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003978 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003979 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003980 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003981 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003982 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003983 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003984
3985 {
Chris Lattner003b6202007-06-15 05:58:24 +00003986 Value *A = 0, *B = 0, *C = 0, *D = 0;
3987 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003988 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3989 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003990
3991 // (A|B) & ~(A&B) -> A^B
3992 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3993 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003994 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003995 }
3996 }
3997
3998 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003999 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4000 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004001
4002 // ~(A&B) & (A|B) -> A^B
4003 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4004 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004005 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004006 }
4007 }
Chris Lattner64daab52006-04-01 08:03:55 +00004008
4009 if (Op0->hasOneUse() &&
4010 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4011 if (A == Op1) { // (A^B)&A -> A&(A^B)
4012 I.swapOperands(); // Simplify below
4013 std::swap(Op0, Op1);
4014 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4015 cast<BinaryOperator>(Op0)->swapOperands();
4016 I.swapOperands(); // Simplify below
4017 std::swap(Op0, Op1);
4018 }
4019 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004020
Chris Lattner64daab52006-04-01 08:03:55 +00004021 if (Op1->hasOneUse() &&
4022 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4023 if (B == Op0) { // B&(A^B) -> B&(B^A)
4024 cast<BinaryOperator>(Op1)->swapOperands();
4025 std::swap(A, B);
4026 }
4027 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004028 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004029 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004030 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004031 }
4032 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004033
4034 // (A&((~A)|B)) -> A&B
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004035 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4036 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4037 return BinaryOperator::CreateAnd(A, Op1);
4038 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4039 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4040 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004041 }
4042
Reid Spencere4d87aa2006-12-23 06:05:41 +00004043 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4044 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4045 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004046 return R;
4047
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004048 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4049 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4050 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004051 }
4052
Chris Lattner6fc205f2006-05-05 06:39:07 +00004053 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004054 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4055 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4056 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4057 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004058 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004059 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004060 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4061 I.getType(), TD) &&
4062 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4063 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004064 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004065 Op1C->getOperand(0),
4066 I.getName());
4067 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004068 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004069 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004070 }
Chris Lattnere511b742006-11-14 07:46:50 +00004071
4072 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004073 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4074 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4075 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004076 SI0->getOperand(1) == SI1->getOperand(1) &&
4077 (SI0->hasOneUse() || SI1->hasOneUse())) {
4078 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004080 SI1->getOperand(0),
4081 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004082 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004083 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004084 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004085 }
4086
Evan Cheng8db90722008-10-14 17:15:11 +00004087 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004088 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4089 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4090 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng8db90722008-10-14 17:15:11 +00004091 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4092 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner99c65742007-10-24 05:38:08 +00004093 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4094 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4095 // If either of the constants are nans, then the whole thing returns
4096 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004097 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004098 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4099 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4100 RHS->getOperand(0));
4101 }
Evan Cheng8db90722008-10-14 17:15:11 +00004102 } else {
4103 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4104 FCmpInst::Predicate Op0CC, Op1CC;
4105 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4106 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Cheng4990b252008-10-14 18:13:38 +00004107 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4108 // Swap RHS operands to match LHS.
4109 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4110 std::swap(Op1LHS, Op1RHS);
4111 }
Evan Cheng8db90722008-10-14 17:15:11 +00004112 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4113 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4114 if (Op0CC == Op1CC)
4115 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4116 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4117 Op1CC == FCmpInst::FCMP_FALSE)
4118 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4119 else if (Op0CC == FCmpInst::FCMP_TRUE)
4120 return ReplaceInstUsesWith(I, Op1);
4121 else if (Op1CC == FCmpInst::FCMP_TRUE)
4122 return ReplaceInstUsesWith(I, Op0);
4123 bool Op0Ordered;
4124 bool Op1Ordered;
4125 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4126 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4127 if (Op1Pred == 0) {
4128 std::swap(Op0, Op1);
4129 std::swap(Op0Pred, Op1Pred);
4130 std::swap(Op0Ordered, Op1Ordered);
4131 }
4132 if (Op0Pred == 0) {
4133 // uno && ueq -> uno && (uno || eq) -> ueq
4134 // ord && olt -> ord && (ord && lt) -> olt
4135 if (Op0Ordered == Op1Ordered)
4136 return ReplaceInstUsesWith(I, Op1);
4137 // uno && oeq -> uno && (ord && eq) -> false
4138 // uno && ord -> false
4139 if (!Op0Ordered)
4140 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4141 // ord && ueq -> ord && (uno || eq) -> oeq
4142 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4143 Op0LHS, Op0RHS));
4144 }
4145 }
4146 }
4147 }
Chris Lattner99c65742007-10-24 05:38:08 +00004148 }
4149 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004150
Chris Lattner7e708292002-06-25 16:13:24 +00004151 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004152}
4153
Chris Lattner8c34cd22008-10-05 02:13:19 +00004154/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4155/// capable of providing pieces of a bswap. The subexpression provides pieces
4156/// of a bswap if it is proven that each of the non-zero bytes in the output of
4157/// the expression came from the corresponding "byte swapped" byte in some other
4158/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4159/// we know that the expression deposits the low byte of %X into the high byte
4160/// of the bswap result and that all other bytes are zero. This expression is
4161/// accepted, the high byte of ByteValues is set to X to indicate a correct
4162/// match.
4163///
4164/// This function returns true if the match was unsuccessful and false if so.
4165/// On entry to the function the "OverallLeftShift" is a signed integer value
4166/// indicating the number of bytes that the subexpression is later shifted. For
4167/// example, if the expression is later right shifted by 16 bits, the
4168/// OverallLeftShift value would be -2 on entry. This is used to specify which
4169/// byte of ByteValues is actually being set.
4170///
4171/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4172/// byte is masked to zero by a user. For example, in (X & 255), X will be
4173/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4174/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4175/// always in the local (OverallLeftShift) coordinate space.
4176///
4177static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4178 SmallVector<Value*, 8> &ByteValues) {
4179 if (Instruction *I = dyn_cast<Instruction>(V)) {
4180 // If this is an or instruction, it may be an inner node of the bswap.
4181 if (I->getOpcode() == Instruction::Or) {
4182 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4183 ByteValues) ||
4184 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4185 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004186 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004187
4188 // If this is a logical shift by a constant multiple of 8, recurse with
4189 // OverallLeftShift and ByteMask adjusted.
4190 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4191 unsigned ShAmt =
4192 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4193 // Ensure the shift amount is defined and of a byte value.
4194 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4195 return true;
4196
4197 unsigned ByteShift = ShAmt >> 3;
4198 if (I->getOpcode() == Instruction::Shl) {
4199 // X << 2 -> collect(X, +2)
4200 OverallLeftShift += ByteShift;
4201 ByteMask >>= ByteShift;
4202 } else {
4203 // X >>u 2 -> collect(X, -2)
4204 OverallLeftShift -= ByteShift;
4205 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004206 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004207 }
4208
4209 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4210 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4211
4212 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4213 ByteValues);
4214 }
4215
4216 // If this is a logical 'and' with a mask that clears bytes, clear the
4217 // corresponding bytes in ByteMask.
4218 if (I->getOpcode() == Instruction::And &&
4219 isa<ConstantInt>(I->getOperand(1))) {
4220 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4221 unsigned NumBytes = ByteValues.size();
4222 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4223 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4224
4225 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4226 // If this byte is masked out by a later operation, we don't care what
4227 // the and mask is.
4228 if ((ByteMask & (1 << i)) == 0)
4229 continue;
4230
4231 // If the AndMask is all zeros for this byte, clear the bit.
4232 APInt MaskB = AndMask & Byte;
4233 if (MaskB == 0) {
4234 ByteMask &= ~(1U << i);
4235 continue;
4236 }
4237
4238 // If the AndMask is not all ones for this byte, it's not a bytezap.
4239 if (MaskB != Byte)
4240 return true;
4241
4242 // Otherwise, this byte is kept.
4243 }
4244
4245 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4246 ByteValues);
4247 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004248 }
4249
Chris Lattner8c34cd22008-10-05 02:13:19 +00004250 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4251 // the input value to the bswap. Some observations: 1) if more than one byte
4252 // is demanded from this input, then it could not be successfully assembled
4253 // into a byteswap. At least one of the two bytes would not be aligned with
4254 // their ultimate destination.
4255 if (!isPowerOf2_32(ByteMask)) return true;
4256 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004257
Chris Lattner8c34cd22008-10-05 02:13:19 +00004258 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4259 // is demanded, it needs to go into byte 0 of the result. This means that the
4260 // byte needs to be shifted until it lands in the right byte bucket. The
4261 // shift amount depends on the position: if the byte is coming from the high
4262 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4263 // low part, it must be shifted left.
4264 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4265 if (InputByteNo < ByteValues.size()/2) {
4266 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4267 return true;
4268 } else {
4269 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4270 return true;
4271 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004272
4273 // If the destination byte value is already defined, the values are or'd
4274 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004275 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004276 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004277 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004278 return false;
4279}
4280
4281/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4282/// If so, insert the new bswap intrinsic and return it.
4283Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004284 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004285 if (!ITy || ITy->getBitWidth() % 16 ||
4286 // ByteMask only allows up to 32-byte values.
4287 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004288 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004289
4290 /// ByteValues - For each byte of the result, we keep track of which value
4291 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004292 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004293 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004294
4295 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004296 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4297 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004298 return 0;
4299
4300 // Check to see if all of the bytes come from the same value.
4301 Value *V = ByteValues[0];
4302 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4303
4304 // Check to make sure that all of the bytes come from the same value.
4305 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4306 if (ByteValues[i] != V)
4307 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004308 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004309 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004310 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004311 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004312}
4313
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004314/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4315/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4316/// we can simplify this expression to "cond ? C : D or B".
4317static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4318 Value *C, Value *D) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004319 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004320 Value *Cond = 0;
Chris Lattner159c35b2009-01-05 23:53:12 +00004321 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004322 return 0;
4323
Chris Lattnera6a474d2008-11-16 04:26:55 +00004324 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner159c35b2009-01-05 23:53:12 +00004325 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004326 return SelectInst::Create(Cond, C, B);
Chris Lattner159c35b2009-01-05 23:53:12 +00004327 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004328 return SelectInst::Create(Cond, C, B);
4329 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner159c35b2009-01-05 23:53:12 +00004330 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004331 return SelectInst::Create(Cond, C, D);
Chris Lattner159c35b2009-01-05 23:53:12 +00004332 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004333 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004334 return 0;
4335}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004336
Chris Lattner69d4ced2008-11-16 05:20:07 +00004337/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4338Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4339 ICmpInst *LHS, ICmpInst *RHS) {
4340 Value *Val, *Val2;
4341 ConstantInt *LHSCst, *RHSCst;
4342 ICmpInst::Predicate LHSCC, RHSCC;
4343
4344 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4345 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4346 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4347 return 0;
4348
4349 // From here on, we only handle:
4350 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4351 if (Val != Val2) return 0;
4352
4353 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4354 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4355 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4356 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4357 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4358 return 0;
4359
4360 // We can't fold (ugt x, C) | (sgt x, C2).
4361 if (!PredicatesFoldable(LHSCC, RHSCC))
4362 return 0;
4363
4364 // Ensure that the larger constant is on the RHS.
4365 bool ShouldSwap;
4366 if (ICmpInst::isSignedPredicate(LHSCC) ||
4367 (ICmpInst::isEquality(LHSCC) &&
4368 ICmpInst::isSignedPredicate(RHSCC)))
4369 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4370 else
4371 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4372
4373 if (ShouldSwap) {
4374 std::swap(LHS, RHS);
4375 std::swap(LHSCst, RHSCst);
4376 std::swap(LHSCC, RHSCC);
4377 }
4378
4379 // At this point, we know we have have two icmp instructions
4380 // comparing a value against two constants and or'ing the result
4381 // together. Because of the above check, we know that we only have
4382 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4383 // FoldICmpLogical check above), that the two constants are not
4384 // equal.
4385 assert(LHSCst != RHSCst && "Compares not folded above?");
4386
4387 switch (LHSCC) {
4388 default: assert(0 && "Unknown integer condition code!");
4389 case ICmpInst::ICMP_EQ:
4390 switch (RHSCC) {
4391 default: assert(0 && "Unknown integer condition code!");
4392 case ICmpInst::ICMP_EQ:
4393 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4394 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4395 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4396 Val->getName()+".off");
4397 InsertNewInstBefore(Add, I);
4398 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4399 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4400 }
4401 break; // (X == 13 | X == 15) -> no change
4402 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4403 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4404 break;
4405 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4406 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4407 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4408 return ReplaceInstUsesWith(I, RHS);
4409 }
4410 break;
4411 case ICmpInst::ICMP_NE:
4412 switch (RHSCC) {
4413 default: assert(0 && "Unknown integer condition code!");
4414 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4415 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4416 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4417 return ReplaceInstUsesWith(I, LHS);
4418 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4419 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4420 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4421 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4422 }
4423 break;
4424 case ICmpInst::ICMP_ULT:
4425 switch (RHSCC) {
4426 default: assert(0 && "Unknown integer condition code!");
4427 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4428 break;
4429 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4430 // If RHSCst is [us]MAXINT, it is always false. Not handling
4431 // this can cause overflow.
4432 if (RHSCst->isMaxValue(false))
4433 return ReplaceInstUsesWith(I, LHS);
4434 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4435 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4436 break;
4437 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4438 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4439 return ReplaceInstUsesWith(I, RHS);
4440 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4441 break;
4442 }
4443 break;
4444 case ICmpInst::ICMP_SLT:
4445 switch (RHSCC) {
4446 default: assert(0 && "Unknown integer condition code!");
4447 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4448 break;
4449 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4450 // If RHSCst is [us]MAXINT, it is always false. Not handling
4451 // this can cause overflow.
4452 if (RHSCst->isMaxValue(true))
4453 return ReplaceInstUsesWith(I, LHS);
4454 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4455 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4456 break;
4457 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4458 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4459 return ReplaceInstUsesWith(I, RHS);
4460 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4461 break;
4462 }
4463 break;
4464 case ICmpInst::ICMP_UGT:
4465 switch (RHSCC) {
4466 default: assert(0 && "Unknown integer condition code!");
4467 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4468 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4469 return ReplaceInstUsesWith(I, LHS);
4470 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4471 break;
4472 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4473 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4474 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4475 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4476 break;
4477 }
4478 break;
4479 case ICmpInst::ICMP_SGT:
4480 switch (RHSCC) {
4481 default: assert(0 && "Unknown integer condition code!");
4482 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4483 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4484 return ReplaceInstUsesWith(I, LHS);
4485 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4486 break;
4487 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4488 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4489 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4490 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4491 break;
4492 }
4493 break;
4494 }
4495 return 0;
4496}
4497
Bill Wendlinga698a472008-12-01 08:23:25 +00004498/// FoldOrWithConstants - This helper function folds:
4499///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004500/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004501///
4502/// into:
4503///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004504/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004505///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004506/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004507Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004508 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004509 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4510 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004511
Bill Wendling286a0542008-12-02 06:24:20 +00004512 Value *V1 = 0;
4513 ConstantInt *CI2 = 0;
4514 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004515
Bill Wendling29976b92008-12-02 06:18:11 +00004516 APInt Xor = CI1->getValue() ^ CI2->getValue();
4517 if (!Xor.isAllOnesValue()) return 0;
4518
Bill Wendling286a0542008-12-02 06:24:20 +00004519 if (V1 == A || V1 == B) {
Bill Wendling29976b92008-12-02 06:18:11 +00004520 Instruction *NewOp =
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004521 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4522 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004523 }
4524
4525 return 0;
4526}
4527
Chris Lattner7e708292002-06-25 16:13:24 +00004528Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004529 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004530 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004531
Chris Lattner42593e62007-03-24 23:56:43 +00004532 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004533 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004534
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004535 // or X, X = X
4536 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004537 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004538
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004539 // See if we can simplify any instructions used by the instruction whose sole
4540 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004541 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004542 if (SimplifyDemandedInstructionBits(I))
Chris Lattner42593e62007-03-24 23:56:43 +00004543 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004544 } else if (isa<ConstantAggregateZero>(Op1)) {
4545 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4546 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4547 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4548 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004549 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004550
4551
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004552
Chris Lattner3f5b8772002-05-06 16:14:14 +00004553 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004555 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004556 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4557 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004558 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004559 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004560 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004561 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004562 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004563 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004564
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004565 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4566 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004567 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004568 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004569 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004570 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004571 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004572 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004573
4574 // Try to fold constant and into select arguments.
4575 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004576 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004577 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004578 if (isa<PHINode>(Op0))
4579 if (Instruction *NV = FoldOpIntoPhi(I))
4580 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004581 }
4582
Chris Lattner4f637d42006-01-06 17:59:59 +00004583 Value *A = 0, *B = 0;
4584 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004585
4586 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4587 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4588 return ReplaceInstUsesWith(I, Op1);
4589 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4590 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4591 return ReplaceInstUsesWith(I, Op0);
4592
Chris Lattner6423d4c2006-07-10 20:25:24 +00004593 // (A | B) | C and A | (B | C) -> bswap if possible.
4594 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004595 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004596 match(Op1, m_Or(m_Value(), m_Value())) ||
4597 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4598 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004599 if (Instruction *BSwap = MatchBSwap(I))
4600 return BSwap;
4601 }
4602
Chris Lattner6e4c6492005-05-09 04:58:36 +00004603 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4604 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004605 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004606 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004607 InsertNewInstBefore(NOr, I);
4608 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004609 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004610 }
4611
4612 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4613 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004614 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004615 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004616 InsertNewInstBefore(NOr, I);
4617 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004618 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004619 }
4620
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004621 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004622 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004623 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4624 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004625 Value *V1 = 0, *V2 = 0, *V3 = 0;
4626 C1 = dyn_cast<ConstantInt>(C);
4627 C2 = dyn_cast<ConstantInt>(D);
4628 if (C1 && C2) { // (A & C1)|(B & C2)
4629 // If we have: ((V + N) & C1) | (V & C2)
4630 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4631 // replace with V+N.
4632 if (C1->getValue() == ~C2->getValue()) {
4633 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4634 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4635 // Add commutes, try both ways.
4636 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4637 return ReplaceInstUsesWith(I, A);
4638 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4639 return ReplaceInstUsesWith(I, A);
4640 }
4641 // Or commutes, try both ways.
4642 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4643 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4644 // Add commutes, try both ways.
4645 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4646 return ReplaceInstUsesWith(I, B);
4647 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4648 return ReplaceInstUsesWith(I, B);
4649 }
4650 }
Chris Lattner044e5332007-04-08 08:01:49 +00004651 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004652 }
4653
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004654 // Check to see if we have any common things being and'ed. If so, find the
4655 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004656 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4657 if (A == B) // (A & C)|(A & D) == A & (C|D)
4658 V1 = A, V2 = C, V3 = D;
4659 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4660 V1 = A, V2 = B, V3 = C;
4661 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4662 V1 = C, V2 = A, V3 = D;
4663 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4664 V1 = C, V2 = A, V3 = B;
4665
4666 if (V1) {
4667 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004668 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4669 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004670 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004671 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004672
Dan Gohman1975d032008-10-30 20:40:10 +00004673 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004674 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4675 return Match;
4676 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4677 return Match;
4678 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4679 return Match;
4680 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4681 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004682
Bill Wendlingb01865c2008-11-30 13:52:49 +00004683 // ((A&~B)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004684 if ((match(C, m_Not(m_Specific(D))) &&
4685 match(B, m_Not(m_Specific(A)))))
4686 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004687 // ((~B&A)|(~A&B)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004688 if ((match(A, m_Not(m_Specific(D))) &&
4689 match(B, m_Not(m_Specific(C)))))
4690 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004691 // ((A&~B)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004692 if ((match(C, m_Not(m_Specific(B))) &&
4693 match(D, m_Not(m_Specific(A)))))
4694 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004695 // ((~B&A)|(B&~A)) -> A^B
Bill Wendling03aae5f2008-12-01 08:09:47 +00004696 if ((match(A, m_Not(m_Specific(B))) &&
4697 match(D, m_Not(m_Specific(C)))))
4698 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004699 }
Chris Lattnere511b742006-11-14 07:46:50 +00004700
4701 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004702 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4703 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4704 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004705 SI0->getOperand(1) == SI1->getOperand(1) &&
4706 (SI0->hasOneUse() || SI1->hasOneUse())) {
4707 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004708 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004709 SI1->getOperand(0),
4710 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004711 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004712 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004713 }
4714 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004715
Bill Wendlingb3833d12008-12-01 01:07:11 +00004716 // ((A|B)&1)|(B&-2) -> (A&1) | B
4717 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4718 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004719 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004720 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004721 }
4722 // (B&-2)|((A|B)&1) -> (A&1) | B
4723 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4724 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004725 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004726 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004727 }
4728
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004729 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4730 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004731 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004732 } else {
4733 A = 0;
4734 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004735 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004736 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4737 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004738 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004739
Misha Brukmancb6267b2004-07-30 12:50:08 +00004740 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004741 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004742 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004743 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004744 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004745 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004746 }
Chris Lattnera2881962003-02-18 19:28:33 +00004747
Reid Spencere4d87aa2006-12-23 06:05:41 +00004748 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4749 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4750 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004751 return R;
4752
Chris Lattner69d4ced2008-11-16 05:20:07 +00004753 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4754 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4755 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004756 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004757
4758 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004759 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004760 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004761 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004762 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4763 !isa<ICmpInst>(Op1C->getOperand(0))) {
4764 const Type *SrcTy = Op0C->getOperand(0)->getType();
4765 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4766 // Only do this if the casts both really cause code to be
4767 // generated.
4768 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4769 I.getType(), TD) &&
4770 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4771 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004772 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004773 Op1C->getOperand(0),
4774 I.getName());
4775 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004776 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004777 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004778 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004779 }
Chris Lattner99c65742007-10-24 05:38:08 +00004780 }
4781
4782
4783 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4784 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4785 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4786 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004787 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng40300622008-10-14 18:44:08 +00004788 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner99c65742007-10-24 05:38:08 +00004789 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4790 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4791 // If either of the constants are nans, then the whole thing returns
4792 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004793 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004794 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4795
4796 // Otherwise, no need to compare the two constants, compare the
4797 // rest.
4798 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4799 RHS->getOperand(0));
4800 }
Evan Cheng40300622008-10-14 18:44:08 +00004801 } else {
4802 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4803 FCmpInst::Predicate Op0CC, Op1CC;
4804 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4805 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4806 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4807 // Swap RHS operands to match LHS.
4808 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4809 std::swap(Op1LHS, Op1RHS);
4810 }
4811 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4812 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4813 if (Op0CC == Op1CC)
4814 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4815 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4816 Op1CC == FCmpInst::FCMP_TRUE)
4817 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4818 else if (Op0CC == FCmpInst::FCMP_FALSE)
4819 return ReplaceInstUsesWith(I, Op1);
4820 else if (Op1CC == FCmpInst::FCMP_FALSE)
4821 return ReplaceInstUsesWith(I, Op0);
4822 bool Op0Ordered;
4823 bool Op1Ordered;
4824 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4825 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4826 if (Op0Ordered == Op1Ordered) {
4827 // If both are ordered or unordered, return a new fcmp with
4828 // or'ed predicates.
4829 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4830 Op0LHS, Op0RHS);
4831 if (Instruction *I = dyn_cast<Instruction>(RV))
4832 return I;
4833 // Otherwise, it's a constant boolean value...
4834 return ReplaceInstUsesWith(I, RV);
4835 }
4836 }
4837 }
4838 }
Chris Lattner99c65742007-10-24 05:38:08 +00004839 }
4840 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004841
Chris Lattner7e708292002-06-25 16:13:24 +00004842 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004843}
4844
Dan Gohman844731a2008-05-13 00:00:25 +00004845namespace {
4846
Chris Lattnerc317d392004-02-16 01:20:27 +00004847// XorSelf - Implements: X ^ X --> 0
4848struct XorSelf {
4849 Value *RHS;
4850 XorSelf(Value *rhs) : RHS(rhs) {}
4851 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4852 Instruction *apply(BinaryOperator &Xor) const {
4853 return &Xor;
4854 }
4855};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004856
Dan Gohman844731a2008-05-13 00:00:25 +00004857}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004858
Chris Lattner7e708292002-06-25 16:13:24 +00004859Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004860 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004861 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004862
Evan Chengd34af782008-03-25 20:07:13 +00004863 if (isa<UndefValue>(Op1)) {
4864 if (isa<UndefValue>(Op0))
4865 // Handle undef ^ undef -> 0 special case. This is a common
4866 // idiom (misuse).
4867 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004868 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004869 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004870
Chris Lattnerc317d392004-02-16 01:20:27 +00004871 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4872 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004873 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004874 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004875 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004876
4877 // See if we can simplify any instructions used by the instruction whose sole
4878 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004879 if (!isa<VectorType>(I.getType())) {
Chris Lattner886ab6c2009-01-31 08:15:18 +00004880 if (SimplifyDemandedInstructionBits(I))
Reid Spencera03d45f2007-03-22 22:19:58 +00004881 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004882 } else if (isa<ConstantAggregateZero>(Op1)) {
4883 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004884 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004885
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004886 // Is this a ~ operation?
4887 if (Value *NotOp = dyn_castNotVal(&I)) {
4888 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4889 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4890 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4891 if (Op0I->getOpcode() == Instruction::And ||
4892 Op0I->getOpcode() == Instruction::Or) {
4893 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4894 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4895 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004896 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004897 Op0I->getOperand(1)->getName()+".not");
4898 InsertNewInstBefore(NotY, I);
4899 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004900 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004901 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004902 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004903 }
4904 }
4905 }
4906 }
4907
4908
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004909 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004910 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00004911 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004912 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004913 return new ICmpInst(ICI->getInversePredicate(),
4914 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004915
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004916 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4917 return new FCmpInst(FCI->getInversePredicate(),
4918 FCI->getOperand(0), FCI->getOperand(1));
4919 }
4920
Nick Lewycky517e1f52008-05-31 19:01:33 +00004921 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4922 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4923 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4924 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4925 Instruction::CastOps Opcode = Op0C->getOpcode();
4926 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4927 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4928 Op0C->getDestTy())) {
4929 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4930 CI->getOpcode(), CI->getInversePredicate(),
4931 CI->getOperand(0), CI->getOperand(1)), I);
4932 NewCI->takeName(CI);
4933 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4934 }
4935 }
4936 }
4937 }
4938 }
4939
Reid Spencere4d87aa2006-12-23 06:05:41 +00004940 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004941 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004942 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4943 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004944 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4945 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004946 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004947 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004948 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004949
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004950 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004951 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004952 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004953 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004954 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004955 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004956 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004957 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004958 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004959 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004960 // (X + C) ^ signbit -> (X + C + signbit)
4961 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004962 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004963
Chris Lattner7c4049c2004-01-12 19:35:11 +00004964 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004965 } else if (Op0I->getOpcode() == Instruction::Or) {
4966 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004967 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004968 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4969 // Anything in both C1 and C2 is known to be zero, remove it from
4970 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004971 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004972 NewRHS = ConstantExpr::getAnd(NewRHS,
4973 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004974 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004975 I.setOperand(0, Op0I->getOperand(0));
4976 I.setOperand(1, NewRHS);
4977 return &I;
4978 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004979 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004980 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004981 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004982
4983 // Try to fold constant and into select arguments.
4984 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004985 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004986 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004987 if (isa<PHINode>(Op0))
4988 if (Instruction *NV = FoldOpIntoPhi(I))
4989 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004990 }
4991
Chris Lattner8d969642003-03-10 23:06:50 +00004992 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004993 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004994 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004995
Chris Lattner8d969642003-03-10 23:06:50 +00004996 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004997 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004998 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004999
Chris Lattner318bf792007-03-18 22:51:34 +00005000
5001 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5002 if (Op1I) {
5003 Value *A, *B;
5004 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5005 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005006 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005007 I.swapOperands();
5008 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005009 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005010 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005011 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005012 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005013 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5014 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5015 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5016 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Chris Lattner318bf792007-03-18 22:51:34 +00005017 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005018 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005019 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005020 std::swap(A, B);
5021 }
Chris Lattner318bf792007-03-18 22:51:34 +00005022 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005023 I.swapOperands(); // Simplified below.
5024 std::swap(Op0, Op1);
5025 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005026 }
Chris Lattner318bf792007-03-18 22:51:34 +00005027 }
5028
5029 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5030 if (Op0I) {
5031 Value *A, *B;
5032 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5033 if (A == Op1) // (B|A)^B == (A|B)^B
5034 std::swap(A, B);
5035 if (B == Op1) { // (A|B)^B == A & ~B
5036 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005037 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5038 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005039 }
Chris Lattnercb504b92008-11-16 05:38:51 +00005040 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5041 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5042 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5043 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Chris Lattner318bf792007-03-18 22:51:34 +00005044 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5045 if (A == Op1) // (A&B)^A -> (B&A)^A
5046 std::swap(A, B);
5047 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005048 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005049 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005050 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5051 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005052 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005053 }
Chris Lattner318bf792007-03-18 22:51:34 +00005054 }
5055
5056 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5057 if (Op0I && Op1I && Op0I->isShift() &&
5058 Op0I->getOpcode() == Op1I->getOpcode() &&
5059 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5060 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5061 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005062 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005063 Op1I->getOperand(0),
5064 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005065 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005066 Op1I->getOperand(1));
5067 }
5068
5069 if (Op0I && Op1I) {
5070 Value *A, *B, *C, *D;
5071 // (A & B)^(A | B) -> A ^ B
5072 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5073 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5074 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005075 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005076 }
5077 // (A | B)^(A & B) -> A ^ B
5078 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5079 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5080 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005081 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005082 }
5083
5084 // (A & B)^(C & D)
5085 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5086 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5087 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5088 // (X & Y)^(X & Y) -> (Y^Z) & X
5089 Value *X = 0, *Y = 0, *Z = 0;
5090 if (A == C)
5091 X = A, Y = B, Z = D;
5092 else if (A == D)
5093 X = A, Y = B, Z = C;
5094 else if (B == C)
5095 X = B, Y = A, Z = D;
5096 else if (B == D)
5097 X = B, Y = A, Z = C;
5098
5099 if (X) {
5100 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005101 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5102 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005103 }
5104 }
5105 }
5106
Reid Spencere4d87aa2006-12-23 06:05:41 +00005107 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5108 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5109 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005110 return R;
5111
Chris Lattner6fc205f2006-05-05 06:39:07 +00005112 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005113 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005114 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005115 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5116 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005117 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005118 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005119 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5120 I.getType(), TD) &&
5121 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5122 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005123 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005124 Op1C->getOperand(0),
5125 I.getName());
5126 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005127 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005128 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005129 }
Chris Lattner99c65742007-10-24 05:38:08 +00005130 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005131
Chris Lattner7e708292002-06-25 16:13:24 +00005132 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005133}
5134
Chris Lattnera96879a2004-09-29 17:40:11 +00005135/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5136/// overflowed for this type.
5137static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005138 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005139 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005140
Reid Spencere4e40032007-03-21 23:19:50 +00005141 if (IsSigned)
5142 if (In2->getValue().isNegative())
5143 return Result->getValue().sgt(In1->getValue());
5144 else
5145 return Result->getValue().slt(In1->getValue());
5146 else
5147 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005148}
5149
Dan Gohman1df3fd62008-09-10 23:30:57 +00005150/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5151/// overflowed for this type.
5152static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5153 ConstantInt *In2, bool IsSigned = false) {
Dan Gohmanbcb37fd2008-09-11 18:53:02 +00005154 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohman1df3fd62008-09-10 23:30:57 +00005155
5156 if (IsSigned)
5157 if (In2->getValue().isNegative())
5158 return Result->getValue().slt(In1->getValue());
5159 else
5160 return Result->getValue().sgt(In1->getValue());
5161 else
5162 return Result->getValue().ugt(In1->getValue());
5163}
5164
Chris Lattner574da9b2005-01-13 20:14:25 +00005165/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5166/// code necessary to compute the offset from the base pointer (without adding
5167/// in the base pointer). Return the result as a signed integer of intptr size.
5168static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5169 TargetData &TD = IC.getTargetData();
5170 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 const Type *IntPtrTy = TD.getIntPtrType();
5172 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005173
5174 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005175 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005176 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005177
Gabor Greif177dd3f2008-06-12 21:37:33 +00005178 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5179 ++i, ++GTI) {
5180 Value *Op = *i;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005181 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005182 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5183 if (OpC->isZero()) continue;
5184
5185 // Handle a struct index, which adds its field offset to the pointer.
5186 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5187 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5188
5189 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5190 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005191 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005192 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005193 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005194 ConstantInt::get(IntPtrTy, Size),
5195 GEP->getName()+".offs"), I);
5196 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005197 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005198
5199 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5200 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5201 Scale = ConstantExpr::getMul(OC, Scale);
5202 if (Constant *RC = dyn_cast<Constant>(Result))
5203 Result = ConstantExpr::getAdd(RC, Scale);
5204 else {
5205 // Emit an add instruction.
5206 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005207 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005208 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005209 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005210 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005211 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005212 // Convert to correct type.
5213 if (Op->getType() != IntPtrTy) {
5214 if (Constant *OpC = dyn_cast<Constant>(Op))
5215 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5216 else
5217 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5218 Op->getName()+".c"), I);
5219 }
5220 if (Size != 1) {
5221 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5222 if (Constant *OpC = dyn_cast<Constant>(Op))
5223 Op = ConstantExpr::getMul(OpC, Scale);
5224 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005225 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005226 GEP->getName()+".idx"), I);
5227 }
5228
5229 // Emit an add instruction.
5230 if (isa<Constant>(Op) && isa<Constant>(Result))
5231 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5232 cast<Constant>(Result));
5233 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005234 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005235 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005236 }
5237 return Result;
5238}
5239
Chris Lattner10c0d912008-04-22 02:53:33 +00005240
5241/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5242/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5243/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5244/// complex, and scales are involved. The above expression would also be legal
5245/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5246/// later form is less amenable to optimization though, and we are allowed to
5247/// generate the first by knowing that pointer arithmetic doesn't overflow.
5248///
5249/// If we can't emit an optimized form for this expression, this returns null.
5250///
5251static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5252 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005253 TargetData &TD = IC.getTargetData();
5254 gep_type_iterator GTI = gep_type_begin(GEP);
5255
5256 // Check to see if this gep only has a single variable index. If so, and if
5257 // any constant indices are a multiple of its scale, then we can compute this
5258 // in terms of the scale of the variable index. For example, if the GEP
5259 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5260 // because the expression will cross zero at the same point.
5261 unsigned i, e = GEP->getNumOperands();
5262 int64_t Offset = 0;
5263 for (i = 1; i != e; ++i, ++GTI) {
5264 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5265 // Compute the aggregate offset of constant indices.
5266 if (CI->isZero()) continue;
5267
5268 // Handle a struct index, which adds its field offset to the pointer.
5269 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5270 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5271 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005272 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005273 Offset += Size*CI->getSExtValue();
5274 }
5275 } else {
5276 // Found our variable index.
5277 break;
5278 }
5279 }
5280
5281 // If there are no variable indices, we must have a constant offset, just
5282 // evaluate it the general way.
5283 if (i == e) return 0;
5284
5285 Value *VariableIdx = GEP->getOperand(i);
5286 // Determine the scale factor of the variable element. For example, this is
5287 // 4 if the variable index is into an array of i32.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005288 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005289
5290 // Verify that there are no other variable indices. If so, emit the hard way.
5291 for (++i, ++GTI; i != e; ++i, ++GTI) {
5292 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5293 if (!CI) return 0;
5294
5295 // Compute the aggregate offset of constant indices.
5296 if (CI->isZero()) continue;
5297
5298 // Handle a struct index, which adds its field offset to the pointer.
5299 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5300 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5301 } else {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005302 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005303 Offset += Size*CI->getSExtValue();
5304 }
5305 }
5306
5307 // Okay, we know we have a single variable index, which must be a
5308 // pointer/array/vector index. If there is no offset, life is simple, return
5309 // the index.
5310 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5311 if (Offset == 0) {
5312 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5313 // we don't need to bother extending: the extension won't affect where the
5314 // computation crosses zero.
5315 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5316 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5317 VariableIdx->getNameStart(), &I);
5318 return VariableIdx;
5319 }
5320
5321 // Otherwise, there is an index. The computation we will do will be modulo
5322 // the pointer size, so get it.
5323 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5324
5325 Offset &= PtrSizeMask;
5326 VariableScale &= PtrSizeMask;
5327
5328 // To do this transformation, any constant index must be a multiple of the
5329 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5330 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5331 // multiple of the variable scale.
5332 int64_t NewOffs = Offset / (int64_t)VariableScale;
5333 if (Offset != NewOffs*(int64_t)VariableScale)
5334 return 0;
5335
5336 // Okay, we can do this evaluation. Start by converting the index to intptr.
5337 const Type *IntPtrTy = TD.getIntPtrType();
5338 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005339 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005340 true /*SExt*/,
5341 VariableIdx->getNameStart(), &I);
5342 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005343 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005344}
5345
5346
Reid Spencere4d87aa2006-12-23 06:05:41 +00005347/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005348/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005349Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5350 ICmpInst::Predicate Cond,
5351 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005352 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005353
Chris Lattner10c0d912008-04-22 02:53:33 +00005354 // Look through bitcasts.
5355 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5356 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005357
Chris Lattner574da9b2005-01-13 20:14:25 +00005358 Value *PtrBase = GEPLHS->getOperand(0);
5359 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005360 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005361 // This transformation (ignoring the base and scales) is valid because we
5362 // know pointers can't overflow. See if we can output an optimized form.
5363 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5364
5365 // If not, synthesize the offset the hard way.
5366 if (Offset == 0)
5367 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005368 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5369 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005370 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005371 // If the base pointers are different, but the indices are the same, just
5372 // compare the base pointer.
5373 if (PtrBase != GEPRHS->getOperand(0)) {
5374 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005375 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005376 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005377 if (IndicesTheSame)
5378 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5379 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5380 IndicesTheSame = false;
5381 break;
5382 }
5383
5384 // If all indices are the same, just compare the base pointers.
5385 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005386 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5387 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005388
5389 // Otherwise, the base pointers are different and the indices are
5390 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005391 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005392 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005393
Chris Lattnere9d782b2005-01-13 22:25:21 +00005394 // If one of the GEPs has all zero indices, recurse.
5395 bool AllZeros = true;
5396 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5397 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5398 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5399 AllZeros = false;
5400 break;
5401 }
5402 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005403 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5404 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005405
5406 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005407 AllZeros = true;
5408 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5409 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5410 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5411 AllZeros = false;
5412 break;
5413 }
5414 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005415 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005416
Chris Lattner4401c9c2005-01-14 00:20:05 +00005417 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5418 // If the GEPs only differ by one index, compare it.
5419 unsigned NumDifferences = 0; // Keep track of # differences.
5420 unsigned DiffOperand = 0; // The operand that differs.
5421 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5422 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005423 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5424 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005425 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005426 NumDifferences = 2;
5427 break;
5428 } else {
5429 if (NumDifferences++) break;
5430 DiffOperand = i;
5431 }
5432 }
5433
5434 if (NumDifferences == 0) // SAME GEP?
5435 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005436 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005437 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005438
Chris Lattner4401c9c2005-01-14 00:20:05 +00005439 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005440 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5441 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005442 // Make sure we do a signed comparison here.
5443 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005444 }
5445 }
5446
Reid Spencere4d87aa2006-12-23 06:05:41 +00005447 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005448 // the result to fold to a constant!
5449 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5450 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5451 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5452 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5453 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005454 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005455 }
5456 }
5457 return 0;
5458}
5459
Chris Lattnera5406232008-05-19 20:18:56 +00005460/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5461///
5462Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5463 Instruction *LHSI,
5464 Constant *RHSC) {
5465 if (!isa<ConstantFP>(RHSC)) return 0;
5466 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5467
5468 // Get the width of the mantissa. We don't want to hack on conversions that
5469 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005470 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005471 if (MantissaWidth == -1) return 0; // Unknown.
5472
5473 // Check to see that the input is converted from an integer type that is small
5474 // enough that preserves all bits. TODO: check here for "known" sign bits.
5475 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5476 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5477
5478 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005479 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5480 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005481 ++InputSize;
5482
5483 // If the conversion would lose info, don't hack on this.
5484 if ((int)InputSize > MantissaWidth)
5485 return 0;
5486
5487 // Otherwise, we can potentially simplify the comparison. We know that it
5488 // will always come through as an integer value and we know the constant is
5489 // not a NAN (it would have been previously simplified).
5490 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5491
5492 ICmpInst::Predicate Pred;
5493 switch (I.getPredicate()) {
5494 default: assert(0 && "Unexpected predicate!");
5495 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005496 case FCmpInst::FCMP_OEQ:
5497 Pred = ICmpInst::ICMP_EQ;
5498 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005499 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005500 case FCmpInst::FCMP_OGT:
5501 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5502 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005503 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005504 case FCmpInst::FCMP_OGE:
5505 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5506 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005507 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005508 case FCmpInst::FCMP_OLT:
5509 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5510 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005511 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005512 case FCmpInst::FCMP_OLE:
5513 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5514 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005515 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005516 case FCmpInst::FCMP_ONE:
5517 Pred = ICmpInst::ICMP_NE;
5518 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005519 case FCmpInst::FCMP_ORD:
Eli Friedman8b019c82008-11-30 22:48:49 +00005520 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005521 case FCmpInst::FCMP_UNO:
Eli Friedman8b019c82008-11-30 22:48:49 +00005522 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera5406232008-05-19 20:18:56 +00005523 }
5524
5525 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5526
5527 // Now we know that the APFloat is a normal number, zero or inf.
5528
Chris Lattner85162782008-05-20 03:50:52 +00005529 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005530 // comparing an i8 to 300.0.
5531 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5532
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005533 if (!LHSUnsigned) {
5534 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5535 // and large values.
5536 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5537 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5538 APFloat::rmNearestTiesToEven);
5539 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5540 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5541 Pred == ICmpInst::ICMP_SLE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005542 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5543 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005544 }
5545 } else {
5546 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5547 // +INF and large values.
5548 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5549 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5550 APFloat::rmNearestTiesToEven);
5551 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5552 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5553 Pred == ICmpInst::ICMP_ULE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005554 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5555 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005556 }
Chris Lattnera5406232008-05-19 20:18:56 +00005557 }
5558
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005559 if (!LHSUnsigned) {
5560 // See if the RHS value is < SignedMin.
5561 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5562 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5563 APFloat::rmNearestTiesToEven);
5564 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5565 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5566 Pred == ICmpInst::ICMP_SGE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005567 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5568 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005569 }
Chris Lattnera5406232008-05-19 20:18:56 +00005570 }
5571
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005572 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5573 // [0, UMAX], but it may still be fractional. See if it is fractional by
5574 // casting the FP value to the integer value and back, checking for equality.
5575 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnera5406232008-05-19 20:18:56 +00005576 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5577 if (!RHS.isZero() &&
5578 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005579 // If we had a comparison against a fractional value, we have to adjust the
5580 // compare predicate and sometimes the value. RHSC is rounded towards zero
5581 // at this point.
Chris Lattnera5406232008-05-19 20:18:56 +00005582 switch (Pred) {
5583 default: assert(0 && "Unexpected integer comparison!");
5584 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedman8b019c82008-11-30 22:48:49 +00005585 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005586 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedman8b019c82008-11-30 22:48:49 +00005587 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005588 case ICmpInst::ICMP_ULE:
5589 // (float)int <= 4.4 --> int <= 4
5590 // (float)int <= -4.4 --> false
5591 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005592 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005593 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005594 case ICmpInst::ICMP_SLE:
5595 // (float)int <= 4.4 --> int <= 4
5596 // (float)int <= -4.4 --> int < -4
5597 if (RHS.isNegative())
5598 Pred = ICmpInst::ICMP_SLT;
5599 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005600 case ICmpInst::ICMP_ULT:
5601 // (float)int < -4.4 --> false
5602 // (float)int < 4.4 --> int <= 4
5603 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005604 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005605 Pred = ICmpInst::ICMP_ULE;
5606 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005607 case ICmpInst::ICMP_SLT:
5608 // (float)int < -4.4 --> int < -4
5609 // (float)int < 4.4 --> int <= 4
5610 if (!RHS.isNegative())
5611 Pred = ICmpInst::ICMP_SLE;
5612 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005613 case ICmpInst::ICMP_UGT:
5614 // (float)int > 4.4 --> int > 4
5615 // (float)int > -4.4 --> true
5616 if (RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005617 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005618 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005619 case ICmpInst::ICMP_SGT:
5620 // (float)int > 4.4 --> int > 4
5621 // (float)int > -4.4 --> int >= -4
5622 if (RHS.isNegative())
5623 Pred = ICmpInst::ICMP_SGE;
5624 break;
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005625 case ICmpInst::ICMP_UGE:
5626 // (float)int >= -4.4 --> true
5627 // (float)int >= 4.4 --> int > 4
5628 if (!RHS.isNegative())
Eli Friedman8b019c82008-11-30 22:48:49 +00005629 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005630 Pred = ICmpInst::ICMP_UGT;
5631 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005632 case ICmpInst::ICMP_SGE:
5633 // (float)int >= -4.4 --> int >= -4
5634 // (float)int >= 4.4 --> int > 4
5635 if (!RHS.isNegative())
5636 Pred = ICmpInst::ICMP_SGT;
5637 break;
5638 }
5639 }
5640
5641 // Lower this FP comparison into an appropriate integer version of the
5642 // comparison.
5643 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5644}
5645
Reid Spencere4d87aa2006-12-23 06:05:41 +00005646Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5647 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005648 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005649
Chris Lattner58e97462007-01-14 19:42:17 +00005650 // Fold trivial predicates.
5651 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005652 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005653 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedman8b019c82008-11-30 22:48:49 +00005654 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005655
5656 // Simplify 'fcmp pred X, X'
5657 if (Op0 == Op1) {
5658 switch (I.getPredicate()) {
5659 default: assert(0 && "Unknown predicate!");
5660 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5661 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5662 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedman8b019c82008-11-30 22:48:49 +00005663 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner58e97462007-01-14 19:42:17 +00005664 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5665 case FCmpInst::FCMP_OLT: // True if ordered and less than
5666 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedman8b019c82008-11-30 22:48:49 +00005667 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner58e97462007-01-14 19:42:17 +00005668
5669 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5670 case FCmpInst::FCMP_ULT: // True if unordered or less than
5671 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5672 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5673 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5674 I.setPredicate(FCmpInst::FCMP_UNO);
5675 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5676 return &I;
5677
5678 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5679 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5680 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5681 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5682 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5683 I.setPredicate(FCmpInst::FCMP_ORD);
5684 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5685 return &I;
5686 }
5687 }
5688
Reid Spencere4d87aa2006-12-23 06:05:41 +00005689 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005690 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005691
Reid Spencere4d87aa2006-12-23 06:05:41 +00005692 // Handle fcmp with constant RHS
5693 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005694 // If the constant is a nan, see if we can fold the comparison based on it.
5695 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5696 if (CFP->getValueAPF().isNaN()) {
5697 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedman8b019c82008-11-30 22:48:49 +00005698 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner85162782008-05-20 03:50:52 +00005699 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5700 "Comparison must be either ordered or unordered!");
5701 // True if unordered.
Eli Friedman8b019c82008-11-30 22:48:49 +00005702 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera5406232008-05-19 20:18:56 +00005703 }
5704 }
5705
Reid Spencere4d87aa2006-12-23 06:05:41 +00005706 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5707 switch (LHSI->getOpcode()) {
5708 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005709 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5710 // block. If in the same block, we're encouraging jump threading. If
5711 // not, we are just pessimizing the code by making an i1 phi.
5712 if (LHSI->getParent() == I.getParent())
5713 if (Instruction *NV = FoldOpIntoPhi(I))
5714 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005715 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005716 case Instruction::SIToFP:
5717 case Instruction::UIToFP:
5718 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5719 return NV;
5720 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005721 case Instruction::Select:
5722 // If either operand of the select is a constant, we can fold the
5723 // comparison into the select arms, which will cause one to be
5724 // constant folded and the select turned into a bitwise or.
5725 Value *Op1 = 0, *Op2 = 0;
5726 if (LHSI->hasOneUse()) {
5727 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5728 // Fold the known value into the constant operand.
5729 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5730 // Insert a new FCmp of the other select operand.
5731 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5732 LHSI->getOperand(2), RHSC,
5733 I.getName()), I);
5734 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5735 // Fold the known value into the constant operand.
5736 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5737 // Insert a new FCmp of the other select operand.
5738 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5739 LHSI->getOperand(1), RHSC,
5740 I.getName()), I);
5741 }
5742 }
5743
5744 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005745 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005746 break;
5747 }
5748 }
5749
5750 return Changed ? &I : 0;
5751}
5752
5753Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5754 bool Changed = SimplifyCompare(I);
5755 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5756 const Type *Ty = Op0->getType();
5757
5758 // icmp X, X
5759 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005760 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005761 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005762
5763 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005764 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005765
Reid Spencere4d87aa2006-12-23 06:05:41 +00005766 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005767 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005768 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5769 isa<ConstantPointerNull>(Op0)) &&
5770 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005771 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005772 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005773 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005774
Reid Spencere4d87aa2006-12-23 06:05:41 +00005775 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005776 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005777 switch (I.getPredicate()) {
5778 default: assert(0 && "Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005779 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005780 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005781 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005782 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005783 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005784 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005785 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005786
Reid Spencere4d87aa2006-12-23 06:05:41 +00005787 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005788 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005789 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005790 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005791 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005792 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005793 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005794 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005795 case ICmpInst::ICMP_SGT:
5796 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005797 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005798 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5799 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5800 InsertNewInstBefore(Not, I);
5801 return BinaryOperator::CreateAnd(Not, Op0);
5802 }
5803 case ICmpInst::ICMP_UGE:
5804 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5805 // FALL THROUGH
5806 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005807 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005808 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005809 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005810 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005811 case ICmpInst::ICMP_SGE:
5812 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5813 // FALL THROUGH
5814 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5815 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5816 InsertNewInstBefore(Not, I);
5817 return BinaryOperator::CreateOr(Not, Op0);
5818 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005819 }
Chris Lattner8b170942002-08-09 23:47:40 +00005820 }
5821
Dan Gohman81b28ce2008-09-16 18:46:06 +00005822 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005823 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerf2991842008-07-11 04:09:09 +00005824 Value *A, *B;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005825
Chris Lattnerb6566012008-01-05 01:18:20 +00005826 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5827 if (I.isEquality() && CI->isNullValue() &&
5828 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5829 // (icmp cond A B) if cond is equality
5830 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005831 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005832
Dan Gohman81b28ce2008-09-16 18:46:06 +00005833 // If we have an icmp le or icmp ge instruction, turn it into the
5834 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5835 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005836 switch (I.getPredicate()) {
5837 default: break;
5838 case ICmpInst::ICMP_ULE:
5839 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5840 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5841 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5842 case ICmpInst::ICMP_SLE:
5843 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5844 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5845 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5846 case ICmpInst::ICMP_UGE:
5847 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5848 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5849 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5850 case ICmpInst::ICMP_SGE:
5851 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5852 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5853 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5854 }
5855
Chris Lattner183661e2008-07-11 05:40:05 +00005856 // See if we can fold the comparison based on range information we can get
5857 // by checking whether bits are known to be zero or one in the input.
5858 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5859 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5860
5861 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005862 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005863 bool UnusedBit;
5864 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5865
Chris Lattner886ab6c2009-01-31 08:15:18 +00005866 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005867 isSignBit ? APInt::getSignBit(BitWidth)
5868 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005869 KnownZero, KnownOne, 0))
5870 return &I;
5871
5872 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00005873 // in. Compute the Min, Max and RHS values based on the known bits. For the
5874 // EQ and NE we use unsigned values.
5875 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner84dff672008-07-11 05:08:55 +00005876 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5877 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5878 else
5879 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5880
Chris Lattner183661e2008-07-11 05:40:05 +00005881 // If Min and Max are known to be the same, then SimplifyDemandedBits
5882 // figured out that the LHS is a constant. Just constant fold this now so
5883 // that code below can assume that Min != Max.
5884 if (Min == Max)
5885 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5886 ConstantInt::get(Min),
5887 CI));
5888
5889 // Based on the range information we know about the LHS, see if we can
5890 // simplify this comparison. For example, (x&4) < 8 is always true.
5891 const APInt &RHSVal = CI->getValue();
Chris Lattner84dff672008-07-11 05:08:55 +00005892 switch (I.getPredicate()) { // LE/GE have been folded already.
5893 default: assert(0 && "Unknown icmp opcode!");
5894 case ICmpInst::ICMP_EQ:
5895 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5896 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5897 break;
5898 case ICmpInst::ICMP_NE:
5899 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5900 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5901 break;
5902 case ICmpInst::ICMP_ULT:
Chris Lattner183661e2008-07-11 05:40:05 +00005903 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005904 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005905 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005906 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005907 if (RHSVal == Max) // A <u MAX -> A != MAX
5908 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5909 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5910 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5911
5912 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5913 if (CI->isMinValue(true))
5914 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5915 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005916 break;
5917 case ICmpInst::ICMP_UGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005918 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005919 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005920 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005921 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005922
5923 if (RHSVal == Min) // A >u MIN -> A != MIN
5924 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5925 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5926 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5927
5928 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5929 if (CI->isMaxValue(true))
5930 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5931 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner84dff672008-07-11 05:08:55 +00005932 break;
5933 case ICmpInst::ICMP_SLT:
Chris Lattner183661e2008-07-11 05:40:05 +00005934 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner84dff672008-07-11 05:08:55 +00005935 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerd01bee72008-07-11 06:40:29 +00005936 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner84dff672008-07-11 05:08:55 +00005937 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005938 if (RHSVal == Max) // A <s MAX -> A != MAX
5939 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattnera8ff4a82008-07-11 06:36:01 +00005940 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattnerf9685ac2008-07-11 06:38:16 +00005941 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005942 break;
5943 case ICmpInst::ICMP_SGT:
Chris Lattner183661e2008-07-11 05:40:05 +00005944 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner84dff672008-07-11 05:08:55 +00005945 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner183661e2008-07-11 05:40:05 +00005946 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner84dff672008-07-11 05:08:55 +00005947 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattner183661e2008-07-11 05:40:05 +00005948
5949 if (RHSVal == Min) // A >s MIN -> A != MIN
5950 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5951 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5952 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005953 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005954 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00005955 }
5956
5957 // Test if the ICmpInst instruction is used exclusively by a select as
5958 // part of a minimum or maximum operation. If so, refrain from doing
5959 // any other folding. This helps out other analyses which understand
5960 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5961 // and CodeGen. And in this case, at least one of the comparison
5962 // operands has at least one user besides the compare (the select),
5963 // which would often largely negate the benefit of folding anyway.
5964 if (I.hasOneUse())
5965 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5966 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5967 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5968 return 0;
5969
5970 // See if we are doing a comparison between a constant and an instruction that
5971 // can be folded into the comparison.
5972 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005973 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005974 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005976 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005977 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5978 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005979 }
5980
Chris Lattner01deb9d2007-04-03 17:43:25 +00005981 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005982 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5983 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5984 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005985 case Instruction::GetElementPtr:
5986 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005987 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005988 bool isAllZeros = true;
5989 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5990 if (!isa<Constant>(LHSI->getOperand(i)) ||
5991 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5992 isAllZeros = false;
5993 break;
5994 }
5995 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005997 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5998 }
5999 break;
6000
Chris Lattner6970b662005-04-23 15:31:55 +00006001 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006002 // Only fold icmp into the PHI if the phi and fcmp are in the same
6003 // block. If in the same block, we're encouraging jump threading. If
6004 // not, we are just pessimizing the code by making an i1 phi.
6005 if (LHSI->getParent() == I.getParent())
6006 if (Instruction *NV = FoldOpIntoPhi(I))
6007 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006008 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006009 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006010 // If either operand of the select is a constant, we can fold the
6011 // comparison into the select arms, which will cause one to be
6012 // constant folded and the select turned into a bitwise or.
6013 Value *Op1 = 0, *Op2 = 0;
6014 if (LHSI->hasOneUse()) {
6015 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6016 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006017 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6018 // Insert a new ICmp of the other select operand.
6019 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6020 LHSI->getOperand(2), RHSC,
6021 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006022 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6023 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006024 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6025 // Insert a new ICmp of the other select operand.
6026 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6027 LHSI->getOperand(1), RHSC,
6028 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006029 }
6030 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006031
Chris Lattner6970b662005-04-23 15:31:55 +00006032 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006033 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006034 break;
6035 }
Chris Lattner4802d902007-04-06 18:57:34 +00006036 case Instruction::Malloc:
6037 // If we have (malloc != null), and if the malloc has a single use, we
6038 // can assume it is successful and remove the malloc.
6039 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6040 AddToWorkList(LHSI);
6041 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006042 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006043 }
6044 break;
6045 }
Chris Lattner6970b662005-04-23 15:31:55 +00006046 }
6047
Reid Spencere4d87aa2006-12-23 06:05:41 +00006048 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006049 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006050 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006051 return NI;
6052 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006053 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6054 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006055 return NI;
6056
Reid Spencere4d87aa2006-12-23 06:05:41 +00006057 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006058 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6059 // now.
6060 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6061 if (isa<PointerType>(Op0->getType()) &&
6062 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006063 // We keep moving the cast from the left operand over to the right
6064 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006065 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006066
Chris Lattner57d86372007-01-06 01:45:59 +00006067 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6068 // so eliminate it as well.
6069 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6070 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006071
Chris Lattnerde90b762003-11-03 04:25:02 +00006072 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006073 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006074 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006075 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006076 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006077 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006078 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006079 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006080 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006081 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006082 }
Chris Lattner57d86372007-01-06 01:45:59 +00006083 }
6084
6085 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006086 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006087 // This comes up when you have code like
6088 // int X = A < B;
6089 // if (X) ...
6090 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006091 // with a constant or another cast from the same type.
6092 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006093 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006094 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006095 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006096
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006097 // See if it's the same type of instruction on the left and right.
6098 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6099 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006100 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006101 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006102 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006103 default: break;
6104 case Instruction::Add:
6105 case Instruction::Sub:
6106 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006107 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Nick Lewycky4333f492009-01-31 21:30:05 +00006108 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6109 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006110 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6112 if (CI->getValue().isSignBit()) {
6113 ICmpInst::Predicate Pred = I.isSignedPredicate()
6114 ? I.getUnsignedPredicate()
6115 : I.getSignedPredicate();
6116 return new ICmpInst(Pred, Op0I->getOperand(0),
6117 Op1I->getOperand(0));
6118 }
6119
6120 if (CI->getValue().isMaxSignedValue()) {
6121 ICmpInst::Predicate Pred = I.isSignedPredicate()
6122 ? I.getUnsignedPredicate()
6123 : I.getSignedPredicate();
6124 Pred = I.getSwappedPredicate(Pred);
6125 return new ICmpInst(Pred, Op0I->getOperand(0),
6126 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006127 }
6128 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006129 break;
6130 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006131 if (!I.isEquality())
6132 break;
6133
Nick Lewycky5d52c452008-08-21 05:56:10 +00006134 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6135 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6136 // Mask = -1 >> count-trailing-zeros(Cst).
6137 if (!CI->isZero() && !CI->isOne()) {
6138 const APInt &AP = CI->getValue();
6139 ConstantInt *Mask = ConstantInt::get(
6140 APInt::getLowBitsSet(AP.getBitWidth(),
6141 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006142 AP.countTrailingZeros()));
Nick Lewycky5d52c452008-08-21 05:56:10 +00006143 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6144 Mask);
6145 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6146 Mask);
6147 InsertNewInstBefore(And1, I);
6148 InsertNewInstBefore(And2, I);
6149 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006150 }
6151 }
6152 break;
6153 }
6154 }
6155 }
6156 }
6157
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006158 // ~x < ~y --> y < x
6159 { Value *A, *B;
6160 if (match(Op0, m_Not(m_Value(A))) &&
6161 match(Op1, m_Not(m_Value(B))))
6162 return new ICmpInst(I.getPredicate(), B, A);
6163 }
6164
Chris Lattner65b72ba2006-09-18 04:22:48 +00006165 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006166 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006167
6168 // -x == -y --> x == y
6169 if (match(Op0, m_Neg(m_Value(A))) &&
6170 match(Op1, m_Neg(m_Value(B))))
6171 return new ICmpInst(I.getPredicate(), A, B);
6172
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006173 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6174 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6175 Value *OtherVal = A == Op1 ? B : A;
6176 return new ICmpInst(I.getPredicate(), OtherVal,
6177 Constant::getNullValue(A->getType()));
6178 }
6179
6180 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6181 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006182 ConstantInt *C1, *C2;
6183 if (match(B, m_ConstantInt(C1)) &&
6184 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6185 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6186 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6187 return new ICmpInst(I.getPredicate(), A,
6188 InsertNewInstBefore(Xor, I));
6189 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006190
6191 // A^B == A^D -> B == D
6192 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6193 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6194 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6195 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6196 }
6197 }
6198
6199 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6200 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006201 // A == (A^B) -> B == 0
6202 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006203 return new ICmpInst(I.getPredicate(), OtherVal,
6204 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006205 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006206
6207 // (A-B) == A -> B == 0
6208 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6209 return new ICmpInst(I.getPredicate(), B,
6210 Constant::getNullValue(B->getType()));
6211
6212 // A == (A-B) -> B == 0
6213 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006214 return new ICmpInst(I.getPredicate(), B,
6215 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006216
Chris Lattner9c2328e2006-11-14 06:06:06 +00006217 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6218 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6219 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6220 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6221 Value *X = 0, *Y = 0, *Z = 0;
6222
6223 if (A == C) {
6224 X = B; Y = D; Z = A;
6225 } else if (A == D) {
6226 X = B; Y = C; Z = A;
6227 } else if (B == C) {
6228 X = A; Y = D; Z = B;
6229 } else if (B == D) {
6230 X = A; Y = C; Z = B;
6231 }
6232
6233 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006234 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6235 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006236 I.setOperand(0, Op1);
6237 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6238 return &I;
6239 }
6240 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006241 }
Chris Lattner7e708292002-06-25 16:13:24 +00006242 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006243}
6244
Chris Lattner562ef782007-06-20 23:46:26 +00006245
6246/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6247/// and CmpRHS are both known to be integer constants.
6248Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6249 ConstantInt *DivRHS) {
6250 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6251 const APInt &CmpRHSV = CmpRHS->getValue();
6252
6253 // FIXME: If the operand types don't match the type of the divide
6254 // then don't attempt this transform. The code below doesn't have the
6255 // logic to deal with a signed divide and an unsigned compare (and
6256 // vice versa). This is because (x /s C1) <s C2 produces different
6257 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6258 // (x /u C1) <u C2. Simply casting the operands and result won't
6259 // work. :( The if statement below tests that condition and bails
6260 // if it finds it.
6261 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6262 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6263 return 0;
6264 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006265 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006266 if (DivIsSigned && DivRHS->isAllOnesValue())
6267 return 0; // The overflow computation also screws up here
6268 if (DivRHS->isOne())
6269 return 0; // Not worth bothering, and eliminates some funny cases
6270 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006271
6272 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6273 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6274 // C2 (CI). By solving for X we can turn this into a range check
6275 // instead of computing a divide.
6276 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6277
6278 // Determine if the product overflows by seeing if the product is
6279 // not equal to the divide. Make sure we do the same kind of divide
6280 // as in the LHS instruction that we're folding.
6281 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6282 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6283
6284 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006285 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006286
Chris Lattner1dbfd482007-06-21 18:11:19 +00006287 // Figure out the interval that is being checked. For example, a comparison
6288 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6289 // Compute this interval based on the constants involved and the signedness of
6290 // the compare/divide. This computes a half-open interval, keeping track of
6291 // whether either value in the interval overflows. After analysis each
6292 // overflow variable is set to 0 if it's corresponding bound variable is valid
6293 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6294 int LoOverflow = 0, HiOverflow = 0;
6295 ConstantInt *LoBound = 0, *HiBound = 0;
6296
Chris Lattner562ef782007-06-20 23:46:26 +00006297 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006298 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006299 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006300 HiOverflow = LoOverflow = ProdOV;
6301 if (!HiOverflow)
6302 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006303 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006304 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006305 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006306 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6307 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006308 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006309 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6310 HiOverflow = LoOverflow = ProdOV;
6311 if (!HiOverflow)
6312 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006313 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006314 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006315 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006316 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6317 if (!LoOverflow) {
6318 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6319 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6320 true) ? -1 : 0;
6321 }
Chris Lattner562ef782007-06-20 23:46:26 +00006322 }
Dan Gohman76491272008-02-13 22:09:18 +00006323 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006324 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006325 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006326 LoBound = AddOne(DivRHS);
6327 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006328 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6329 HiOverflow = 1; // [INTMIN+1, overflow)
6330 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6331 }
Dan Gohman76491272008-02-13 22:09:18 +00006332 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006333 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnera6321b42008-10-11 22:55:00 +00006334 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006335 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006336 if (!LoOverflow)
Chris Lattnera6321b42008-10-11 22:55:00 +00006337 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006338 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006339 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6340 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006341 if (!HiOverflow)
6342 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006343 }
6344
Chris Lattner1dbfd482007-06-21 18:11:19 +00006345 // Dividing by a negative swaps the condition. LT <-> GT
6346 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006347 }
6348
6349 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006350 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006351 default: assert(0 && "Unhandled icmp opcode!");
6352 case ICmpInst::ICMP_EQ:
6353 if (LoOverflow && HiOverflow)
6354 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6355 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006356 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006357 ICmpInst::ICMP_UGE, X, LoBound);
6358 else if (LoOverflow)
6359 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6360 ICmpInst::ICMP_ULT, X, HiBound);
6361 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006362 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006363 case ICmpInst::ICMP_NE:
6364 if (LoOverflow && HiOverflow)
6365 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6366 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006367 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006368 ICmpInst::ICMP_ULT, X, LoBound);
6369 else if (LoOverflow)
6370 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6371 ICmpInst::ICMP_UGE, X, HiBound);
6372 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006373 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006374 case ICmpInst::ICMP_ULT:
6375 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006376 if (LoOverflow == +1) // Low bound is greater than input range.
6377 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6378 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006379 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006380 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006381 case ICmpInst::ICMP_UGT:
6382 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006383 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006384 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006385 else if (HiOverflow == -1) // High bound less than input range.
6386 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6387 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006388 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6389 else
6390 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6391 }
6392}
6393
6394
Chris Lattner01deb9d2007-04-03 17:43:25 +00006395/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6396///
6397Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6398 Instruction *LHSI,
6399 ConstantInt *RHS) {
6400 const APInt &RHSV = RHS->getValue();
6401
6402 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006403 case Instruction::Trunc:
6404 if (ICI.isEquality() && LHSI->hasOneUse()) {
6405 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6406 // of the high bits truncated out of x are known.
6407 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6408 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6409 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6410 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6411 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6412
6413 // If all the high bits are known, we can do this xform.
6414 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6415 // Pull in the high bits from known-ones set.
6416 APInt NewRHS(RHS->getValue());
6417 NewRHS.zext(SrcBits);
6418 NewRHS |= KnownOne;
6419 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6420 ConstantInt::get(NewRHS));
6421 }
6422 }
6423 break;
6424
Duncan Sands0091bf22007-04-04 06:42:45 +00006425 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006426 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6427 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6428 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006429 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6430 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006431 Value *CompareVal = LHSI->getOperand(0);
6432
6433 // If the sign bit of the XorCST is not set, there is no change to
6434 // the operation, just stop using the Xor.
6435 if (!XorCST->getValue().isNegative()) {
6436 ICI.setOperand(0, CompareVal);
6437 AddToWorkList(LHSI);
6438 return &ICI;
6439 }
6440
6441 // Was the old condition true if the operand is positive?
6442 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6443
6444 // If so, the new one isn't.
6445 isTrueIfPositive ^= true;
6446
6447 if (isTrueIfPositive)
6448 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6449 else
6450 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6451 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006452
6453 if (LHSI->hasOneUse()) {
6454 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6455 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6456 const APInt &SignBit = XorCST->getValue();
6457 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6458 ? ICI.getUnsignedPredicate()
6459 : ICI.getSignedPredicate();
6460 return new ICmpInst(Pred, LHSI->getOperand(0),
6461 ConstantInt::get(RHSV ^ SignBit));
6462 }
6463
6464 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006465 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006466 const APInt &NotSignBit = XorCST->getValue();
6467 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6468 ? ICI.getUnsignedPredicate()
6469 : ICI.getSignedPredicate();
6470 Pred = ICI.getSwappedPredicate(Pred);
6471 return new ICmpInst(Pred, LHSI->getOperand(0),
6472 ConstantInt::get(RHSV ^ NotSignBit));
6473 }
6474 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006475 }
6476 break;
6477 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6478 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6479 LHSI->getOperand(0)->hasOneUse()) {
6480 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6481
6482 // If the LHS is an AND of a truncating cast, we can widen the
6483 // and/compare to be the input width without changing the value
6484 // produced, eliminating a cast.
6485 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6486 // We can do this transformation if either the AND constant does not
6487 // have its sign bit set or if it is an equality comparison.
6488 // Extending a relational comparison when we're checking the sign
6489 // bit would not work.
6490 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006491 (ICI.isEquality() ||
6492 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006493 uint32_t BitWidth =
6494 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6495 APInt NewCST = AndCST->getValue();
6496 NewCST.zext(BitWidth);
6497 APInt NewCI = RHSV;
6498 NewCI.zext(BitWidth);
6499 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006500 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006501 ConstantInt::get(NewCST),LHSI->getName());
6502 InsertNewInstBefore(NewAnd, ICI);
6503 return new ICmpInst(ICI.getPredicate(), NewAnd,
6504 ConstantInt::get(NewCI));
6505 }
6506 }
6507
6508 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6509 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6510 // happens a LOT in code produced by the C front-end, for bitfield
6511 // access.
6512 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6513 if (Shift && !Shift->isShift())
6514 Shift = 0;
6515
6516 ConstantInt *ShAmt;
6517 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6518 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6519 const Type *AndTy = AndCST->getType(); // Type of the and.
6520
6521 // We can fold this as long as we can't shift unknown bits
6522 // into the mask. This can only happen with signed shift
6523 // rights, as they sign-extend.
6524 if (ShAmt) {
6525 bool CanFold = Shift->isLogicalShift();
6526 if (!CanFold) {
6527 // To test for the bad case of the signed shr, see if any
6528 // of the bits shifted in could be tested after the mask.
6529 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6530 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6531
6532 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6533 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6534 AndCST->getValue()) == 0)
6535 CanFold = true;
6536 }
6537
6538 if (CanFold) {
6539 Constant *NewCst;
6540 if (Shift->getOpcode() == Instruction::Shl)
6541 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6542 else
6543 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6544
6545 // Check to see if we are shifting out any of the bits being
6546 // compared.
6547 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6548 // If we shifted bits out, the fold is not going to work out.
6549 // As a special case, check to see if this means that the
6550 // result is always true or false now.
6551 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6552 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6553 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6554 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6555 } else {
6556 ICI.setOperand(1, NewCst);
6557 Constant *NewAndCST;
6558 if (Shift->getOpcode() == Instruction::Shl)
6559 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6560 else
6561 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6562 LHSI->setOperand(1, NewAndCST);
6563 LHSI->setOperand(0, Shift->getOperand(0));
6564 AddToWorkList(Shift); // Shift is dead.
6565 AddUsesToWorkList(ICI);
6566 return &ICI;
6567 }
6568 }
6569 }
6570
6571 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6572 // preferable because it allows the C<<Y expression to be hoisted out
6573 // of a loop if Y is invariant and X is not.
6574 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6575 ICI.isEquality() && !Shift->isArithmeticShift() &&
6576 isa<Instruction>(Shift->getOperand(0))) {
6577 // Compute C << Y.
6578 Value *NS;
6579 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006580 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006581 Shift->getOperand(1), "tmp");
6582 } else {
6583 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006584 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006585 Shift->getOperand(1), "tmp");
6586 }
6587 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6588
6589 // Compute X & (C << Y).
6590 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006591 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006592 InsertNewInstBefore(NewAnd, ICI);
6593
6594 ICI.setOperand(0, NewAnd);
6595 return &ICI;
6596 }
6597 }
6598 break;
6599
Chris Lattnera0141b92007-07-15 20:42:37 +00006600 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6601 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6602 if (!ShAmt) break;
6603
6604 uint32_t TypeBits = RHSV.getBitWidth();
6605
6606 // Check that the shift amount is in range. If not, don't perform
6607 // undefined shifts. When the shift is visited it will be
6608 // simplified.
6609 if (ShAmt->uge(TypeBits))
6610 break;
6611
6612 if (ICI.isEquality()) {
6613 // If we are comparing against bits always shifted out, the
6614 // comparison cannot succeed.
6615 Constant *Comp =
6616 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6617 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6618 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6619 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6620 return ReplaceInstUsesWith(ICI, Cst);
6621 }
6622
6623 if (LHSI->hasOneUse()) {
6624 // Otherwise strength reduce the shift into an and.
6625 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6626 Constant *Mask =
6627 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006628
Chris Lattnera0141b92007-07-15 20:42:37 +00006629 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006630 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006631 Mask, LHSI->getName()+".mask");
6632 Value *And = InsertNewInstBefore(AndI, ICI);
6633 return new ICmpInst(ICI.getPredicate(), And,
6634 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006635 }
6636 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006637
6638 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6639 bool TrueIfSigned = false;
6640 if (LHSI->hasOneUse() &&
6641 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6642 // (X << 31) <s 0 --> (X&1) != 0
6643 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6644 (TypeBits-ShAmt->getZExtValue()-1));
6645 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006646 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006647 Mask, LHSI->getName()+".mask");
6648 Value *And = InsertNewInstBefore(AndI, ICI);
6649
6650 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6651 And, Constant::getNullValue(And->getType()));
6652 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006653 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006654 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006655
6656 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006657 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006658 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006659 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006660 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006661
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006662 // Check that the shift amount is in range. If not, don't perform
6663 // undefined shifts. When the shift is visited it will be
6664 // simplified.
6665 uint32_t TypeBits = RHSV.getBitWidth();
6666 if (ShAmt->uge(TypeBits))
6667 break;
6668
6669 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006670
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006671 // If we are comparing against bits always shifted out, the
6672 // comparison cannot succeed.
6673 APInt Comp = RHSV << ShAmtVal;
6674 if (LHSI->getOpcode() == Instruction::LShr)
6675 Comp = Comp.lshr(ShAmtVal);
6676 else
6677 Comp = Comp.ashr(ShAmtVal);
6678
6679 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6680 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6681 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6682 return ReplaceInstUsesWith(ICI, Cst);
6683 }
6684
6685 // Otherwise, check to see if the bits shifted out are known to be zero.
6686 // If so, we can compare against the unshifted value:
6687 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006688 if (LHSI->hasOneUse() &&
6689 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006690 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6691 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6692 ConstantExpr::getShl(RHS, ShAmt));
6693 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006694
Evan Chengf30752c2008-04-23 00:38:06 +00006695 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006696 // Otherwise strength reduce the shift into an and.
6697 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6698 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006699
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006700 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006701 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006702 Mask, LHSI->getName()+".mask");
6703 Value *And = InsertNewInstBefore(AndI, ICI);
6704 return new ICmpInst(ICI.getPredicate(), And,
6705 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006706 }
6707 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006708 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006709
6710 case Instruction::SDiv:
6711 case Instruction::UDiv:
6712 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6713 // Fold this div into the comparison, producing a range check.
6714 // Determine, based on the divide type, what the range is being
6715 // checked. If there is an overflow on the low or high side, remember
6716 // it, otherwise compute the range [low, hi) bounding the new value.
6717 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006718 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6719 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6720 DivRHS))
6721 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006722 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006723
6724 case Instruction::Add:
6725 // Fold: icmp pred (add, X, C1), C2
6726
6727 if (!ICI.isEquality()) {
6728 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6729 if (!LHSC) break;
6730 const APInt &LHSV = LHSC->getValue();
6731
6732 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6733 .subtract(LHSV);
6734
6735 if (ICI.isSignedPredicate()) {
6736 if (CR.getLower().isSignBit()) {
6737 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6738 ConstantInt::get(CR.getUpper()));
6739 } else if (CR.getUpper().isSignBit()) {
6740 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6741 ConstantInt::get(CR.getLower()));
6742 }
6743 } else {
6744 if (CR.getLower().isMinValue()) {
6745 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6746 ConstantInt::get(CR.getUpper()));
6747 } else if (CR.getUpper().isMinValue()) {
6748 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6749 ConstantInt::get(CR.getLower()));
6750 }
6751 }
6752 }
6753 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006754 }
6755
6756 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6757 if (ICI.isEquality()) {
6758 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6759
6760 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6761 // the second operand is a constant, simplify a bit.
6762 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6763 switch (BO->getOpcode()) {
6764 case Instruction::SRem:
6765 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6766 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6767 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6768 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6769 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006770 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006771 BO->getName());
6772 InsertNewInstBefore(NewRem, ICI);
6773 return new ICmpInst(ICI.getPredicate(), NewRem,
6774 Constant::getNullValue(BO->getType()));
6775 }
6776 }
6777 break;
6778 case Instruction::Add:
6779 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6780 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6781 if (BO->hasOneUse())
6782 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6783 Subtract(RHS, BOp1C));
6784 } else if (RHSV == 0) {
6785 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6786 // efficiently invertible, or if the add has just this one use.
6787 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6788
6789 if (Value *NegVal = dyn_castNegVal(BOp1))
6790 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6791 else if (Value *NegVal = dyn_castNegVal(BOp0))
6792 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6793 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006794 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006795 InsertNewInstBefore(Neg, ICI);
6796 Neg->takeName(BO);
6797 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6798 }
6799 }
6800 break;
6801 case Instruction::Xor:
6802 // For the xor case, we can xor two constants together, eliminating
6803 // the explicit xor.
6804 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6805 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6806 ConstantExpr::getXor(RHS, BOC));
6807
6808 // FALLTHROUGH
6809 case Instruction::Sub:
6810 // Replace (([sub|xor] A, B) != 0) with (A != B)
6811 if (RHSV == 0)
6812 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6813 BO->getOperand(1));
6814 break;
6815
6816 case Instruction::Or:
6817 // If bits are being or'd in that are not present in the constant we
6818 // are comparing against, then the comparison could never succeed!
6819 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6820 Constant *NotCI = ConstantExpr::getNot(RHS);
6821 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6822 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6823 isICMP_NE));
6824 }
6825 break;
6826
6827 case Instruction::And:
6828 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6829 // If bits are being compared against that are and'd out, then the
6830 // comparison can never succeed!
6831 if ((RHSV & ~BOC->getValue()) != 0)
6832 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6833 isICMP_NE));
6834
6835 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6836 if (RHS == BOC && RHSV.isPowerOf2())
6837 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6838 ICmpInst::ICMP_NE, LHSI,
6839 Constant::getNullValue(RHS->getType()));
6840
6841 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00006842 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843 Value *X = BO->getOperand(0);
6844 Constant *Zero = Constant::getNullValue(X->getType());
6845 ICmpInst::Predicate pred = isICMP_NE ?
6846 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6847 return new ICmpInst(pred, X, Zero);
6848 }
6849
6850 // ((X & ~7) == 0) --> X < 8
6851 if (RHSV == 0 && isHighOnes(BOC)) {
6852 Value *X = BO->getOperand(0);
6853 Constant *NegX = ConstantExpr::getNeg(BOC);
6854 ICmpInst::Predicate pred = isICMP_NE ?
6855 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6856 return new ICmpInst(pred, X, NegX);
6857 }
6858 }
6859 default: break;
6860 }
6861 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6862 // Handle icmp {eq|ne} <intrinsic>, intcst.
6863 if (II->getIntrinsicID() == Intrinsic::bswap) {
6864 AddToWorkList(II);
6865 ICI.setOperand(0, II->getOperand(1));
6866 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6867 return &ICI;
6868 }
6869 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006870 }
6871 return 0;
6872}
6873
6874/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6875/// We only handle extending casts so far.
6876///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006877Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6878 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006879 Value *LHSCIOp = LHSCI->getOperand(0);
6880 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006881 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006882 Value *RHSCIOp;
6883
Chris Lattner8c756c12007-05-05 22:41:33 +00006884 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6885 // integer type is the same size as the pointer type.
6886 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6887 getTargetData().getPointerSizeInBits() ==
6888 cast<IntegerType>(DestTy)->getBitWidth()) {
6889 Value *RHSOp = 0;
6890 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006891 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006892 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6893 RHSOp = RHSC->getOperand(0);
6894 // If the pointer types don't match, insert a bitcast.
6895 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006896 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006897 }
6898
6899 if (RHSOp)
6900 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6901 }
6902
6903 // The code below only handles extension cast instructions, so far.
6904 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006905 if (LHSCI->getOpcode() != Instruction::ZExt &&
6906 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006907 return 0;
6908
Reid Spencere4d87aa2006-12-23 06:05:41 +00006909 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6910 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006911
Reid Spencere4d87aa2006-12-23 06:05:41 +00006912 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006913 // Not an extension from the same type?
6914 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006915 if (RHSCIOp->getType() != LHSCIOp->getType())
6916 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006917
Nick Lewycky4189a532008-01-28 03:48:02 +00006918 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006919 // and the other is a zext), then we can't handle this.
6920 if (CI->getOpcode() != LHSCI->getOpcode())
6921 return 0;
6922
Nick Lewycky4189a532008-01-28 03:48:02 +00006923 // Deal with equality cases early.
6924 if (ICI.isEquality())
6925 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6926
6927 // A signed comparison of sign extended values simplifies into a
6928 // signed comparison.
6929 if (isSignedCmp && isSignedExt)
6930 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6931
6932 // The other three cases all fold into an unsigned comparison.
6933 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006934 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006935
Reid Spencere4d87aa2006-12-23 06:05:41 +00006936 // If we aren't dealing with a constant on the RHS, exit early
6937 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6938 if (!CI)
6939 return 0;
6940
6941 // Compute the constant that would happen if we truncated to SrcTy then
6942 // reextended to DestTy.
6943 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6944 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6945
6946 // If the re-extended constant didn't change...
6947 if (Res2 == CI) {
6948 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6949 // For example, we might have:
6950 // %A = sext short %X to uint
6951 // %B = icmp ugt uint %A, 1330
6952 // It is incorrect to transform this into
6953 // %B = icmp ugt short %X, 1330
6954 // because %A may have negative value.
6955 //
Chris Lattnerf2991842008-07-11 04:09:09 +00006956 // However, we allow this when the compare is EQ/NE, because they are
6957 // signless.
6958 if (isSignedExt == isSignedCmp || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006959 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00006960 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006961 }
6962
6963 // The re-extended constant changed so the constant cannot be represented
6964 // in the shorter type. Consequently, we cannot emit a simple comparison.
6965
6966 // First, handle some easy cases. We know the result cannot be equal at this
6967 // point so handle the ICI.isEquality() cases
6968 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006969 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006970 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006971 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006972
6973 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6974 // should have been folded away previously and not enter in here.
6975 Value *Result;
6976 if (isSignedCmp) {
6977 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006978 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006979 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006980 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006981 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006982 } else {
6983 // We're performing an unsigned comparison.
6984 if (isSignedExt) {
6985 // We're performing an unsigned comp with a sign extended value.
6986 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006987 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006988 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6989 NegOne, ICI.getName()), ICI);
6990 } else {
6991 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006992 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006993 }
6994 }
6995
6996 // Finally, return the value computed.
6997 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00006998 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006999 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007000
7001 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7002 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7003 "ICmp should be folded!");
7004 if (Constant *CI = dyn_cast<Constant>(Result))
7005 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7006 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007007}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007008
Reid Spencer832254e2007-02-02 02:16:23 +00007009Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7010 return commonShiftTransforms(I);
7011}
7012
7013Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7014 return commonShiftTransforms(I);
7015}
7016
7017Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007018 if (Instruction *R = commonShiftTransforms(I))
7019 return R;
7020
7021 Value *Op0 = I.getOperand(0);
7022
7023 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7024 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7025 if (CSI->isAllOnesValue())
7026 return ReplaceInstUsesWith(I, CSI);
7027
7028 // See if we can turn a signed shr into an unsigned shr.
Nate Begeman5bc1ea02008-07-29 15:49:41 +00007029 if (!isa<VectorType>(I.getType()) &&
7030 MaskedValueIsZero(Op0,
Chris Lattner348f6652007-12-06 01:59:46 +00007031 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007032 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00007033
7034 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007035}
7036
7037Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7038 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007039 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007040
7041 // shl X, 0 == X and shr X, 0 == X
7042 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00007043 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00007044 Op0 == Constant::getNullValue(Op0->getType()))
7045 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007046
Reid Spencere4d87aa2006-12-23 06:05:41 +00007047 if (isa<UndefValue>(Op0)) {
7048 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007049 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007050 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007051 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7052 }
7053 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007054 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7055 return ReplaceInstUsesWith(I, Op0);
7056 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007057 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007058 }
7059
Chris Lattner2eefe512004-04-09 19:05:30 +00007060 // Try to fold constant and into select arguments.
7061 if (isa<Constant>(Op0))
7062 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007063 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007064 return R;
7065
Reid Spencerb83eb642006-10-20 07:07:24 +00007066 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007067 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7068 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007069 return 0;
7070}
7071
Reid Spencerb83eb642006-10-20 07:07:24 +00007072Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007073 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007074 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007075
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007076 // See if we can simplify any instructions used by the instruction whose sole
7077 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007078 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +00007079 if (SimplifyDemandedInstructionBits(I))
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007080 return &I;
7081
Chris Lattner4d5542c2006-01-06 07:12:35 +00007082 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7083 // of a signed value.
7084 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007085 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007086 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007087 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7088 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007089 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007090 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007091 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007092 }
7093
7094 // ((X*C1) << C2) == (X * (C1 << C2))
7095 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7096 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7097 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007098 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007099 ConstantExpr::getShl(BOOp, Op1));
7100
7101 // Try to fold constant and into select arguments.
7102 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7103 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7104 return R;
7105 if (isa<PHINode>(Op0))
7106 if (Instruction *NV = FoldOpIntoPhi(I))
7107 return NV;
7108
Chris Lattner8999dd32007-12-22 09:07:47 +00007109 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7110 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7111 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7112 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7113 // place. Don't try to do this transformation in this case. Also, we
7114 // require that the input operand is a shift-by-constant so that we have
7115 // confidence that the shifts will get folded together. We could do this
7116 // xform in more cases, but it is unlikely to be profitable.
7117 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7118 isa<ConstantInt>(TrOp->getOperand(1))) {
7119 // Okay, we'll do this xform. Make the shift of shift.
7120 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007121 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007122 I.getName());
7123 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7124
7125 // For logical shifts, the truncation has the effect of making the high
7126 // part of the register be zeros. Emulate this by inserting an AND to
7127 // clear the top bits as needed. This 'and' will usually be zapped by
7128 // other xforms later if dead.
7129 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7130 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7131 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7132
7133 // The mask we constructed says what the trunc would do if occurring
7134 // between the shifts. We want to know the effect *after* the second
7135 // shift. We know that it is a logical shift by a constant, so adjust the
7136 // mask as appropriate.
7137 if (I.getOpcode() == Instruction::Shl)
7138 MaskV <<= Op1->getZExtValue();
7139 else {
7140 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7141 MaskV = MaskV.lshr(Op1->getZExtValue());
7142 }
7143
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007144 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007145 TI->getName());
7146 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7147
7148 // Return the value truncated to the interesting size.
7149 return new TruncInst(And, I.getType());
7150 }
7151 }
7152
Chris Lattner4d5542c2006-01-06 07:12:35 +00007153 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007154 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7155 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7156 Value *V1, *V2;
7157 ConstantInt *CC;
7158 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007159 default: break;
7160 case Instruction::Add:
7161 case Instruction::And:
7162 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007163 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007164 // These operators commute.
7165 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007166 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007167 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007168 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007169 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007170 Op0BO->getName());
7171 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007172 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007173 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007174 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007175 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007176 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007177 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007178 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007179 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007180
Chris Lattner150f12a2005-09-18 06:30:59 +00007181 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007182 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007183 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007184 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007185 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7186 m_ConstantInt(CC))) &&
7187 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007188 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007189 Op0BO->getOperand(0), Op1,
7190 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007191 InsertNewInstBefore(YS, I); // (Y << C)
7192 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007193 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007194 V1->getName()+".mask");
7195 InsertNewInstBefore(XM, I); // X & (CC << C)
7196
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007197 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007198 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007199 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007200
Reid Spencera07cb7d2007-02-02 14:41:37 +00007201 // FALL THROUGH.
7202 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007203 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007204 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007205 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007206 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007207 Op0BO->getOperand(1), Op1,
7208 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007209 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007210 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007211 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007212 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007213 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007214 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007215 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007216 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007217 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007218
Chris Lattner13d4ab42006-05-31 21:14:00 +00007219 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007220 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7221 match(Op0BO->getOperand(0),
7222 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007223 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007224 cast<BinaryOperator>(Op0BO->getOperand(0))
7225 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007226 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007227 Op0BO->getOperand(1), Op1,
7228 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007229 InsertNewInstBefore(YS, I); // (Y << C)
7230 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007231 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007232 V1->getName()+".mask");
7233 InsertNewInstBefore(XM, I); // X & (CC << C)
7234
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007235 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007236 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007237
Chris Lattner11021cb2005-09-18 05:12:10 +00007238 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007239 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007240 }
7241
7242
7243 // If the operand is an bitwise operator with a constant RHS, and the
7244 // shift is the only use, we can pull it out of the shift.
7245 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7246 bool isValid = true; // Valid only for And, Or, Xor
7247 bool highBitSet = false; // Transform if high bit of constant set?
7248
7249 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007250 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007251 case Instruction::Add:
7252 isValid = isLeftShift;
7253 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007254 case Instruction::Or:
7255 case Instruction::Xor:
7256 highBitSet = false;
7257 break;
7258 case Instruction::And:
7259 highBitSet = true;
7260 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007261 }
7262
7263 // If this is a signed shift right, and the high bit is modified
7264 // by the logical operation, do not perform the transformation.
7265 // The highBitSet boolean indicates the value of the high bit of
7266 // the constant which would cause it to be modified for this
7267 // operation.
7268 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007269 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007270 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007271
7272 if (isValid) {
7273 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7274
7275 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007276 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007277 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007278 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007279
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007280 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007281 NewRHS);
7282 }
7283 }
7284 }
7285 }
7286
Chris Lattnerad0124c2006-01-06 07:52:12 +00007287 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007288 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7289 if (ShiftOp && !ShiftOp->isShift())
7290 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007291
Reid Spencerb83eb642006-10-20 07:07:24 +00007292 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007293 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007294 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7295 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007296 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7297 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7298 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007299
Zhou Sheng4351c642007-04-02 08:20:41 +00007300 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007301 if (AmtSum > TypeBits)
7302 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007303
7304 const IntegerType *Ty = cast<IntegerType>(I.getType());
7305
7306 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007307 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007308 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007309 ConstantInt::get(Ty, AmtSum));
7310 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7311 I.getOpcode() == Instruction::AShr) {
7312 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007313 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007314 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7315 I.getOpcode() == Instruction::LShr) {
7316 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7317 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007318 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007319 InsertNewInstBefore(Shift, I);
7320
Zhou Shenge9e03f62007-03-28 15:02:20 +00007321 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007322 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007323 }
7324
Chris Lattnerb87056f2007-02-05 00:57:54 +00007325 // Okay, if we get here, one shift must be left, and the other shift must be
7326 // right. See if the amounts are equal.
7327 if (ShiftAmt1 == ShiftAmt2) {
7328 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7329 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007330 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007331 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007332 }
7333 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7334 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007335 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007336 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007337 }
7338 // We can simplify ((X << C) >>s C) into a trunc + sext.
7339 // NOTE: we could do this for any C, but that would make 'unusual' integer
7340 // types. For now, just stick to ones well-supported by the code
7341 // generators.
7342 const Type *SExtType = 0;
7343 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007344 case 1 :
7345 case 8 :
7346 case 16 :
7347 case 32 :
7348 case 64 :
7349 case 128:
7350 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7351 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007352 default: break;
7353 }
7354 if (SExtType) {
7355 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7356 InsertNewInstBefore(NewTrunc, I);
7357 return new SExtInst(NewTrunc, Ty);
7358 }
7359 // Otherwise, we can't handle it yet.
7360 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007361 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007362
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007363 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007364 if (I.getOpcode() == Instruction::Shl) {
7365 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7366 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007367 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007368 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007369 InsertNewInstBefore(Shift, I);
7370
Reid Spencer55702aa2007-03-25 21:11:44 +00007371 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007372 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007373 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007374
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007375 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007376 if (I.getOpcode() == Instruction::LShr) {
7377 assert(ShiftOp->getOpcode() == Instruction::Shl);
7378 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007379 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007380 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007381
Reid Spencerd5e30f02007-03-26 17:18:58 +00007382 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007383 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007384 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007385
7386 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7387 } else {
7388 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007389 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007390
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007391 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007392 if (I.getOpcode() == Instruction::Shl) {
7393 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7394 ShiftOp->getOpcode() == Instruction::AShr);
7395 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007396 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007397 ConstantInt::get(Ty, ShiftDiff));
7398 InsertNewInstBefore(Shift, I);
7399
Reid Spencer55702aa2007-03-25 21:11:44 +00007400 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007401 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007402 }
7403
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007404 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007405 if (I.getOpcode() == Instruction::LShr) {
7406 assert(ShiftOp->getOpcode() == Instruction::Shl);
7407 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007408 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007409 InsertNewInstBefore(Shift, I);
7410
Reid Spencer68d27cf2007-03-26 23:45:51 +00007411 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007412 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007413 }
7414
7415 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007416 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007417 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007418 return 0;
7419}
7420
Chris Lattnera1be5662002-05-02 17:06:02 +00007421
Chris Lattnercfd65102005-10-29 04:36:15 +00007422/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7423/// expression. If so, decompose it, returning some value X, such that Val is
7424/// X*Scale+Offset.
7425///
7426static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007427 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007428 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007429 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007430 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007431 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007432 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007433 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7434 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7435 if (I->getOpcode() == Instruction::Shl) {
7436 // This is a value scaled by '1 << the shift amt'.
7437 Scale = 1U << RHS->getZExtValue();
7438 Offset = 0;
7439 return I->getOperand(0);
7440 } else if (I->getOpcode() == Instruction::Mul) {
7441 // This value is scaled by 'RHS'.
7442 Scale = RHS->getZExtValue();
7443 Offset = 0;
7444 return I->getOperand(0);
7445 } else if (I->getOpcode() == Instruction::Add) {
7446 // We have X+C. Check to see if we really have (X*C2)+C1,
7447 // where C1 is divisible by C2.
7448 unsigned SubScale;
7449 Value *SubVal =
7450 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7451 Offset += RHS->getZExtValue();
7452 Scale = SubScale;
7453 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007454 }
7455 }
7456 }
7457
7458 // Otherwise, we can't look past this.
7459 Scale = 1;
7460 Offset = 0;
7461 return Val;
7462}
7463
7464
Chris Lattnerb3f83972005-10-24 06:03:58 +00007465/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7466/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007467Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007468 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007469 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007470
Chris Lattnerb53c2382005-10-24 06:22:12 +00007471 // Remove any uses of AI that are dead.
7472 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007473
Chris Lattnerb53c2382005-10-24 06:22:12 +00007474 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7475 Instruction *User = cast<Instruction>(*UI++);
7476 if (isInstructionTriviallyDead(User)) {
7477 while (UI != E && *UI == User)
7478 ++UI; // If this instruction uses AI more than once, don't break UI.
7479
Chris Lattnerb53c2382005-10-24 06:22:12 +00007480 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007481 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007482 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007483 }
7484 }
7485
Chris Lattnerb3f83972005-10-24 06:03:58 +00007486 // Get the type really allocated and the type casted to.
7487 const Type *AllocElTy = AI.getAllocatedType();
7488 const Type *CastElTy = PTy->getElementType();
7489 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007490
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007491 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7492 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007493 if (CastElTyAlign < AllocElTyAlign) return 0;
7494
Chris Lattner39387a52005-10-24 06:35:18 +00007495 // If the allocation has multiple uses, only promote it if we are strictly
7496 // increasing the alignment of the resultant allocation. If we keep it the
7497 // same, we open the door to infinite loops of various kinds.
7498 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7499
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007500 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7501 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007502 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007503
Chris Lattner455fcc82005-10-29 03:19:53 +00007504 // See if we can satisfy the modulus by pulling a scale out of the array
7505 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007506 unsigned ArraySizeScale;
7507 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007508 Value *NumElements = // See if the array size is a decomposable linear expr.
7509 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7510
Chris Lattner455fcc82005-10-29 03:19:53 +00007511 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7512 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007513 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7514 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007515
Chris Lattner455fcc82005-10-29 03:19:53 +00007516 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7517 Value *Amt = 0;
7518 if (Scale == 1) {
7519 Amt = NumElements;
7520 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007521 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007522 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7523 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007524 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007525 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007526 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007527 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007528 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007529 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007530 }
7531
Jeff Cohen86796be2007-04-04 16:58:57 +00007532 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7533 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007534 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007535 Amt = InsertNewInstBefore(Tmp, AI);
7536 }
7537
Chris Lattnerb3f83972005-10-24 06:03:58 +00007538 AllocationInst *New;
7539 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007540 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007541 else
Chris Lattner6934a042007-02-11 01:23:03 +00007542 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007543 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007544 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007545
7546 // If the allocation has multiple uses, insert a cast and change all things
7547 // that used it to use the new cast. This will also hack on CI, but it will
7548 // die soon.
7549 if (!AI.hasOneUse()) {
7550 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007551 // New is the allocation instruction, pointer typed. AI is the original
7552 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7553 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007554 InsertNewInstBefore(NewCast, AI);
7555 AI.replaceAllUsesWith(NewCast);
7556 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007557 return ReplaceInstUsesWith(CI, New);
7558}
7559
Chris Lattner70074e02006-05-13 02:06:03 +00007560/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007561/// and return it as type Ty without inserting any new casts and without
7562/// changing the computed value. This is used by code that tries to decide
7563/// whether promoting or shrinking integer operations to wider or smaller types
7564/// will allow us to eliminate a truncate or extend.
7565///
7566/// This is a truncation operation if Ty is smaller than V->getType(), or an
7567/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007568///
7569/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7570/// should return true if trunc(V) can be computed by computing V in the smaller
7571/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7572/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7573/// efficiently truncated.
7574///
7575/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7576/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7577/// the final result.
Evan Cheng4e56ab22009-01-16 02:11:43 +00007578bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7579 unsigned CastOpc,
7580 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007581 // We can always evaluate constants in another type.
7582 if (isa<ConstantInt>(V))
7583 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007584
7585 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007586 if (!I) return false;
7587
7588 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007589
Chris Lattner951626b2007-08-02 06:11:14 +00007590 // If this is an extension or truncate, we can often eliminate it.
7591 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7592 // If this is a cast from the destination type, we can trivially eliminate
7593 // it, and this will remove a cast overall.
7594 if (I->getOperand(0)->getType() == Ty) {
7595 // If the first operand is itself a cast, and is eliminable, do not count
7596 // this as an eliminable cast. We would prefer to eliminate those two
7597 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007598 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007599 ++NumCastsRemoved;
7600 return true;
7601 }
7602 }
7603
7604 // We can't extend or shrink something that has multiple uses: doing so would
7605 // require duplicating the instruction in general, which isn't profitable.
7606 if (!I->hasOneUse()) return false;
7607
Evan Chengf35fd542009-01-15 17:01:23 +00007608 unsigned Opc = I->getOpcode();
7609 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007610 case Instruction::Add:
7611 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007612 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007613 case Instruction::And:
7614 case Instruction::Or:
7615 case Instruction::Xor:
7616 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007617 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007618 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007619 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007620 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007621
Chris Lattner46b96052006-11-29 07:18:39 +00007622 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007623 // If we are truncating the result of this SHL, and if it's a shift of a
7624 // constant amount, we can always perform a SHL in a smaller type.
7625 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007626 uint32_t BitWidth = Ty->getBitWidth();
7627 if (BitWidth < OrigTy->getBitWidth() &&
7628 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007629 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007630 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007631 }
7632 break;
7633 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007634 // If this is a truncate of a logical shr, we can truncate it to a smaller
7635 // lshr iff we know that the bits we would otherwise be shifting in are
7636 // already zeros.
7637 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007638 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7639 uint32_t BitWidth = Ty->getBitWidth();
7640 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007641 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007642 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7643 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007644 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007645 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007646 }
7647 }
Chris Lattner46b96052006-11-29 07:18:39 +00007648 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007649 case Instruction::ZExt:
7650 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007651 case Instruction::Trunc:
7652 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007653 // can safely replace it. Note that replacing it does not reduce the number
7654 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007655 if (Opc == CastOpc)
7656 return true;
7657
7658 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007659 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007660 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007661 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007662 case Instruction::Select: {
7663 SelectInst *SI = cast<SelectInst>(I);
7664 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007665 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007666 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007667 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007668 }
Chris Lattner8114b712008-06-18 04:00:49 +00007669 case Instruction::PHI: {
7670 // We can change a phi if we can change all operands.
7671 PHINode *PN = cast<PHINode>(I);
7672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7673 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007674 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007675 return false;
7676 return true;
7677 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007678 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007679 // TODO: Can handle more cases here.
7680 break;
7681 }
7682
7683 return false;
7684}
7685
7686/// EvaluateInDifferentType - Given an expression that
7687/// CanEvaluateInDifferentType returns true for, actually insert the code to
7688/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007689Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007690 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007691 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007692 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007693
7694 // Otherwise, it must be an instruction.
7695 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007696 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007697 unsigned Opc = I->getOpcode();
7698 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007699 case Instruction::Add:
7700 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007701 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007702 case Instruction::And:
7703 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007704 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007705 case Instruction::AShr:
7706 case Instruction::LShr:
7707 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007708 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007709 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007710 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007711 break;
7712 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007713 case Instruction::Trunc:
7714 case Instruction::ZExt:
7715 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007716 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007717 // just return the source. There's no need to insert it because it is not
7718 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007719 if (I->getOperand(0)->getType() == Ty)
7720 return I->getOperand(0);
7721
Chris Lattner8114b712008-06-18 04:00:49 +00007722 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007723 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007724 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007725 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007726 case Instruction::Select: {
7727 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7728 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7729 Res = SelectInst::Create(I->getOperand(0), True, False);
7730 break;
7731 }
Chris Lattner8114b712008-06-18 04:00:49 +00007732 case Instruction::PHI: {
7733 PHINode *OPN = cast<PHINode>(I);
7734 PHINode *NPN = PHINode::Create(Ty);
7735 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7736 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7737 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7738 }
7739 Res = NPN;
7740 break;
7741 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007742 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007743 // TODO: Can handle more cases here.
7744 assert(0 && "Unreachable!");
7745 break;
7746 }
7747
Chris Lattner8114b712008-06-18 04:00:49 +00007748 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007749 return InsertNewInstBefore(Res, *I);
7750}
7751
Reid Spencer3da59db2006-11-27 01:05:10 +00007752/// @brief Implement the transforms common to all CastInst visitors.
7753Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007754 Value *Src = CI.getOperand(0);
7755
Dan Gohman23d9d272007-05-11 21:10:54 +00007756 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007757 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007758 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007759 if (Instruction::CastOps opc =
7760 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7761 // The first cast (CSrc) is eliminable so we need to fix up or replace
7762 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007763 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007764 }
7765 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007766
Reid Spencer3da59db2006-11-27 01:05:10 +00007767 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007768 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7769 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7770 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007771
7772 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007773 if (isa<PHINode>(Src))
7774 if (Instruction *NV = FoldOpIntoPhi(CI))
7775 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007776
Reid Spencer3da59db2006-11-27 01:05:10 +00007777 return 0;
7778}
7779
Chris Lattner46cd5a12009-01-09 05:44:56 +00007780/// FindElementAtOffset - Given a type and a constant offset, determine whether
7781/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007782/// the specified offset. If so, fill them into NewIndices and return the
7783/// resultant element type, otherwise return null.
7784static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7785 SmallVectorImpl<Value*> &NewIndices,
7786 const TargetData *TD) {
7787 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007788
7789 // Start with the index over the outer type. Note that the type size
7790 // might be zero (even if the offset isn't zero) if the indexed type
7791 // is something like [0 x {int, int}]
7792 const Type *IntPtrTy = TD->getIntPtrType();
7793 int64_t FirstIdx = 0;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007794 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00007795 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00007796 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007797
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007798 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00007799 if (Offset < 0) {
7800 --FirstIdx;
7801 Offset += TySize;
7802 assert(Offset >= 0);
7803 }
7804 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7805 }
7806
7807 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7808
7809 // Index into the types. If we fail, set OrigBase to null.
7810 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007811 // Indexing into tail padding between struct/array elements.
7812 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00007813 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007814
Chris Lattner46cd5a12009-01-09 05:44:56 +00007815 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7816 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007817 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7818 "Offset must stay within the indexed type");
7819
Chris Lattner46cd5a12009-01-09 05:44:56 +00007820 unsigned Elt = SL->getElementContainingOffset(Offset);
7821 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7822
7823 Offset -= SL->getElementOffset(Elt);
7824 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00007825 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00007826 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007827 assert(EltSize && "Cannot index into a zero-sized array");
7828 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7829 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00007830 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007831 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00007832 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00007833 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007834 }
7835 }
7836
Chris Lattner3914f722009-01-24 01:00:13 +00007837 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007838}
7839
Chris Lattnerd3e28342007-04-27 17:44:50 +00007840/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7841Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7842 Value *Src = CI.getOperand(0);
7843
Chris Lattnerd3e28342007-04-27 17:44:50 +00007844 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007845 // If casting the result of a getelementptr instruction with no offset, turn
7846 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007847 if (GEP->hasAllZeroIndices()) {
7848 // Changing the cast operand is usually not a good idea but it is safe
7849 // here because the pointer operand is being replaced with another
7850 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007851 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007852 CI.setOperand(0, GEP->getOperand(0));
7853 return &CI;
7854 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007855
7856 // If the GEP has a single use, and the base pointer is a bitcast, and the
7857 // GEP computes a constant offset, see if we can convert these three
7858 // instructions into fewer. This typically happens with unions and other
7859 // non-type-safe code.
7860 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7861 if (GEP->hasAllConstantIndices()) {
7862 // We are guaranteed to get a constant from EmitGEPOffset.
7863 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7864 int64_t Offset = OffsetV->getSExtValue();
7865
7866 // Get the base pointer input of the bitcast, and the type it points to.
7867 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7868 const Type *GEPIdxTy =
7869 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00007870 SmallVector<Value*, 8> NewIndices;
7871 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7872 // If we were able to index down into an element, create the GEP
7873 // and bitcast the result. This eliminates one bitcast, potentially
7874 // two.
7875 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7876 NewIndices.begin(),
7877 NewIndices.end(), "");
7878 InsertNewInstBefore(NGEP, CI);
7879 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00007880
Chris Lattner46cd5a12009-01-09 05:44:56 +00007881 if (isa<BitCastInst>(CI))
7882 return new BitCastInst(NGEP, CI.getType());
7883 assert(isa<PtrToIntInst>(CI));
7884 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00007885 }
7886 }
7887 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007888 }
7889
7890 return commonCastTransforms(CI);
7891}
7892
7893
Chris Lattnerc739cd62007-03-03 05:27:34 +00007894/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7895/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007896/// cases.
7897/// @brief Implement the transforms common to CastInst with integer operands
7898Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7899 if (Instruction *Result = commonCastTransforms(CI))
7900 return Result;
7901
7902 Value *Src = CI.getOperand(0);
7903 const Type *SrcTy = Src->getType();
7904 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007905 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7906 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007907
Reid Spencer3da59db2006-11-27 01:05:10 +00007908 // See if we can simplify any instructions used by the LHS whose sole
7909 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00007910 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00007911 return &CI;
7912
7913 // If the source isn't an instruction or has more than one use then we
7914 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007915 Instruction *SrcI = dyn_cast<Instruction>(Src);
7916 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007917 return 0;
7918
Chris Lattnerc739cd62007-03-03 05:27:34 +00007919 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007920 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007921 if (!isa<BitCastInst>(CI) &&
7922 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng4e56ab22009-01-16 02:11:43 +00007923 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007924 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007925 // eliminates the cast, so it is always a win. If this is a zero-extension,
7926 // we need to do an AND to maintain the clear top-part of the computation,
7927 // so we require that the input have eliminated at least one cast. If this
7928 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007929 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00007930 bool DoXForm = false;
7931 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007932 switch (CI.getOpcode()) {
7933 default:
7934 // All the others use floating point so we shouldn't actually
7935 // get here because of the check above.
7936 assert(0 && "Unknown cast type");
7937 case Instruction::Trunc:
7938 DoXForm = true;
7939 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007940 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007941 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007942 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007943 // If it's unnecessary to issue an AND to clear the high bits, it's
7944 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00007945 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007946 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7947 if (MaskedValueIsZero(TryRes, Mask))
7948 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007949
7950 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007951 if (TryI->use_empty())
7952 EraseInstFromFunction(*TryI);
7953 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007954 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00007955 }
Evan Chengf35fd542009-01-15 17:01:23 +00007956 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007957 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00007958 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00007959 // If we do not have to emit the truncate + sext pair, then it's always
7960 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00007961 //
7962 // It's not safe to eliminate the trunc + sext pair if one of the
7963 // eliminated cast is a truncate. e.g.
7964 // t2 = trunc i32 t1 to i16
7965 // t3 = sext i16 t2 to i32
7966 // !=
7967 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00007968 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007969 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7970 if (NumSignBits > (DestBitSize - SrcBitSize))
7971 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00007972
7973 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00007974 if (TryI->use_empty())
7975 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00007976 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00007977 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007978 }
Evan Chengf35fd542009-01-15 17:01:23 +00007979 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007980
7981 if (DoXForm) {
Chris Lattner39c27ed2009-01-31 19:05:27 +00007982 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
7983 << " cast: " << CI;
Reid Spencerc55b2432006-12-13 18:21:21 +00007984 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7985 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007986 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00007987 // Just replace this cast with the result.
7988 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00007989
Reid Spencer3da59db2006-11-27 01:05:10 +00007990 assert(Res->getType() == DestTy);
7991 switch (CI.getOpcode()) {
7992 default: assert(0 && "Unknown cast type!");
7993 case Instruction::Trunc:
7994 case Instruction::BitCast:
7995 // Just replace this cast with the result.
7996 return ReplaceInstUsesWith(CI, Res);
7997 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00007998 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00007999
8000 // If the high bits are already zero, just replace this cast with the
8001 // result.
8002 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8003 if (MaskedValueIsZero(Res, Mask))
8004 return ReplaceInstUsesWith(CI, Res);
8005
8006 // We need to emit an AND to clear the high bits.
Chris Lattnercd1d6d52007-04-02 05:48:58 +00008007 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8008 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008009 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008010 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008011 case Instruction::SExt: {
8012 // If the high bits are already filled with sign bit, just replace this
8013 // cast with the result.
8014 unsigned NumSignBits = ComputeNumSignBits(Res);
8015 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008016 return ReplaceInstUsesWith(CI, Res);
8017
Reid Spencer3da59db2006-11-27 01:05:10 +00008018 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008019 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008020 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8021 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008022 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008023 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008024 }
8025 }
8026
8027 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8028 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8029
8030 switch (SrcI->getOpcode()) {
8031 case Instruction::Add:
8032 case Instruction::Mul:
8033 case Instruction::And:
8034 case Instruction::Or:
8035 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008036 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00008037 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8038 // Don't insert two casts if they cannot be eliminated. We allow
8039 // two casts to be inserted if the sizes are the same. This could
8040 // only be converting signedness, which is a noop.
8041 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008042 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8043 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00008044 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008045 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8046 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008047 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008048 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008049 }
8050 }
8051
8052 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8053 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8054 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008055 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008056 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008057 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008058 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008059 }
8060 break;
8061 case Instruction::SDiv:
8062 case Instruction::UDiv:
8063 case Instruction::SRem:
8064 case Instruction::URem:
8065 // If we are just changing the sign, rewrite.
8066 if (DestBitSize == SrcBitSize) {
8067 // Don't insert two casts if they cannot be eliminated. We allow
8068 // two casts to be inserted if the sizes are the same. This could
8069 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008070 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8071 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008072 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8073 Op0, DestTy, *SrcI);
8074 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8075 Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008076 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00008077 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8078 }
8079 }
8080 break;
8081
8082 case Instruction::Shl:
8083 // Allow changing the sign of the source operand. Do not allow
8084 // changing the size of the shift, UNLESS the shift amount is a
8085 // constant. We must not change variable sized shifts to a smaller
8086 // size, because it is undefined to shift more bits out than exist
8087 // in the value.
8088 if (DestBitSize == SrcBitSize ||
8089 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00008090 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8091 Instruction::BitCast : Instruction::Trunc);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008092 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8093 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008094 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008095 }
8096 break;
8097 case Instruction::AShr:
8098 // If this is a signed shr, and if all bits shifted in are about to be
8099 // truncated off, turn it into an unsigned shr to allow greater
8100 // simplifications.
8101 if (DestBitSize < SrcBitSize &&
8102 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008103 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00008104 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8105 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008106 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 }
8108 }
8109 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008110 }
8111 return 0;
8112}
8113
Chris Lattner8a9f5712007-04-11 06:57:46 +00008114Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008115 if (Instruction *Result = commonIntCastTransforms(CI))
8116 return Result;
8117
8118 Value *Src = CI.getOperand(0);
8119 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00008120 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8121 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008122
8123 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8124 switch (SrcI->getOpcode()) {
8125 default: break;
8126 case Instruction::LShr:
8127 // We can shrink lshr to something smaller if we know the bits shifted in
8128 // are already zeros.
8129 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00008130 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008131
8132 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00008133 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00008134 Value* SrcIOp0 = SrcI->getOperand(0);
8135 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008136 if (ShAmt >= DestBitWidth) // All zeros.
8137 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8138
8139 // Okay, we can shrink this. Truncate the input, then return a new
8140 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00008141 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8142 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8143 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008144 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008145 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008146 } else { // This is a variable shr.
8147
8148 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8149 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8150 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00008151 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008152 Value *One = ConstantInt::get(SrcI->getType(), 1);
8153
Reid Spencer832254e2007-02-02 02:16:23 +00008154 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008155 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00008156 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008157 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008158 SrcI->getOperand(0),
8159 "tmp"), CI);
8160 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008161 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008162 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008163 }
8164 break;
8165 }
8166 }
8167
8168 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008169}
8170
Evan Chengb98a10e2008-03-24 00:21:34 +00008171/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8172/// in order to eliminate the icmp.
8173Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8174 bool DoXform) {
8175 // If we are just checking for a icmp eq of a single bit and zext'ing it
8176 // to an integer, then shift the bit to the appropriate place and then
8177 // cast to integer to avoid the comparison.
8178 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8179 const APInt &Op1CV = Op1C->getValue();
8180
8181 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8182 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8183 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8184 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8185 if (!DoXform) return ICI;
8186
8187 Value *In = ICI->getOperand(0);
8188 Value *Sh = ConstantInt::get(In->getType(),
8189 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008190 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008191 In->getName()+".lobit"),
8192 CI);
8193 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008194 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008195 false/*ZExt*/, "tmp", &CI);
8196
8197 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8198 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008199 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008200 In->getName()+".not"),
8201 CI);
8202 }
8203
8204 return ReplaceInstUsesWith(CI, In);
8205 }
8206
8207
8208
8209 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8210 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8211 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8212 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8213 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8214 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8215 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8216 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8217 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8218 // This only works for EQ and NE
8219 ICI->isEquality()) {
8220 // If Op1C some other power of two, convert:
8221 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8222 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8223 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8224 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8225
8226 APInt KnownZeroMask(~KnownZero);
8227 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8228 if (!DoXform) return ICI;
8229
8230 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8231 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8232 // (X&4) == 2 --> false
8233 // (X&4) != 2 --> true
8234 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8235 Res = ConstantExpr::getZExt(Res, CI.getType());
8236 return ReplaceInstUsesWith(CI, Res);
8237 }
8238
8239 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8240 Value *In = ICI->getOperand(0);
8241 if (ShiftAmt) {
8242 // Perform a logical shr by shiftamt.
8243 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008244 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008245 ConstantInt::get(In->getType(), ShiftAmt),
8246 In->getName()+".lobit"), CI);
8247 }
8248
8249 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8250 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008251 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008252 InsertNewInstBefore(cast<Instruction>(In), CI);
8253 }
8254
8255 if (CI.getType() == In->getType())
8256 return ReplaceInstUsesWith(CI, In);
8257 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008258 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008259 }
8260 }
8261 }
8262
8263 return 0;
8264}
8265
Chris Lattner8a9f5712007-04-11 06:57:46 +00008266Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008267 // If one of the common conversion will work ..
8268 if (Instruction *Result = commonIntCastTransforms(CI))
8269 return Result;
8270
8271 Value *Src = CI.getOperand(0);
8272
8273 // If this is a cast of a cast
8274 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008275 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8276 // types and if the sizes are just right we can convert this into a logical
8277 // 'and' which will be much cheaper than the pair of casts.
8278 if (isa<TruncInst>(CSrc)) {
8279 // Get the sizes of the types involved
8280 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008281 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8282 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8283 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008284 // If we're actually extending zero bits and the trunc is a no-op
8285 if (MidSize < DstSize && SrcSize == DstSize) {
8286 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008287 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008288 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008289 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008290 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008291 // Unfortunately, if the type changed, we need to cast it back.
8292 if (And->getType() != CI.getType()) {
8293 And->setName(CSrc->getName()+".mask");
8294 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008295 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008296 }
8297 return And;
8298 }
8299 }
8300 }
8301
Evan Chengb98a10e2008-03-24 00:21:34 +00008302 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8303 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008304
Evan Chengb98a10e2008-03-24 00:21:34 +00008305 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8306 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8307 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8308 // of the (zext icmp) will be transformed.
8309 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8310 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8311 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8312 (transformZExtICmp(LHS, CI, false) ||
8313 transformZExtICmp(RHS, CI, false))) {
8314 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8315 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008316 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008317 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008318 }
8319
Reid Spencer3da59db2006-11-27 01:05:10 +00008320 return 0;
8321}
8322
Chris Lattner8a9f5712007-04-11 06:57:46 +00008323Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008324 if (Instruction *I = commonIntCastTransforms(CI))
8325 return I;
8326
Chris Lattner8a9f5712007-04-11 06:57:46 +00008327 Value *Src = CI.getOperand(0);
8328
Dan Gohman1975d032008-10-30 20:40:10 +00008329 // Canonicalize sign-extend from i1 to a select.
8330 if (Src->getType() == Type::Int1Ty)
8331 return SelectInst::Create(Src,
8332 ConstantInt::getAllOnesValue(CI.getType()),
8333 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008334
8335 // See if the value being truncated is already sign extended. If so, just
8336 // eliminate the trunc/sext pair.
8337 if (getOpcode(Src) == Instruction::Trunc) {
8338 Value *Op = cast<User>(Src)->getOperand(0);
8339 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8340 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8341 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8342 unsigned NumSignBits = ComputeNumSignBits(Op);
8343
8344 if (OpBits == DestBits) {
8345 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8346 // bits, it is already ready.
8347 if (NumSignBits > DestBits-MidBits)
8348 return ReplaceInstUsesWith(CI, Op);
8349 } else if (OpBits < DestBits) {
8350 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8351 // bits, just sext from i32.
8352 if (NumSignBits > OpBits-MidBits)
8353 return new SExtInst(Op, CI.getType(), "tmp");
8354 } else {
8355 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8356 // bits, just truncate to i32.
8357 if (NumSignBits > OpBits-MidBits)
8358 return new TruncInst(Op, CI.getType(), "tmp");
8359 }
8360 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008361
8362 // If the input is a shl/ashr pair of a same constant, then this is a sign
8363 // extension from a smaller value. If we could trust arbitrary bitwidth
8364 // integers, we could turn this into a truncate to the smaller bit and then
8365 // use a sext for the whole extension. Since we don't, look deeper and check
8366 // for a truncate. If the source and dest are the same type, eliminate the
8367 // trunc and extend and just do shifts. For example, turn:
8368 // %a = trunc i32 %i to i8
8369 // %b = shl i8 %a, 6
8370 // %c = ashr i8 %b, 6
8371 // %d = sext i8 %c to i32
8372 // into:
8373 // %a = shl i32 %i, 30
8374 // %d = ashr i32 %a, 30
8375 Value *A = 0;
8376 ConstantInt *BA = 0, *CA = 0;
8377 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8378 m_ConstantInt(CA))) &&
8379 BA == CA && isa<TruncInst>(A)) {
8380 Value *I = cast<TruncInst>(A)->getOperand(0);
8381 if (I->getType() == CI.getType()) {
8382 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8383 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8384 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8385 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8386 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8387 CI.getName()), CI);
8388 return BinaryOperator::CreateAShr(I, ShAmtV);
8389 }
8390 }
8391
Chris Lattnerba417832007-04-11 06:12:58 +00008392 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008393}
8394
Chris Lattnerb7530652008-01-27 05:29:54 +00008395/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8396/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008397static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008398 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008399 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008400 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8401 if (!losesInfo)
Chris Lattner02a260a2008-04-20 00:41:09 +00008402 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008403 return 0;
8404}
8405
8406/// LookThroughFPExtensions - If this is an fp extension instruction, look
8407/// through it until we get the source value.
8408static Value *LookThroughFPExtensions(Value *V) {
8409 if (Instruction *I = dyn_cast<Instruction>(V))
8410 if (I->getOpcode() == Instruction::FPExt)
8411 return LookThroughFPExtensions(I->getOperand(0));
8412
8413 // If this value is a constant, return the constant in the smallest FP type
8414 // that can accurately represent it. This allows us to turn
8415 // (float)((double)X+2.0) into x+2.0f.
8416 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8417 if (CFP->getType() == Type::PPC_FP128Ty)
8418 return V; // No constant folding of this.
8419 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008420 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008421 return V;
8422 if (CFP->getType() == Type::DoubleTy)
8423 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008424 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008425 return V;
8426 // Don't try to shrink to various long double types.
8427 }
8428
8429 return V;
8430}
8431
8432Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8433 if (Instruction *I = commonCastTransforms(CI))
8434 return I;
8435
8436 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8437 // smaller than the destination type, we can eliminate the truncate by doing
8438 // the add as the smaller type. This applies to add/sub/mul/div as well as
8439 // many builtins (sqrt, etc).
8440 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8441 if (OpI && OpI->hasOneUse()) {
8442 switch (OpI->getOpcode()) {
8443 default: break;
8444 case Instruction::Add:
8445 case Instruction::Sub:
8446 case Instruction::Mul:
8447 case Instruction::FDiv:
8448 case Instruction::FRem:
8449 const Type *SrcTy = OpI->getType();
8450 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8451 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8452 if (LHSTrunc->getType() != SrcTy &&
8453 RHSTrunc->getType() != SrcTy) {
8454 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8455 // If the source types were both smaller than the destination type of
8456 // the cast, do this xform.
8457 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8458 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8459 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8460 CI.getType(), CI);
8461 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8462 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008463 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008464 }
8465 }
8466 break;
8467 }
8468 }
8469 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008470}
8471
8472Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8473 return commonCastTransforms(CI);
8474}
8475
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008476Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008477 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8478 if (OpI == 0)
8479 return commonCastTransforms(FI);
8480
8481 // fptoui(uitofp(X)) --> X
8482 // fptoui(sitofp(X)) --> X
8483 // This is safe if the intermediate type has enough bits in its mantissa to
8484 // accurately represent all values of X. For example, do not do this with
8485 // i64->float->i64. This is also safe for sitofp case, because any negative
8486 // 'X' value would cause an undefined result for the fptoui.
8487 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8488 OpI->getOperand(0)->getType() == FI.getType() &&
8489 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8490 OpI->getType()->getFPMantissaWidth())
8491 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008492
8493 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008494}
8495
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008496Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008497 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8498 if (OpI == 0)
8499 return commonCastTransforms(FI);
8500
8501 // fptosi(sitofp(X)) --> X
8502 // fptosi(uitofp(X)) --> X
8503 // This is safe if the intermediate type has enough bits in its mantissa to
8504 // accurately represent all values of X. For example, do not do this with
8505 // i64->float->i64. This is also safe for sitofp case, because any negative
8506 // 'X' value would cause an undefined result for the fptoui.
8507 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8508 OpI->getOperand(0)->getType() == FI.getType() &&
8509 (int)FI.getType()->getPrimitiveSizeInBits() <=
8510 OpI->getType()->getFPMantissaWidth())
8511 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008512
8513 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008514}
8515
8516Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8517 return commonCastTransforms(CI);
8518}
8519
8520Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8521 return commonCastTransforms(CI);
8522}
8523
8524Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008525 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008526}
8527
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008528Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8529 if (Instruction *I = commonCastTransforms(CI))
8530 return I;
8531
8532 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8533 if (!DestPointee->isSized()) return 0;
8534
8535 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8536 ConstantInt *Cst;
8537 Value *X;
8538 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8539 m_ConstantInt(Cst)))) {
8540 // If the source and destination operands have the same type, see if this
8541 // is a single-index GEP.
8542 if (X->getType() == CI.getType()) {
8543 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008544 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008545
8546 // Convert the constant to intptr type.
8547 APInt Offset = Cst->getValue();
8548 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8549
8550 // If Offset is evenly divisible by Size, we can do this xform.
8551 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8552 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008553 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008554 }
8555 }
8556 // TODO: Could handle other cases, e.g. where add is indexing into field of
8557 // struct etc.
8558 } else if (CI.getOperand(0)->hasOneUse() &&
8559 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8560 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8561 // "inttoptr+GEP" instead of "add+intptr".
8562
8563 // Get the size of the pointee type.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00008564 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008565
8566 // Convert the constant to intptr type.
8567 APInt Offset = Cst->getValue();
8568 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8569
8570 // If Offset is evenly divisible by Size, we can do this xform.
8571 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8572 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8573
8574 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8575 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008576 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008577 }
8578 }
8579 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008580}
8581
Chris Lattnerd3e28342007-04-27 17:44:50 +00008582Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008583 // If the operands are integer typed then apply the integer transforms,
8584 // otherwise just apply the common ones.
8585 Value *Src = CI.getOperand(0);
8586 const Type *SrcTy = Src->getType();
8587 const Type *DestTy = CI.getType();
8588
Chris Lattner42a75512007-01-15 02:27:26 +00008589 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008590 if (Instruction *Result = commonIntCastTransforms(CI))
8591 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008592 } else if (isa<PointerType>(SrcTy)) {
8593 if (Instruction *I = commonPointerCastTransforms(CI))
8594 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008595 } else {
8596 if (Instruction *Result = commonCastTransforms(CI))
8597 return Result;
8598 }
8599
8600
8601 // Get rid of casts from one type to the same type. These are useless and can
8602 // be replaced by the operand.
8603 if (DestTy == Src->getType())
8604 return ReplaceInstUsesWith(CI, Src);
8605
Reid Spencer3da59db2006-11-27 01:05:10 +00008606 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008607 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8608 const Type *DstElTy = DstPTy->getElementType();
8609 const Type *SrcElTy = SrcPTy->getElementType();
8610
Nate Begeman83ad90a2008-03-31 00:22:16 +00008611 // If the address spaces don't match, don't eliminate the bitcast, which is
8612 // required for changing types.
8613 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8614 return 0;
8615
Chris Lattnerd3e28342007-04-27 17:44:50 +00008616 // If we are casting a malloc or alloca to a pointer to a type of the same
8617 // size, rewrite the allocation instruction to allocate the "right" type.
8618 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8619 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8620 return V;
8621
Chris Lattnerd717c182007-05-05 22:32:24 +00008622 // If the source and destination are pointers, and this cast is equivalent
8623 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008624 // This can enhance SROA and other transforms that want type-safe pointers.
8625 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8626 unsigned NumZeros = 0;
8627 while (SrcElTy != DstElTy &&
8628 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8629 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8630 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8631 ++NumZeros;
8632 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008633
Chris Lattnerd3e28342007-04-27 17:44:50 +00008634 // If we found a path from the src to dest, create the getelementptr now.
8635 if (SrcElTy == DstElTy) {
8636 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008637 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8638 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008639 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008640 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008641
Reid Spencer3da59db2006-11-27 01:05:10 +00008642 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8643 if (SVI->hasOneUse()) {
8644 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8645 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008646 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008647 cast<VectorType>(DestTy)->getNumElements() ==
8648 SVI->getType()->getNumElements() &&
8649 SVI->getType()->getNumElements() ==
8650 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008651 CastInst *Tmp;
8652 // If either of the operands is a cast from CI.getType(), then
8653 // evaluating the shuffle in the casted destination's type will allow
8654 // us to eliminate at least one cast.
8655 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8656 Tmp->getOperand(0)->getType() == DestTy) ||
8657 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8658 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008659 Value *LHS = InsertCastBefore(Instruction::BitCast,
8660 SVI->getOperand(0), DestTy, CI);
8661 Value *RHS = InsertCastBefore(Instruction::BitCast,
8662 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008663 // Return a new shuffle vector. Use the same element ID's, as we
8664 // know the vector types match #elts.
8665 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008666 }
8667 }
8668 }
8669 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008670 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008671}
8672
Chris Lattnere576b912004-04-09 23:46:01 +00008673/// GetSelectFoldableOperands - We want to turn code that looks like this:
8674/// %C = or %A, %B
8675/// %D = select %cond, %C, %A
8676/// into:
8677/// %C = select %cond, %B, 0
8678/// %D = or %A, %C
8679///
8680/// Assuming that the specified instruction is an operand to the select, return
8681/// a bitmask indicating which operands of this instruction are foldable if they
8682/// equal the other incoming value of the select.
8683///
8684static unsigned GetSelectFoldableOperands(Instruction *I) {
8685 switch (I->getOpcode()) {
8686 case Instruction::Add:
8687 case Instruction::Mul:
8688 case Instruction::And:
8689 case Instruction::Or:
8690 case Instruction::Xor:
8691 return 3; // Can fold through either operand.
8692 case Instruction::Sub: // Can only fold on the amount subtracted.
8693 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008694 case Instruction::LShr:
8695 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008696 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008697 default:
8698 return 0; // Cannot fold
8699 }
8700}
8701
8702/// GetSelectFoldableConstant - For the same transformation as the previous
8703/// function, return the identity constant that goes into the select.
8704static Constant *GetSelectFoldableConstant(Instruction *I) {
8705 switch (I->getOpcode()) {
8706 default: assert(0 && "This cannot happen!"); abort();
8707 case Instruction::Add:
8708 case Instruction::Sub:
8709 case Instruction::Or:
8710 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008711 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008712 case Instruction::LShr:
8713 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008714 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008715 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008716 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008717 case Instruction::Mul:
8718 return ConstantInt::get(I->getType(), 1);
8719 }
8720}
8721
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008722/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8723/// have the same opcode and only one use each. Try to simplify this.
8724Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8725 Instruction *FI) {
8726 if (TI->getNumOperands() == 1) {
8727 // If this is a non-volatile load or a cast from the same type,
8728 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008729 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008730 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8731 return 0;
8732 } else {
8733 return 0; // unknown unary op.
8734 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008735
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008736 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008737 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8738 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008739 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008740 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008741 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008742 }
8743
Reid Spencer832254e2007-02-02 02:16:23 +00008744 // Only handle binary operators here.
8745 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008746 return 0;
8747
8748 // Figure out if the operations have any operands in common.
8749 Value *MatchOp, *OtherOpT, *OtherOpF;
8750 bool MatchIsOpZero;
8751 if (TI->getOperand(0) == FI->getOperand(0)) {
8752 MatchOp = TI->getOperand(0);
8753 OtherOpT = TI->getOperand(1);
8754 OtherOpF = FI->getOperand(1);
8755 MatchIsOpZero = true;
8756 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8757 MatchOp = TI->getOperand(1);
8758 OtherOpT = TI->getOperand(0);
8759 OtherOpF = FI->getOperand(0);
8760 MatchIsOpZero = false;
8761 } else if (!TI->isCommutative()) {
8762 return 0;
8763 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8764 MatchOp = TI->getOperand(0);
8765 OtherOpT = TI->getOperand(1);
8766 OtherOpF = FI->getOperand(0);
8767 MatchIsOpZero = true;
8768 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8769 MatchOp = TI->getOperand(1);
8770 OtherOpT = TI->getOperand(0);
8771 OtherOpF = FI->getOperand(1);
8772 MatchIsOpZero = true;
8773 } else {
8774 return 0;
8775 }
8776
8777 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008778 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8779 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008780 InsertNewInstBefore(NewSI, SI);
8781
8782 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8783 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008784 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008785 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008786 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008787 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008788 assert(0 && "Shouldn't get here");
8789 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008790}
8791
Dan Gohman81b28ce2008-09-16 18:46:06 +00008792/// visitSelectInstWithICmp - Visit a SelectInst that has an
8793/// ICmpInst as its first operand.
8794///
8795Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8796 ICmpInst *ICI) {
8797 bool Changed = false;
8798 ICmpInst::Predicate Pred = ICI->getPredicate();
8799 Value *CmpLHS = ICI->getOperand(0);
8800 Value *CmpRHS = ICI->getOperand(1);
8801 Value *TrueVal = SI.getTrueValue();
8802 Value *FalseVal = SI.getFalseValue();
8803
8804 // Check cases where the comparison is with a constant that
8805 // can be adjusted to fit the min/max idiom. We may edit ICI in
8806 // place here, so make sure the select is the only user.
8807 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00008808 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00008809 switch (Pred) {
8810 default: break;
8811 case ICmpInst::ICMP_ULT:
8812 case ICmpInst::ICMP_SLT: {
8813 // X < MIN ? T : F --> F
8814 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8815 return ReplaceInstUsesWith(SI, FalseVal);
8816 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8817 Constant *AdjustedRHS = SubOne(CI);
8818 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8819 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8820 Pred = ICmpInst::getSwappedPredicate(Pred);
8821 CmpRHS = AdjustedRHS;
8822 std::swap(FalseVal, TrueVal);
8823 ICI->setPredicate(Pred);
8824 ICI->setOperand(1, CmpRHS);
8825 SI.setOperand(1, TrueVal);
8826 SI.setOperand(2, FalseVal);
8827 Changed = true;
8828 }
8829 break;
8830 }
8831 case ICmpInst::ICMP_UGT:
8832 case ICmpInst::ICMP_SGT: {
8833 // X > MAX ? T : F --> F
8834 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8835 return ReplaceInstUsesWith(SI, FalseVal);
8836 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8837 Constant *AdjustedRHS = AddOne(CI);
8838 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8839 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8840 Pred = ICmpInst::getSwappedPredicate(Pred);
8841 CmpRHS = AdjustedRHS;
8842 std::swap(FalseVal, TrueVal);
8843 ICI->setPredicate(Pred);
8844 ICI->setOperand(1, CmpRHS);
8845 SI.setOperand(1, TrueVal);
8846 SI.setOperand(2, FalseVal);
8847 Changed = true;
8848 }
8849 break;
8850 }
8851 }
8852
Dan Gohman1975d032008-10-30 20:40:10 +00008853 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8854 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00008855 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner159c35b2009-01-05 23:53:12 +00008856 if (match(TrueVal, m_ConstantInt<-1>()) &&
8857 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008858 Pred = ICI->getPredicate();
Chris Lattner159c35b2009-01-05 23:53:12 +00008859 else if (match(TrueVal, m_ConstantInt<0>()) &&
8860 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00008861 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8862
Dan Gohman1975d032008-10-30 20:40:10 +00008863 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8864 // If we are just checking for a icmp eq of a single bit and zext'ing it
8865 // to an integer, then shift the bit to the appropriate place and then
8866 // cast to integer to avoid the comparison.
8867 const APInt &Op1CV = CI->getValue();
8868
8869 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8870 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8871 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00008872 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00008873 Value *In = ICI->getOperand(0);
8874 Value *Sh = ConstantInt::get(In->getType(),
8875 In->getType()->getPrimitiveSizeInBits()-1);
8876 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8877 In->getName()+".lobit"),
8878 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00008879 if (In->getType() != SI.getType())
8880 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00008881 true/*SExt*/, "tmp", ICI);
8882
8883 if (Pred == ICmpInst::ICMP_SGT)
8884 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8885 In->getName()+".not"), *ICI);
8886
8887 return ReplaceInstUsesWith(SI, In);
8888 }
8889 }
8890 }
8891
Dan Gohman81b28ce2008-09-16 18:46:06 +00008892 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8893 // Transform (X == Y) ? X : Y -> Y
8894 if (Pred == ICmpInst::ICMP_EQ)
8895 return ReplaceInstUsesWith(SI, FalseVal);
8896 // Transform (X != Y) ? X : Y -> X
8897 if (Pred == ICmpInst::ICMP_NE)
8898 return ReplaceInstUsesWith(SI, TrueVal);
8899 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8900
8901 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8902 // Transform (X == Y) ? Y : X -> X
8903 if (Pred == ICmpInst::ICMP_EQ)
8904 return ReplaceInstUsesWith(SI, FalseVal);
8905 // Transform (X != Y) ? Y : X -> Y
8906 if (Pred == ICmpInst::ICMP_NE)
8907 return ReplaceInstUsesWith(SI, TrueVal);
8908 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8909 }
8910
8911 /// NOTE: if we wanted to, this is where to detect integer ABS
8912
8913 return Changed ? &SI : 0;
8914}
8915
Chris Lattner3d69f462004-03-12 05:52:32 +00008916Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008917 Value *CondVal = SI.getCondition();
8918 Value *TrueVal = SI.getTrueValue();
8919 Value *FalseVal = SI.getFalseValue();
8920
8921 // select true, X, Y -> X
8922 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008923 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008924 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008925
8926 // select C, X, X -> X
8927 if (TrueVal == FalseVal)
8928 return ReplaceInstUsesWith(SI, TrueVal);
8929
Chris Lattnere87597f2004-10-16 18:11:37 +00008930 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8931 return ReplaceInstUsesWith(SI, FalseVal);
8932 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8933 return ReplaceInstUsesWith(SI, TrueVal);
8934 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8935 if (isa<Constant>(TrueVal))
8936 return ReplaceInstUsesWith(SI, TrueVal);
8937 else
8938 return ReplaceInstUsesWith(SI, FalseVal);
8939 }
8940
Reid Spencer4fe16d62007-01-11 18:21:29 +00008941 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008942 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008943 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008944 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008945 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008946 } else {
8947 // Change: A = select B, false, C --> A = and !B, C
8948 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008949 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008950 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008951 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008952 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008953 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008954 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008955 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008956 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008957 } else {
8958 // Change: A = select B, C, true --> A = or !B, C
8959 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008960 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008961 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008962 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008963 }
8964 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008965
8966 // select a, b, a -> a&b
8967 // select a, a, b -> a|b
8968 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008969 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008970 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008971 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008972 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008973
Chris Lattner2eefe512004-04-09 19:05:30 +00008974 // Selecting between two integer constants?
8975 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8976 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008977 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008978 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008979 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008980 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008981 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008982 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008983 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008984 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008985 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008986 }
Chris Lattner457dd822004-06-09 07:59:58 +00008987
Reid Spencere4d87aa2006-12-23 06:05:41 +00008988 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008989
Reid Spencere4d87aa2006-12-23 06:05:41 +00008990 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008991 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008992 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008993 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008994 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008995 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008996 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008997 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008998 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008999 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00009000 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00009001 InsertNewInstBefore(SRA, SI);
Eli Friedmand1fd1da2008-11-30 21:09:11 +00009002
9003 // Then cast to the appropriate width.
9004 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Chris Lattnerb8456462006-09-20 04:44:59 +00009005 }
9006 }
9007
9008
9009 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009010 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009011 // non-constant value, eliminate this whole mess. This corresponds to
9012 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009013 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009014 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009015 cast<Constant>(IC->getOperand(1))->isNullValue())
9016 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9017 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009018 isa<ConstantInt>(ICA->getOperand(1)) &&
9019 (ICA->getOperand(1) == TrueValC ||
9020 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009021 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9022 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009023 // know whether we have a icmp_ne or icmp_eq and whether the
9024 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009025 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009026 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009027 Value *V = ICA;
9028 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009029 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009030 Instruction::Xor, V, ICA->getOperand(1)), SI);
9031 return ReplaceInstUsesWith(SI, V);
9032 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009033 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009034 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009035
9036 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009037 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9038 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009039 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009040 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9041 // This is not safe in general for floating point:
9042 // consider X== -0, Y== +0.
9043 // It becomes safe if either operand is a nonzero constant.
9044 ConstantFP *CFPt, *CFPf;
9045 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9046 !CFPt->getValueAPF().isZero()) ||
9047 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9048 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009049 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009050 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009051 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009052 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009053 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009054 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009055
Reid Spencere4d87aa2006-12-23 06:05:41 +00009056 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009057 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009058 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9059 // This is not safe in general for floating point:
9060 // consider X== -0, Y== +0.
9061 // It becomes safe if either operand is a nonzero constant.
9062 ConstantFP *CFPt, *CFPf;
9063 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9064 !CFPt->getValueAPF().isZero()) ||
9065 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9066 !CFPf->getValueAPF().isZero()))
9067 return ReplaceInstUsesWith(SI, FalseVal);
9068 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009069 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009070 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9071 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009072 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009073 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009074 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009075 }
9076
9077 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009078 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9079 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9080 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009081
Chris Lattner87875da2005-01-13 22:52:24 +00009082 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9083 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9084 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009085 Instruction *AddOp = 0, *SubOp = 0;
9086
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009087 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9088 if (TI->getOpcode() == FI->getOpcode())
9089 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9090 return IV;
9091
9092 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9093 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00009094 if (TI->getOpcode() == Instruction::Sub &&
9095 FI->getOpcode() == Instruction::Add) {
9096 AddOp = FI; SubOp = TI;
9097 } else if (FI->getOpcode() == Instruction::Sub &&
9098 TI->getOpcode() == Instruction::Add) {
9099 AddOp = TI; SubOp = FI;
9100 }
9101
9102 if (AddOp) {
9103 Value *OtherAddOp = 0;
9104 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9105 OtherAddOp = AddOp->getOperand(1);
9106 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9107 OtherAddOp = AddOp->getOperand(0);
9108 }
9109
9110 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009111 // So at this point we know we have (Y -> OtherAddOp):
9112 // select C, (add X, Y), (sub X, Z)
9113 Value *NegVal; // Compute -Z
9114 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9115 NegVal = ConstantExpr::getNeg(C);
9116 } else {
9117 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009118 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009119 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009120
9121 Value *NewTrueOp = OtherAddOp;
9122 Value *NewFalseOp = NegVal;
9123 if (AddOp != TI)
9124 std::swap(NewTrueOp, NewFalseOp);
9125 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009126 SelectInst::Create(CondVal, NewTrueOp,
9127 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009128
9129 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009130 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009131 }
9132 }
9133 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009134
Chris Lattnere576b912004-04-09 23:46:01 +00009135 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009136 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00009137 // See the comment above GetSelectFoldableOperands for a description of the
9138 // transformation we are doing here.
9139 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9140 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9141 !isa<Constant>(FalseVal))
9142 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9143 unsigned OpToFold = 0;
9144 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9145 OpToFold = 1;
9146 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9147 OpToFold = 2;
9148 }
9149
9150 if (OpToFold) {
9151 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009152 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009153 SelectInst::Create(SI.getCondition(),
9154 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00009155 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009156 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009157 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009158 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00009159 else {
9160 assert(0 && "Unknown instruction!!");
9161 }
9162 }
9163 }
Chris Lattnera96879a2004-09-29 17:40:11 +00009164
Chris Lattnere576b912004-04-09 23:46:01 +00009165 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9166 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9167 !isa<Constant>(TrueVal))
9168 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9169 unsigned OpToFold = 0;
9170 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9171 OpToFold = 1;
9172 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9173 OpToFold = 2;
9174 }
9175
9176 if (OpToFold) {
9177 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009178 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009179 SelectInst::Create(SI.getCondition(), C,
9180 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00009181 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00009182 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00009183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009184 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00009185 else
Chris Lattnere576b912004-04-09 23:46:01 +00009186 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00009187 }
9188 }
9189 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009190
9191 if (BinaryOperator::isNot(CondVal)) {
9192 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9193 SI.setOperand(1, FalseVal);
9194 SI.setOperand(2, TrueVal);
9195 return &SI;
9196 }
9197
Chris Lattner3d69f462004-03-12 05:52:32 +00009198 return 0;
9199}
9200
Dan Gohmaneee962e2008-04-10 18:43:06 +00009201/// EnforceKnownAlignment - If the specified pointer points to an object that
9202/// we control, modify the object's alignment to PrefAlign. This isn't
9203/// often possible though. If alignment is important, a more reliable approach
9204/// is to simply align all global variables and allocation instructions to
9205/// their preferred alignment from the beginning.
9206///
9207static unsigned EnforceKnownAlignment(Value *V,
9208 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009209
Dan Gohmaneee962e2008-04-10 18:43:06 +00009210 User *U = dyn_cast<User>(V);
9211 if (!U) return Align;
9212
9213 switch (getOpcode(U)) {
9214 default: break;
9215 case Instruction::BitCast:
9216 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9217 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009218 // If all indexes are zero, it is just the alignment of the base pointer.
9219 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009220 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009221 if (!isa<Constant>(*i) ||
9222 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009223 AllZeroOperands = false;
9224 break;
9225 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009226
9227 if (AllZeroOperands) {
9228 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009229 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009230 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009231 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009232 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009233 }
9234
9235 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9236 // If there is a large requested alignment and we can, bump up the alignment
9237 // of the global.
9238 if (!GV->isDeclaration()) {
9239 GV->setAlignment(PrefAlign);
9240 Align = PrefAlign;
9241 }
9242 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9243 // If there is a requested alignment and if this is an alloca, round up. We
9244 // don't do this for malloc, because some systems can't respect the request.
9245 if (isa<AllocaInst>(AI)) {
9246 AI->setAlignment(PrefAlign);
9247 Align = PrefAlign;
9248 }
9249 }
9250
9251 return Align;
9252}
9253
9254/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9255/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9256/// and it is more than the alignment of the ultimate object, see if we can
9257/// increase the alignment of the ultimate object, making this check succeed.
9258unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9259 unsigned PrefAlign) {
9260 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9261 sizeof(PrefAlign) * CHAR_BIT;
9262 APInt Mask = APInt::getAllOnesValue(BitWidth);
9263 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9264 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9265 unsigned TrailZ = KnownZero.countTrailingOnes();
9266 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9267
9268 if (PrefAlign > Align)
9269 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9270
9271 // We don't need to make any adjustment.
9272 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009273}
9274
Chris Lattnerf497b022008-01-13 23:50:23 +00009275Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009276 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9277 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009278 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9279 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9280
9281 if (CopyAlign < MinAlign) {
9282 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9283 return MI;
9284 }
9285
9286 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9287 // load/store.
9288 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9289 if (MemOpLength == 0) return 0;
9290
Chris Lattner37ac6082008-01-14 00:28:35 +00009291 // Source and destination pointer types are always "i8*" for intrinsic. See
9292 // if the size is something we can handle with a single primitive load/store.
9293 // A single load+store correctly handles overlapping memory in the memmove
9294 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009295 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009296 if (Size == 0) return MI; // Delete this mem transfer.
9297
9298 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009299 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009300
Chris Lattner37ac6082008-01-14 00:28:35 +00009301 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009302 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009303
9304 // Memcpy forces the use of i8* for the source and destination. That means
9305 // that if you're using memcpy to move one double around, you'll get a cast
9306 // from double* to i8*. We'd much rather use a double load+store rather than
9307 // an i64 load+store, here because this improves the odds that the source or
9308 // dest address will be promotable. See if we can find a better type than the
9309 // integer datatype.
9310 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9311 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9312 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9313 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9314 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009315 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009316 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9317 if (STy->getNumElements() == 1)
9318 SrcETy = STy->getElementType(0);
9319 else
9320 break;
9321 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9322 if (ATy->getNumElements() == 1)
9323 SrcETy = ATy->getElementType();
9324 else
9325 break;
9326 } else
9327 break;
9328 }
9329
Dan Gohman8f8e2692008-05-23 01:52:21 +00009330 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009331 NewPtrTy = PointerType::getUnqual(SrcETy);
9332 }
9333 }
9334
9335
Chris Lattnerf497b022008-01-13 23:50:23 +00009336 // If the memcpy/memmove provides better alignment info than we can
9337 // infer, use it.
9338 SrcAlign = std::max(SrcAlign, CopyAlign);
9339 DstAlign = std::max(DstAlign, CopyAlign);
9340
9341 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9342 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009343 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9344 InsertNewInstBefore(L, *MI);
9345 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9346
9347 // Set the size of the copy to 0, it will be deleted on the next iteration.
9348 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9349 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009350}
Chris Lattner3d69f462004-03-12 05:52:32 +00009351
Chris Lattner69ea9d22008-04-30 06:39:11 +00009352Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9353 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9354 if (MI->getAlignment()->getZExtValue() < Alignment) {
9355 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9356 return MI;
9357 }
9358
9359 // Extract the length and alignment and fill if they are constant.
9360 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9361 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9362 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9363 return 0;
9364 uint64_t Len = LenC->getZExtValue();
9365 Alignment = MI->getAlignment()->getZExtValue();
9366
9367 // If the length is zero, this is a no-op
9368 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9369
9370 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9371 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9372 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9373
9374 Value *Dest = MI->getDest();
9375 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9376
9377 // Alignment 0 is identity for alignment 1 for memset, but not store.
9378 if (Alignment == 0) Alignment = 1;
9379
9380 // Extract the fill value and store.
9381 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9382 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9383 Alignment), *MI);
9384
9385 // Set the size of the copy to 0, it will be deleted on the next iteration.
9386 MI->setLength(Constant::getNullValue(LenC->getType()));
9387 return MI;
9388 }
9389
9390 return 0;
9391}
9392
9393
Chris Lattner8b0ea312006-01-13 20:11:04 +00009394/// visitCallInst - CallInst simplification. This mostly only handles folding
9395/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9396/// the heavy lifting.
9397///
Chris Lattner9fe38862003-06-19 17:00:31 +00009398Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009399 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9400 if (!II) return visitCallSite(&CI);
9401
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009402 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9403 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009404 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009405 bool Changed = false;
9406
9407 // memmove/cpy/set of zero bytes is a noop.
9408 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9409 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9410
Chris Lattner35b9e482004-10-12 04:52:52 +00009411 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009412 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009413 // Replace the instruction with just byte operations. We would
9414 // transform other cases to loads/stores, but we don't know if
9415 // alignment is sufficient.
9416 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009417 }
9418
Chris Lattner35b9e482004-10-12 04:52:52 +00009419 // If we have a memmove and the source operation is a constant global,
9420 // then the source and dest pointers can't alias, so we can change this
9421 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009422 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009423 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9424 if (GVSrc->isConstant()) {
9425 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009426 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9427 const Type *Tys[1];
9428 Tys[0] = CI.getOperand(3)->getType();
9429 CI.setOperand(0,
9430 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009431 Changed = true;
9432 }
Chris Lattnera935db82008-05-28 05:30:41 +00009433
9434 // memmove(x,x,size) -> noop.
9435 if (MMI->getSource() == MMI->getDest())
9436 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009437 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009438
Chris Lattner95a959d2006-03-06 20:18:44 +00009439 // If we can determine a pointer alignment that is bigger than currently
9440 // set, update the alignment.
9441 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009442 if (Instruction *I = SimplifyMemTransfer(MI))
9443 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009444 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9445 if (Instruction *I = SimplifyMemSet(MSI))
9446 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009447 }
9448
Chris Lattner8b0ea312006-01-13 20:11:04 +00009449 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009450 }
9451
9452 switch (II->getIntrinsicID()) {
9453 default: break;
9454 case Intrinsic::bswap:
9455 // bswap(bswap(x)) -> x
9456 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9457 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9458 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9459 break;
9460 case Intrinsic::ppc_altivec_lvx:
9461 case Intrinsic::ppc_altivec_lvxl:
9462 case Intrinsic::x86_sse_loadu_ps:
9463 case Intrinsic::x86_sse2_loadu_pd:
9464 case Intrinsic::x86_sse2_loadu_dq:
9465 // Turn PPC lvx -> load if the pointer is known aligned.
9466 // Turn X86 loadups -> load if the pointer is known aligned.
9467 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9468 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9469 PointerType::getUnqual(II->getType()),
9470 CI);
9471 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009472 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009473 break;
9474 case Intrinsic::ppc_altivec_stvx:
9475 case Intrinsic::ppc_altivec_stvxl:
9476 // Turn stvx -> store if the pointer is known aligned.
9477 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9478 const Type *OpPtrTy =
9479 PointerType::getUnqual(II->getOperand(1)->getType());
9480 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9481 return new StoreInst(II->getOperand(1), Ptr);
9482 }
9483 break;
9484 case Intrinsic::x86_sse_storeu_ps:
9485 case Intrinsic::x86_sse2_storeu_pd:
9486 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009487 // Turn X86 storeu -> store if the pointer is known aligned.
9488 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9489 const Type *OpPtrTy =
9490 PointerType::getUnqual(II->getOperand(2)->getType());
9491 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9492 return new StoreInst(II->getOperand(2), Ptr);
9493 }
9494 break;
9495
9496 case Intrinsic::x86_sse_cvttss2si: {
9497 // These intrinsics only demands the 0th element of its input vector. If
9498 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009499 unsigned VWidth =
9500 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9501 APInt DemandedElts(VWidth, 1);
9502 APInt UndefElts(VWidth, 0);
9503 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009504 UndefElts)) {
9505 II->setOperand(1, V);
9506 return II;
9507 }
9508 break;
9509 }
9510
9511 case Intrinsic::ppc_altivec_vperm:
9512 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9513 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9514 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009515
Chris Lattner0521e3c2008-06-18 04:33:20 +00009516 // Check that all of the elements are integer constants or undefs.
9517 bool AllEltsOk = true;
9518 for (unsigned i = 0; i != 16; ++i) {
9519 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9520 !isa<UndefValue>(Mask->getOperand(i))) {
9521 AllEltsOk = false;
9522 break;
9523 }
9524 }
9525
9526 if (AllEltsOk) {
9527 // Cast the input vectors to byte vectors.
9528 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9529 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9530 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009531
Chris Lattner0521e3c2008-06-18 04:33:20 +00009532 // Only extract each element once.
9533 Value *ExtractedElts[32];
9534 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9535
Chris Lattnere2ed0572006-04-06 19:19:17 +00009536 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009537 if (isa<UndefValue>(Mask->getOperand(i)))
9538 continue;
9539 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9540 Idx &= 31; // Match the hardware behavior.
9541
9542 if (ExtractedElts[Idx] == 0) {
9543 Instruction *Elt =
9544 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9545 InsertNewInstBefore(Elt, CI);
9546 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009547 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009548
Chris Lattner0521e3c2008-06-18 04:33:20 +00009549 // Insert this value into the result vector.
9550 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9551 i, "tmp");
9552 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009553 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009554 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009555 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009556 }
9557 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009558
Chris Lattner0521e3c2008-06-18 04:33:20 +00009559 case Intrinsic::stackrestore: {
9560 // If the save is right next to the restore, remove the restore. This can
9561 // happen when variable allocas are DCE'd.
9562 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9563 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9564 BasicBlock::iterator BI = SS;
9565 if (&*++BI == II)
9566 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009567 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009568 }
9569
9570 // Scan down this block to see if there is another stack restore in the
9571 // same block without an intervening call/alloca.
9572 BasicBlock::iterator BI = II;
9573 TerminatorInst *TI = II->getParent()->getTerminator();
9574 bool CannotRemove = false;
9575 for (++BI; &*BI != TI; ++BI) {
9576 if (isa<AllocaInst>(BI)) {
9577 CannotRemove = true;
9578 break;
9579 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009580 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9581 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9582 // If there is a stackrestore below this one, remove this one.
9583 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9584 return EraseInstFromFunction(CI);
9585 // Otherwise, ignore the intrinsic.
9586 } else {
9587 // If we found a non-intrinsic call, we can't remove the stack
9588 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009589 CannotRemove = true;
9590 break;
9591 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009592 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009593 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009594
9595 // If the stack restore is in a return/unwind block and if there are no
9596 // allocas or calls between the restore and the return, nuke the restore.
9597 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9598 return EraseInstFromFunction(CI);
9599 break;
9600 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009601 }
9602
Chris Lattner8b0ea312006-01-13 20:11:04 +00009603 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009604}
9605
9606// InvokeInst simplification
9607//
9608Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009609 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009610}
9611
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009612/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9613/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009614static bool isSafeToEliminateVarargsCast(const CallSite CS,
9615 const CastInst * const CI,
9616 const TargetData * const TD,
9617 const int ix) {
9618 if (!CI->isLosslessCast())
9619 return false;
9620
9621 // The size of ByVal arguments is derived from the type, so we
9622 // can't change to a type with a different size. If the size were
9623 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009624 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009625 return true;
9626
9627 const Type* SrcTy =
9628 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9629 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9630 if (!SrcTy->isSized() || !DstTy->isSized())
9631 return false;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00009632 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009633 return false;
9634 return true;
9635}
9636
Chris Lattnera44d8a22003-10-07 22:32:43 +00009637// visitCallSite - Improvements for call and invoke instructions.
9638//
9639Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009640 bool Changed = false;
9641
9642 // If the callee is a constexpr cast of a function, attempt to move the cast
9643 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009644 if (transformConstExprCastCall(CS)) return 0;
9645
Chris Lattner6c266db2003-10-07 22:54:13 +00009646 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009647
Chris Lattner08b22ec2005-05-13 07:09:09 +00009648 if (Function *CalleeF = dyn_cast<Function>(Callee))
9649 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9650 Instruction *OldCall = CS.getInstruction();
9651 // If the call and callee calling conventions don't match, this call must
9652 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009653 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009654 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9655 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009656 if (!OldCall->use_empty())
9657 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9658 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9659 return EraseInstFromFunction(*OldCall);
9660 return 0;
9661 }
9662
Chris Lattner17be6352004-10-18 02:59:09 +00009663 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9664 // This instruction is not reachable, just remove it. We insert a store to
9665 // undef so that we know that this code is not reachable, despite the fact
9666 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009667 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009668 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009669 CS.getInstruction());
9670
9671 if (!CS.getInstruction()->use_empty())
9672 CS.getInstruction()->
9673 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9674
9675 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9676 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009677 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9678 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009679 }
Chris Lattner17be6352004-10-18 02:59:09 +00009680 return EraseInstFromFunction(*CS.getInstruction());
9681 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009682
Duncan Sandscdb6d922007-09-17 10:26:40 +00009683 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9684 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9685 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9686 return transformCallThroughTrampoline(CS);
9687
Chris Lattner6c266db2003-10-07 22:54:13 +00009688 const PointerType *PTy = cast<PointerType>(Callee->getType());
9689 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9690 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009691 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009692 // See if we can optimize any arguments passed through the varargs area of
9693 // the call.
9694 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009695 E = CS.arg_end(); I != E; ++I, ++ix) {
9696 CastInst *CI = dyn_cast<CastInst>(*I);
9697 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9698 *I = CI->getOperand(0);
9699 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009700 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009701 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009702 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009703
Duncan Sandsf0c33542007-12-19 21:13:37 +00009704 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009705 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009706 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009707 Changed = true;
9708 }
9709
Chris Lattner6c266db2003-10-07 22:54:13 +00009710 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009711}
9712
Chris Lattner9fe38862003-06-19 17:00:31 +00009713// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9714// attempt to move the cast to the arguments of the call/invoke.
9715//
9716bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9717 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9718 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009719 if (CE->getOpcode() != Instruction::BitCast ||
9720 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009721 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009722 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009723 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009724 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009725
9726 // Okay, this is a cast from a function to a different type. Unless doing so
9727 // would cause a type conversion of one of our arguments, change this call to
9728 // be a direct call with arguments casted to the appropriate types.
9729 //
9730 const FunctionType *FT = Callee->getFunctionType();
9731 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009732 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009733
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009734 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009735 return false; // TODO: Handle multiple return values.
9736
Chris Lattnerf78616b2004-01-14 06:06:08 +00009737 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009738 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009739 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009740 // Conversion is ok if changing from one pointer type to another or from
9741 // a pointer to an integer of the same size.
9742 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands34b176a2008-06-17 15:55:30 +00009743 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Chris Lattnerec479922007-01-06 02:09:32 +00009744 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009745
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009746 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009747 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009748 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009749 return false; // Cannot transform this return value.
9750
Chris Lattner58d74912008-03-12 17:45:29 +00009751 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009752 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009753 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009754 return false; // Attribute not compatible with transformed value.
9755 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009756
Chris Lattnerf78616b2004-01-14 06:06:08 +00009757 // If the callsite is an invoke instruction, and the return value is used by
9758 // a PHI node in a successor, we cannot change the return type of the call
9759 // because there is no place to put the cast instruction (without breaking
9760 // the critical edge). Bail out in this case.
9761 if (!Caller->use_empty())
9762 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9763 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9764 UI != E; ++UI)
9765 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9766 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009767 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009768 return false;
9769 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009770
9771 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9772 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009773
Chris Lattner9fe38862003-06-19 17:00:31 +00009774 CallSite::arg_iterator AI = CS.arg_begin();
9775 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9776 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009777 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009778
9779 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009780 return false; // Cannot transform this parameter value.
9781
Devang Patel19c87462008-09-26 22:53:05 +00009782 if (CallerPAL.getParamAttributes(i + 1)
9783 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +00009784 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009785
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009786 // Converting from one pointer type to another or between a pointer and an
9787 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009788 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009789 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9790 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009791 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009792 }
9793
9794 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009795 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009796 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009797
Chris Lattner58d74912008-03-12 17:45:29 +00009798 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9799 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009800 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009801 // won't be dropping them. Check that these extra arguments have attributes
9802 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009803 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9804 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009805 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +00009806 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +00009807 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +00009808 return false;
9809 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009810
Chris Lattner9fe38862003-06-19 17:00:31 +00009811 // Okay, we decided that this is a safe thing to do: go ahead and start
9812 // inserting cast instructions as necessary...
9813 std::vector<Value*> Args;
9814 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +00009815 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009816 attrVec.reserve(NumCommonArgs);
9817
9818 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009819 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009820
9821 // If the return value is not being used, the type may not be compatible
9822 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +00009823 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009824
9825 // Add the new return attributes.
9826 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +00009827 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009828
9829 AI = CS.arg_begin();
9830 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9831 const Type *ParamTy = FT->getParamType(i);
9832 if ((*AI)->getType() == ParamTy) {
9833 Args.push_back(*AI);
9834 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009835 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009836 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009837 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009838 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009839 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009840
9841 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009842 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009843 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009844 }
9845
9846 // If the function takes more arguments than the call was taking, add them
9847 // now...
9848 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9849 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9850
9851 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009852 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009853 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009854 cerr << "WARNING: While resolving call to function '"
9855 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009856 } else {
9857 // Add all of the arguments in their promoted form to the arg list...
9858 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9859 const Type *PTy = getPromotedType((*AI)->getType());
9860 if (PTy != (*AI)->getType()) {
9861 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009862 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9863 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009864 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009865 InsertNewInstBefore(Cast, *Caller);
9866 Args.push_back(Cast);
9867 } else {
9868 Args.push_back(*AI);
9869 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009870
Duncan Sandse1e520f2008-01-13 08:02:44 +00009871 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +00009872 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +00009873 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +00009874 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009875 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009876 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009877
Devang Patel19c87462008-09-26 22:53:05 +00009878 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9879 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9880
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009881 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009882 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009883
Devang Patel05988662008-09-25 21:00:45 +00009884 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009885
Chris Lattner9fe38862003-06-19 17:00:31 +00009886 Instruction *NC;
9887 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009888 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009889 Args.begin(), Args.end(),
9890 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009891 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009892 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009893 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009894 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9895 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009896 CallInst *CI = cast<CallInst>(Caller);
9897 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009898 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009899 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +00009900 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009901 }
9902
Chris Lattner6934a042007-02-11 01:23:03 +00009903 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009904 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009905 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009906 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009907 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009908 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009909 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009910
9911 // If this is an invoke instruction, we should insert it after the first
9912 // non-phi, instruction in the normal successor block.
9913 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009914 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009915 InsertNewInstBefore(NC, *I);
9916 } else {
9917 // Otherwise, it's a call, just insert cast right after the call instr
9918 InsertNewInstBefore(NC, *Caller);
9919 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009920 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009921 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009922 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009923 }
9924 }
9925
9926 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9927 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009928 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009929 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009930 return true;
9931}
9932
Duncan Sandscdb6d922007-09-17 10:26:40 +00009933// transformCallThroughTrampoline - Turn a call to a function created by the
9934// init_trampoline intrinsic into a direct call to the underlying function.
9935//
9936Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9937 Value *Callee = CS.getCalledValue();
9938 const PointerType *PTy = cast<PointerType>(Callee->getType());
9939 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +00009940 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009941
9942 // If the call already has the 'nest' attribute somewhere then give up -
9943 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +00009944 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009945 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009946
9947 IntrinsicInst *Tramp =
9948 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9949
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009950 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009951 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9952 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9953
Devang Patel05988662008-09-25 21:00:45 +00009954 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +00009955 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009956 unsigned NestIdx = 1;
9957 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +00009958 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009959
9960 // Look for a parameter marked with the 'nest' attribute.
9961 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9962 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +00009963 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009964 // Record the parameter type and any other attributes.
9965 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +00009966 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009967 break;
9968 }
9969
9970 if (NestTy) {
9971 Instruction *Caller = CS.getInstruction();
9972 std::vector<Value*> NewArgs;
9973 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9974
Devang Patel05988662008-09-25 21:00:45 +00009975 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +00009976 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009977
Duncan Sandscdb6d922007-09-17 10:26:40 +00009978 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009979 // mean appending it. Likewise for attributes.
9980
Devang Patel19c87462008-09-26 22:53:05 +00009981 // Add any result attributes.
9982 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +00009983 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009984
Duncan Sandscdb6d922007-09-17 10:26:40 +00009985 {
9986 unsigned Idx = 1;
9987 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9988 do {
9989 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009990 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009991 Value *NestVal = Tramp->getOperand(3);
9992 if (NestVal->getType() != NestTy)
9993 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9994 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +00009995 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009996 }
9997
9998 if (I == E)
9999 break;
10000
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010001 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010002 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010003 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010004 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010005 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010006
10007 ++Idx, ++I;
10008 } while (1);
10009 }
10010
Devang Patel19c87462008-09-26 22:53:05 +000010011 // Add any function attributes.
10012 if (Attributes Attr = Attrs.getFnAttributes())
10013 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10014
Duncan Sandscdb6d922007-09-17 10:26:40 +000010015 // The trampoline may have been bitcast to a bogus type (FTy).
10016 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010017 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010018
Duncan Sandscdb6d922007-09-17 10:26:40 +000010019 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010020 NewTypes.reserve(FTy->getNumParams()+1);
10021
Duncan Sandscdb6d922007-09-17 10:26:40 +000010022 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010023 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010024 {
10025 unsigned Idx = 1;
10026 FunctionType::param_iterator I = FTy->param_begin(),
10027 E = FTy->param_end();
10028
10029 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010030 if (Idx == NestIdx)
10031 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010032 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010033
10034 if (I == E)
10035 break;
10036
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010037 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010038 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010039
10040 ++Idx, ++I;
10041 } while (1);
10042 }
10043
10044 // Replace the trampoline call with a direct call. Let the generic
10045 // code sort out any function type mismatches.
10046 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +000010047 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010048 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10049 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Patel05988662008-09-25 21:00:45 +000010050 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010051
10052 Instruction *NewCaller;
10053 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010054 NewCaller = InvokeInst::Create(NewCallee,
10055 II->getNormalDest(), II->getUnwindDest(),
10056 NewArgs.begin(), NewArgs.end(),
10057 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010058 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010059 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010060 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010061 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10062 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010063 if (cast<CallInst>(Caller)->isTailCall())
10064 cast<CallInst>(NewCaller)->setTailCall();
10065 cast<CallInst>(NewCaller)->
10066 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010067 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010068 }
10069 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10070 Caller->replaceAllUsesWith(NewCaller);
10071 Caller->eraseFromParent();
10072 RemoveFromWorkList(Caller);
10073 return 0;
10074 }
10075 }
10076
10077 // Replace the trampoline call with a direct call. Since there is no 'nest'
10078 // parameter, there is no need to adjust the argument list. Let the generic
10079 // code sort out any function type mismatches.
10080 Constant *NewCallee =
10081 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10082 CS.setCalledFunction(NewCallee);
10083 return CS.getInstruction();
10084}
10085
Chris Lattner7da52b22006-11-01 04:51:18 +000010086/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10087/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10088/// and a single binop.
10089Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10090 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010091 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010092 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010093 Value *LHSVal = FirstInst->getOperand(0);
10094 Value *RHSVal = FirstInst->getOperand(1);
10095
10096 const Type *LHSType = LHSVal->getType();
10097 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010098
10099 // Scan to see if all operands are the same opcode, all have one use, and all
10100 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010101 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010102 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010103 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010104 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010105 // types or GEP's with different index types.
10106 I->getOperand(0)->getType() != LHSType ||
10107 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010108 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010109
10110 // If they are CmpInst instructions, check their predicates
10111 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10112 if (cast<CmpInst>(I)->getPredicate() !=
10113 cast<CmpInst>(FirstInst)->getPredicate())
10114 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010115
10116 // Keep track of which operand needs a phi node.
10117 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10118 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010119 }
10120
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010121 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010122
Chris Lattner7da52b22006-11-01 04:51:18 +000010123 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010124 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010125 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010126 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010127 NewLHS = PHINode::Create(LHSType,
10128 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010129 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10130 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010131 InsertNewInstBefore(NewLHS, PN);
10132 LHSVal = NewLHS;
10133 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010134
10135 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010136 NewRHS = PHINode::Create(RHSType,
10137 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010138 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10139 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010140 InsertNewInstBefore(NewRHS, PN);
10141 RHSVal = NewRHS;
10142 }
10143
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010144 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010145 if (NewLHS || NewRHS) {
10146 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10147 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10148 if (NewLHS) {
10149 Value *NewInLHS = InInst->getOperand(0);
10150 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10151 }
10152 if (NewRHS) {
10153 Value *NewInRHS = InInst->getOperand(1);
10154 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10155 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010156 }
10157 }
10158
Chris Lattner7da52b22006-11-01 04:51:18 +000010159 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010160 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010161 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10162 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10163 RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010164}
10165
Chris Lattner05f18922008-12-01 02:34:36 +000010166Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10167 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10168
10169 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10170 FirstInst->op_end());
10171
10172 // Scan to see if all operands are the same opcode, all have one use, and all
10173 // kill their operands (i.e. the operands have one use).
10174 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10175 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10176 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10177 GEP->getNumOperands() != FirstInst->getNumOperands())
10178 return 0;
10179
10180 // Compare the operand lists.
10181 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10182 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10183 continue;
10184
10185 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10186 // if one of the PHIs has a constant for the index. The index may be
10187 // substantially cheaper to compute for the constants, so making it a
10188 // variable index could pessimize the path. This also handles the case
10189 // for struct indices, which must always be constant.
10190 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10191 isa<ConstantInt>(GEP->getOperand(op)))
10192 return 0;
10193
10194 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10195 return 0;
10196 FixedOperands[op] = 0; // Needs a PHI.
10197 }
10198 }
10199
10200 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10201 // that is variable.
10202 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10203
10204 bool HasAnyPHIs = false;
10205 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10206 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10207 Value *FirstOp = FirstInst->getOperand(i);
10208 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10209 FirstOp->getName()+".pn");
10210 InsertNewInstBefore(NewPN, PN);
10211
10212 NewPN->reserveOperandSpace(e);
10213 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10214 OperandPhis[i] = NewPN;
10215 FixedOperands[i] = NewPN;
10216 HasAnyPHIs = true;
10217 }
10218
10219
10220 // Add all operands to the new PHIs.
10221 if (HasAnyPHIs) {
10222 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10223 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10224 BasicBlock *InBB = PN.getIncomingBlock(i);
10225
10226 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10227 if (PHINode *OpPhi = OperandPhis[op])
10228 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10229 }
10230 }
10231
10232 Value *Base = FixedOperands[0];
10233 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10234 FixedOperands.end());
10235}
10236
10237
Chris Lattner76c73142006-11-01 07:13:54 +000010238/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10239/// of the block that defines it. This means that it must be obvious the value
10240/// of the load is not changed from the point of the load to the end of the
10241/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010242///
10243/// Finally, it is safe, but not profitable, to sink a load targetting a
10244/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10245/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +000010246static bool isSafeToSinkLoad(LoadInst *L) {
10247 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10248
10249 for (++BBI; BBI != E; ++BBI)
10250 if (BBI->mayWriteToMemory())
10251 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010252
10253 // Check for non-address taken alloca. If not address-taken already, it isn't
10254 // profitable to do this xform.
10255 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10256 bool isAddressTaken = false;
10257 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10258 UI != E; ++UI) {
10259 if (isa<LoadInst>(UI)) continue;
10260 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10261 // If storing TO the alloca, then the address isn't taken.
10262 if (SI->getOperand(1) == AI) continue;
10263 }
10264 isAddressTaken = true;
10265 break;
10266 }
10267
10268 if (!isAddressTaken)
10269 return false;
10270 }
10271
Chris Lattner76c73142006-11-01 07:13:54 +000010272 return true;
10273}
10274
Chris Lattner9fe38862003-06-19 17:00:31 +000010275
Chris Lattnerbac32862004-11-14 19:13:23 +000010276// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10277// operator and they all are only used by the PHI, PHI together their
10278// inputs, and do the operation once, to the result of the PHI.
10279Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10280 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10281
10282 // Scan the instruction, looking for input operations that can be folded away.
10283 // If all input operands to the phi are the same instruction (e.g. a cast from
10284 // the same type or "+42") we can pull the operation through the PHI, reducing
10285 // code size and simplifying code.
10286 Constant *ConstantOp = 0;
10287 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010288 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010289 if (isa<CastInst>(FirstInst)) {
10290 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010291 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010292 // Can fold binop, compare or shift here if the RHS is a constant,
10293 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010294 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010295 if (ConstantOp == 0)
10296 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010297 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10298 isVolatile = LI->isVolatile();
10299 // We can't sink the load if the loaded value could be modified between the
10300 // load and the PHI.
10301 if (LI->getParent() != PN.getIncomingBlock(0) ||
10302 !isSafeToSinkLoad(LI))
10303 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010304
10305 // If the PHI is of volatile loads and the load block has multiple
10306 // successors, sinking it would remove a load of the volatile value from
10307 // the path through the other successor.
10308 if (isVolatile &&
10309 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10310 return 0;
10311
Chris Lattner9c080502006-11-01 07:43:41 +000010312 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010313 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010314 } else {
10315 return 0; // Cannot fold this operation.
10316 }
10317
10318 // Check to see if all arguments are the same operation.
10319 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10320 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10321 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010322 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010323 return 0;
10324 if (CastSrcTy) {
10325 if (I->getOperand(0)->getType() != CastSrcTy)
10326 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010327 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010328 // We can't sink the load if the loaded value could be modified between
10329 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010330 if (LI->isVolatile() != isVolatile ||
10331 LI->getParent() != PN.getIncomingBlock(i) ||
10332 !isSafeToSinkLoad(LI))
10333 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010334
Chris Lattner71042962008-07-08 17:18:32 +000010335 // If the PHI is of volatile loads and the load block has multiple
10336 // successors, sinking it would remove a load of the volatile value from
10337 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010338 if (isVolatile &&
10339 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10340 return 0;
10341
10342
Chris Lattnerbac32862004-11-14 19:13:23 +000010343 } else if (I->getOperand(1) != ConstantOp) {
10344 return 0;
10345 }
10346 }
10347
10348 // Okay, they are all the same operation. Create a new PHI node of the
10349 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010350 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10351 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010352 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010353
10354 Value *InVal = FirstInst->getOperand(0);
10355 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010356
10357 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010358 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10359 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10360 if (NewInVal != InVal)
10361 InVal = 0;
10362 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10363 }
10364
10365 Value *PhiVal;
10366 if (InVal) {
10367 // The new PHI unions all of the same values together. This is really
10368 // common, so we handle it intelligently here for compile-time speed.
10369 PhiVal = InVal;
10370 delete NewPN;
10371 } else {
10372 InsertNewInstBefore(NewPN, PN);
10373 PhiVal = NewPN;
10374 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010375
Chris Lattnerbac32862004-11-14 19:13:23 +000010376 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010377 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010378 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010379 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010380 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010381 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010382 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010383 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010384 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10385
10386 // If this was a volatile load that we are merging, make sure to loop through
10387 // and mark all the input loads as non-volatile. If we don't do this, we will
10388 // insert a new volatile load and the old ones will not be deletable.
10389 if (isVolatile)
10390 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10391 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10392
10393 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010394}
Chris Lattnera1be5662002-05-02 17:06:02 +000010395
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010396/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10397/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010398static bool DeadPHICycle(PHINode *PN,
10399 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010400 if (PN->use_empty()) return true;
10401 if (!PN->hasOneUse()) return false;
10402
10403 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010404 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010405 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010406
10407 // Don't scan crazily complex things.
10408 if (PotentiallyDeadPHIs.size() == 16)
10409 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010410
10411 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10412 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010413
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010414 return false;
10415}
10416
Chris Lattnercf5008a2007-11-06 21:52:06 +000010417/// PHIsEqualValue - Return true if this phi node is always equal to
10418/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10419/// z = some value; x = phi (y, z); y = phi (x, z)
10420static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10421 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10422 // See if we already saw this PHI node.
10423 if (!ValueEqualPHIs.insert(PN))
10424 return true;
10425
10426 // Don't scan crazily complex things.
10427 if (ValueEqualPHIs.size() == 16)
10428 return false;
10429
10430 // Scan the operands to see if they are either phi nodes or are equal to
10431 // the value.
10432 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10433 Value *Op = PN->getIncomingValue(i);
10434 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10435 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10436 return false;
10437 } else if (Op != NonPhiInVal)
10438 return false;
10439 }
10440
10441 return true;
10442}
10443
10444
Chris Lattner473945d2002-05-06 18:06:38 +000010445// PHINode simplification
10446//
Chris Lattner7e708292002-06-25 16:13:24 +000010447Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010448 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010449 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010450
Owen Anderson7e057142006-07-10 22:03:18 +000010451 if (Value *V = PN.hasConstantValue())
10452 return ReplaceInstUsesWith(PN, V);
10453
Owen Anderson7e057142006-07-10 22:03:18 +000010454 // If all PHI operands are the same operation, pull them through the PHI,
10455 // reducing code size.
10456 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010457 isa<Instruction>(PN.getIncomingValue(1)) &&
10458 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10459 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10460 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10461 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010462 PN.getIncomingValue(0)->hasOneUse())
10463 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10464 return Result;
10465
10466 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10467 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10468 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010469 if (PN.hasOneUse()) {
10470 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10471 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010472 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010473 PotentiallyDeadPHIs.insert(&PN);
10474 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10475 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10476 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010477
10478 // If this phi has a single use, and if that use just computes a value for
10479 // the next iteration of a loop, delete the phi. This occurs with unused
10480 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10481 // common case here is good because the only other things that catch this
10482 // are induction variable analysis (sometimes) and ADCE, which is only run
10483 // late.
10484 if (PHIUser->hasOneUse() &&
10485 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10486 PHIUser->use_back() == &PN) {
10487 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10488 }
10489 }
Owen Anderson7e057142006-07-10 22:03:18 +000010490
Chris Lattnercf5008a2007-11-06 21:52:06 +000010491 // We sometimes end up with phi cycles that non-obviously end up being the
10492 // same value, for example:
10493 // z = some value; x = phi (y, z); y = phi (x, z)
10494 // where the phi nodes don't necessarily need to be in the same block. Do a
10495 // quick check to see if the PHI node only contains a single non-phi value, if
10496 // so, scan to see if the phi cycle is actually equal to that value.
10497 {
10498 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10499 // Scan for the first non-phi operand.
10500 while (InValNo != NumOperandVals &&
10501 isa<PHINode>(PN.getIncomingValue(InValNo)))
10502 ++InValNo;
10503
10504 if (InValNo != NumOperandVals) {
10505 Value *NonPhiInVal = PN.getOperand(InValNo);
10506
10507 // Scan the rest of the operands to see if there are any conflicts, if so
10508 // there is no need to recursively scan other phis.
10509 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10510 Value *OpVal = PN.getIncomingValue(InValNo);
10511 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10512 break;
10513 }
10514
10515 // If we scanned over all operands, then we have one unique value plus
10516 // phi values. Scan PHI nodes to see if they all merge in each other or
10517 // the value.
10518 if (InValNo == NumOperandVals) {
10519 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10520 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10521 return ReplaceInstUsesWith(PN, NonPhiInVal);
10522 }
10523 }
10524 }
Chris Lattner60921c92003-12-19 05:58:40 +000010525 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010526}
10527
Reid Spencer17212df2006-12-12 09:18:51 +000010528static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10529 Instruction *InsertPoint,
10530 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010531 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10532 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010533 // We must cast correctly to the pointer type. Ensure that we
10534 // sign extend the integer value if it is smaller as this is
10535 // used for address computation.
10536 Instruction::CastOps opcode =
10537 (VTySize < PtrSize ? Instruction::SExt :
10538 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10539 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010540}
10541
Chris Lattnera1be5662002-05-02 17:06:02 +000010542
Chris Lattner7e708292002-06-25 16:13:24 +000010543Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010544 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010545 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010546 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010547 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010548 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010549
Chris Lattnere87597f2004-10-16 18:11:37 +000010550 if (isa<UndefValue>(GEP.getOperand(0)))
10551 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10552
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010553 bool HasZeroPointerIndex = false;
10554 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10555 HasZeroPointerIndex = C->isNullValue();
10556
10557 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010558 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010559
Chris Lattner28977af2004-04-05 01:30:19 +000010560 // Eliminate unneeded casts for indices.
10561 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010562
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010563 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010564 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10565 i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010566 if (isa<SequentialType>(*GTI)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010567 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010568 if (CI->getOpcode() == Instruction::ZExt ||
10569 CI->getOpcode() == Instruction::SExt) {
10570 const Type *SrcTy = CI->getOperand(0)->getType();
10571 // We can eliminate a cast from i32 to i64 iff the target
10572 // is a 32-bit pointer target.
10573 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10574 MadeChange = true;
Gabor Greif177dd3f2008-06-12 21:37:33 +000010575 *i = CI->getOperand(0);
Chris Lattner28977af2004-04-05 01:30:19 +000010576 }
10577 }
10578 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010579 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman4f833d42008-09-11 23:06:38 +000010580 // to what we need. If narrower, sign-extend it to what we need.
10581 // If the incoming value needs a cast instruction,
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010582 // insert it. This explicit cast can make subsequent optimizations more
10583 // obvious.
Gabor Greif177dd3f2008-06-12 21:37:33 +000010584 Value *Op = *i;
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010585 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010586 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif177dd3f2008-06-12 21:37:33 +000010587 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Chris Lattner4f1134e2004-04-17 18:16:10 +000010588 MadeChange = true;
10589 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010590 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10591 GEP);
Gabor Greif177dd3f2008-06-12 21:37:33 +000010592 *i = Op;
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010593 MadeChange = true;
10594 }
Dan Gohman4f833d42008-09-11 23:06:38 +000010595 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10596 if (Constant *C = dyn_cast<Constant>(Op)) {
10597 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10598 MadeChange = true;
10599 } else {
10600 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10601 GEP);
10602 *i = Op;
10603 MadeChange = true;
10604 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010605 }
Chris Lattner28977af2004-04-05 01:30:19 +000010606 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010607 }
Chris Lattner28977af2004-04-05 01:30:19 +000010608 if (MadeChange) return &GEP;
10609
Chris Lattner90ac28c2002-08-02 19:29:35 +000010610 // Combine Indices - If the source pointer to this getelementptr instruction
10611 // is a getelementptr instruction, combine the indices of the two
10612 // getelementptr instructions into a single instruction.
10613 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010614 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010615 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010616 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010617
10618 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010619 // Note that if our source is a gep chain itself that we wait for that
10620 // chain to be resolved before we perform this transformation. This
10621 // avoids us creating a TON of code in some cases.
10622 //
10623 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10624 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10625 return 0; // Wait until our source is folded to completion.
10626
Chris Lattner72588fc2007-02-15 22:48:32 +000010627 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010628
10629 // Find out whether the last index in the source GEP is a sequential idx.
10630 bool EndsWithSequential = false;
10631 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10632 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010633 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010634
Chris Lattner90ac28c2002-08-02 19:29:35 +000010635 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010636 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010637 // Replace: gep (gep %P, long B), long A, ...
10638 // With: T = long A+B; gep %P, T, ...
10639 //
Chris Lattner620ce142004-05-07 22:09:22 +000010640 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010641 if (SO1 == Constant::getNullValue(SO1->getType())) {
10642 Sum = GO1;
10643 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10644 Sum = SO1;
10645 } else {
10646 // If they aren't the same type, convert both to an integer of the
10647 // target's pointer size.
10648 if (SO1->getType() != GO1->getType()) {
10649 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010650 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010651 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010652 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010653 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010654 unsigned PS = TD->getPointerSizeInBits();
10655 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010656 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010657 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010658
Duncan Sands514ab342007-11-01 20:53:16 +000010659 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010660 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010661 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010662 } else {
10663 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010664 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10665 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010666 }
10667 }
10668 }
Chris Lattner620ce142004-05-07 22:09:22 +000010669 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10670 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10671 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010672 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010673 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010674 }
Chris Lattner28977af2004-04-05 01:30:19 +000010675 }
Chris Lattner620ce142004-05-07 22:09:22 +000010676
10677 // Recycle the GEP we already have if possible.
10678 if (SrcGEPOperands.size() == 2) {
10679 GEP.setOperand(0, SrcGEPOperands[0]);
10680 GEP.setOperand(1, Sum);
10681 return &GEP;
10682 } else {
10683 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10684 SrcGEPOperands.end()-1);
10685 Indices.push_back(Sum);
10686 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10687 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010688 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010689 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010690 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010691 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010692 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10693 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010694 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10695 }
10696
10697 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010698 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10699 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010700
Chris Lattner620ce142004-05-07 22:09:22 +000010701 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010702 // GEP of global variable. If all of the indices for this GEP are
10703 // constants, we can promote this to a constexpr instead of an instruction.
10704
10705 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010706 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010707 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10708 for (; I != E && isa<Constant>(*I); ++I)
10709 Indices.push_back(cast<Constant>(*I));
10710
10711 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010712 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10713 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010714
10715 // Replace all uses of the GEP with the new constexpr...
10716 return ReplaceInstUsesWith(GEP, CE);
10717 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010718 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010719 if (!isa<PointerType>(X->getType())) {
10720 // Not interesting. Source pointer must be a cast from pointer.
10721 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010722 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10723 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010724 //
10725 // This occurs when the program declares an array extern like "int X[];"
10726 //
10727 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10728 const PointerType *XTy = cast<PointerType>(X->getType());
10729 if (const ArrayType *XATy =
10730 dyn_cast<ArrayType>(XTy->getElementType()))
10731 if (const ArrayType *CATy =
10732 dyn_cast<ArrayType>(CPTy->getElementType()))
10733 if (CATy->getElementType() == XATy->getElementType()) {
10734 // At this point, we know that the cast source type is a pointer
10735 // to an array of the same type as the destination pointer
10736 // array. Because the array type is never stepped over (there
10737 // is a leading zero) we can fold the cast into this GEP.
10738 GEP.setOperand(0, X);
10739 return &GEP;
10740 }
10741 } else if (GEP.getNumOperands() == 2) {
10742 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010743 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10744 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010745 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10746 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10747 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010748 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10749 TD->getTypePaddedSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010750 Value *Idx[2];
10751 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10752 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010753 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010754 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010755 // V and GEP are both pointer types --> BitCast
10756 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010757 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010758
10759 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010760 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010761 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010762 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010763
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010764 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010765 uint64_t ArrayEltSize =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +000010766 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010767
10768 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10769 // allow either a mul, shift, or constant here.
10770 Value *NewIdx = 0;
10771 ConstantInt *Scale = 0;
10772 if (ArrayEltSize == 1) {
10773 NewIdx = GEP.getOperand(1);
10774 Scale = ConstantInt::get(NewIdx->getType(), 1);
10775 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010776 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010777 Scale = CI;
10778 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10779 if (Inst->getOpcode() == Instruction::Shl &&
10780 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010781 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10782 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10783 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010784 NewIdx = Inst->getOperand(0);
10785 } else if (Inst->getOpcode() == Instruction::Mul &&
10786 isa<ConstantInt>(Inst->getOperand(1))) {
10787 Scale = cast<ConstantInt>(Inst->getOperand(1));
10788 NewIdx = Inst->getOperand(0);
10789 }
10790 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010791
Chris Lattner7835cdd2005-09-13 18:36:04 +000010792 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010793 // out, perform the transformation. Note, we don't know whether Scale is
10794 // signed or not. We'll use unsigned version of division/modulo
10795 // operation after making sure Scale doesn't have the sign bit set.
10796 if (Scale && Scale->getSExtValue() >= 0LL &&
10797 Scale->getZExtValue() % ArrayEltSize == 0) {
10798 Scale = ConstantInt::get(Scale->getType(),
10799 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010800 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010801 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010802 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010803 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010804 NewIdx = InsertNewInstBefore(Sc, GEP);
10805 }
10806
10807 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010808 Value *Idx[2];
10809 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10810 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010811 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010812 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010813 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10814 // The NewGEP must be pointer typed, so must the old one -> BitCast
10815 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010816 }
10817 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010818 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010819 }
Chris Lattner58407792009-01-09 04:53:57 +000010820
Chris Lattner46cd5a12009-01-09 05:44:56 +000010821 /// See if we can simplify:
10822 /// X = bitcast A to B*
10823 /// Y = gep X, <...constant indices...>
10824 /// into a gep of the original struct. This is important for SROA and alias
10825 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000010826 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000010827 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10828 // Determine how much the GEP moves the pointer. We are guaranteed to get
10829 // a constant back from EmitGEPOffset.
10830 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10831 int64_t Offset = OffsetV->getSExtValue();
10832
10833 // If this GEP instruction doesn't move the pointer, just replace the GEP
10834 // with a bitcast of the real input to the dest type.
10835 if (Offset == 0) {
10836 // If the bitcast is of an allocation, and the allocation will be
10837 // converted to match the type of the cast, don't touch this.
10838 if (isa<AllocationInst>(BCI->getOperand(0))) {
10839 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10840 if (Instruction *I = visitBitCast(*BCI)) {
10841 if (I != BCI) {
10842 I->takeName(BCI);
10843 BCI->getParent()->getInstList().insert(BCI, I);
10844 ReplaceInstUsesWith(*BCI, I);
10845 }
10846 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000010847 }
Chris Lattner58407792009-01-09 04:53:57 +000010848 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010849 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000010850 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000010851
10852 // Otherwise, if the offset is non-zero, we need to find out if there is a
10853 // field at Offset in 'A's type. If so, we can pull the cast through the
10854 // GEP.
10855 SmallVector<Value*, 8> NewIndices;
10856 const Type *InTy =
10857 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10858 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10859 Instruction *NGEP =
10860 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10861 NewIndices.end());
10862 if (NGEP->getType() == GEP.getType()) return NGEP;
10863 InsertNewInstBefore(NGEP, GEP);
10864 NGEP->takeName(&GEP);
10865 return new BitCastInst(NGEP, GEP.getType());
10866 }
Chris Lattner58407792009-01-09 04:53:57 +000010867 }
10868 }
10869
Chris Lattner8a2a3112001-12-14 16:52:21 +000010870 return 0;
10871}
10872
Chris Lattner0864acf2002-11-04 16:18:53 +000010873Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10874 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010875 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010876 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10877 const Type *NewTy =
10878 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010879 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010880
10881 // Create and insert the replacement instruction...
10882 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010883 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010884 else {
10885 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010886 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010887 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010888
10889 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010890
Chris Lattner0864acf2002-11-04 16:18:53 +000010891 // Scan to the end of the allocation instructions, to skip over a block of
10892 // allocas if possible...
10893 //
10894 BasicBlock::iterator It = New;
10895 while (isa<AllocationInst>(*It)) ++It;
10896
10897 // Now that I is pointing to the first non-allocation-inst in the block,
10898 // insert our getelementptr instruction...
10899 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010900 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010901 Value *Idx[2];
10902 Idx[0] = NullIdx;
10903 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010904 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10905 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010906
10907 // Now make everything use the getelementptr instead of the original
10908 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010909 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010910 } else if (isa<UndefValue>(AI.getArraySize())) {
10911 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010912 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010913 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010914
Dan Gohman6893cd72009-01-13 20:18:38 +000010915 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10916 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10917 // Note that we only do this for alloca's, because malloc should allocate and
10918 // return a unique pointer, even for a zero byte allocation.
10919 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10920 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10921
10922 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10923 if (AI.getAlignment() == 0)
10924 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10925 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010926
Chris Lattner0864acf2002-11-04 16:18:53 +000010927 return 0;
10928}
10929
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010930Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10931 Value *Op = FI.getOperand(0);
10932
Chris Lattner17be6352004-10-18 02:59:09 +000010933 // free undef -> unreachable.
10934 if (isa<UndefValue>(Op)) {
10935 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010936 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010937 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010938 return EraseInstFromFunction(FI);
10939 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010940
Chris Lattner6160e852004-02-28 04:57:37 +000010941 // If we have 'free null' delete the instruction. This can happen in stl code
10942 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010943 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010944 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010945
10946 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10947 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10948 FI.setOperand(0, CI->getOperand(0));
10949 return &FI;
10950 }
10951
10952 // Change free (gep X, 0,0,0,0) into free(X)
10953 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10954 if (GEPI->hasAllZeroIndices()) {
10955 AddToWorkList(GEPI);
10956 FI.setOperand(0, GEPI->getOperand(0));
10957 return &FI;
10958 }
10959 }
10960
10961 // Change free(malloc) into nothing, if the malloc has a single use.
10962 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10963 if (MI->hasOneUse()) {
10964 EraseInstFromFunction(FI);
10965 return EraseInstFromFunction(*MI);
10966 }
Chris Lattner6160e852004-02-28 04:57:37 +000010967
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010968 return 0;
10969}
10970
10971
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010972/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010973static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010974 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010975 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010976 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010977
Devang Patel99db6ad2007-10-18 19:52:32 +000010978 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10979 // Instead of loading constant c string, use corresponding integer value
10980 // directly if string length is small enough.
Evan Cheng0ff39b32008-06-30 07:31:25 +000010981 std::string Str;
10982 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010983 unsigned len = Str.length();
10984 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10985 unsigned numBits = Ty->getPrimitiveSizeInBits();
10986 // Replace LI with immediate integer store.
10987 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010988 APInt StrVal(numBits, 0);
10989 APInt SingleChar(numBits, 0);
10990 if (TD->isLittleEndian()) {
10991 for (signed i = len-1; i >= 0; i--) {
10992 SingleChar = (uint64_t) Str[i];
10993 StrVal = (StrVal << 8) | SingleChar;
10994 }
10995 } else {
10996 for (unsigned i = 0; i < len; i++) {
10997 SingleChar = (uint64_t) Str[i];
10998 StrVal = (StrVal << 8) | SingleChar;
10999 }
11000 // Append NULL at the end.
11001 SingleChar = 0;
11002 StrVal = (StrVal << 8) | SingleChar;
11003 }
11004 Value *NL = ConstantInt::get(StrVal);
11005 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000011006 }
11007 }
11008 }
11009
Chris Lattnerb89e0712004-07-13 01:49:43 +000011010 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011011 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011012 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011013
Reid Spencer42230162007-01-22 05:51:25 +000011014 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011015 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011016 // If the source is an array, the code below will not succeed. Check to
11017 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11018 // constants.
11019 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11020 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11021 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011022 Value *Idxs[2];
11023 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11024 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011025 SrcTy = cast<PointerType>(CastOp->getType());
11026 SrcPTy = SrcTy->getElementType();
11027 }
11028
Reid Spencer42230162007-01-22 05:51:25 +000011029 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011030 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011031 // Do not allow turning this into a load of an integer, which is then
11032 // casted to a pointer, this pessimizes pointer analysis a lot.
11033 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000011034 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11035 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011036
Chris Lattnerf9527852005-01-31 04:50:46 +000011037 // Okay, we are casting from one integer or pointer type to another of
11038 // the same size. Instead of casting the pointer before the load, cast
11039 // the result of the loaded value.
11040 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11041 CI->getName(),
11042 LI.isVolatile()),LI);
11043 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011044 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011045 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011046 }
11047 }
11048 return 0;
11049}
11050
Chris Lattnerc10aced2004-09-19 18:43:46 +000011051/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000011052/// from this value cannot trap. If it is not obviously safe to load from the
11053/// specified pointer, we do a quick local scan of the basic block containing
11054/// ScanFrom, to determine if the address is already accessed.
11055static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000011056 // If it is an alloca it is always safe to load from.
11057 if (isa<AllocaInst>(V)) return true;
11058
Duncan Sands46318cd2007-09-19 10:25:38 +000011059 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000011060 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000011061 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000011062 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000011063
11064 // Otherwise, be a little bit agressive by scanning the local block where we
11065 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011066 // from/to. If so, the previous load or store would have already trapped,
11067 // so there is no harm doing an extra load (also, CSE will later eliminate
11068 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000011069 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11070
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011071 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000011072 --BBI;
11073
Chris Lattner2de3fec2008-06-20 05:12:56 +000011074 // If we see a free or a call (which might do a free) the pointer could be
11075 // marked invalid.
11076 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
11077 return false;
11078
Chris Lattner8a375202004-09-19 19:18:10 +000011079 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11080 if (LI->getOperand(0) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011081 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chris Lattner8a375202004-09-19 19:18:10 +000011082 if (SI->getOperand(1) == V) return true;
Chris Lattner2de3fec2008-06-20 05:12:56 +000011083 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011084
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000011085 }
Chris Lattner8a375202004-09-19 19:18:10 +000011086 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000011087}
11088
Chris Lattner833b8a42003-06-26 05:06:25 +000011089Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11090 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011091
Dan Gohman9941f742007-07-20 16:34:21 +000011092 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000011093 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
11094 if (KnownAlign >
11095 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11096 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011097 LI.setAlignment(KnownAlign);
11098
Chris Lattner37366c12005-05-01 04:24:53 +000011099 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011100 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011101 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011102 return Res;
11103
11104 // None of the following transforms are legal for volatile loads.
11105 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011106
Dan Gohman2276a7b2008-10-15 23:19:35 +000011107 // Do really simple store-to-load forwarding and load CSE, to catch cases
11108 // where there are several consequtive memory accesses to the same location,
11109 // separated by a few arithmetic operations.
11110 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011111 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11112 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011113
Christopher Lambb15147e2007-12-29 07:56:53 +000011114 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11115 const Value *GEPI0 = GEPI->getOperand(0);
11116 // TODO: Consider a target hook for valid address spaces for this xform.
11117 if (isa<ConstantPointerNull>(GEPI0) &&
11118 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011119 // Insert a new store to null instruction before the load to indicate
11120 // that this code is not reachable. We do this instead of inserting
11121 // an unreachable instruction directly because we cannot modify the
11122 // CFG.
11123 new StoreInst(UndefValue::get(LI.getType()),
11124 Constant::getNullValue(Op->getType()), &LI);
11125 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11126 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011127 }
Chris Lattner37366c12005-05-01 04:24:53 +000011128
Chris Lattnere87597f2004-10-16 18:11:37 +000011129 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011130 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011131 // TODO: Consider a target hook for valid address spaces for this xform.
11132 if (isa<UndefValue>(C) || (C->isNullValue() &&
11133 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011134 // Insert a new store to null instruction before the load to indicate that
11135 // this code is not reachable. We do this instead of inserting an
11136 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000011137 new StoreInst(UndefValue::get(LI.getType()),
11138 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000011139 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011140 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011141
Chris Lattnere87597f2004-10-16 18:11:37 +000011142 // Instcombine load (constant global) into the value loaded.
11143 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011144 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000011145 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011146
Chris Lattnere87597f2004-10-16 18:11:37 +000011147 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011148 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011149 if (CE->getOpcode() == Instruction::GetElementPtr) {
11150 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000011151 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000011152 if (Constant *V =
11153 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000011154 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011155 if (CE->getOperand(0)->isNullValue()) {
11156 // Insert a new store to null instruction before the load to indicate
11157 // that this code is not reachable. We do this instead of inserting
11158 // an unreachable instruction directly because we cannot modify the
11159 // CFG.
11160 new StoreInst(UndefValue::get(LI.getType()),
11161 Constant::getNullValue(Op->getType()), &LI);
11162 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11163 }
11164
Reid Spencer3da59db2006-11-27 01:05:10 +000011165 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011166 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011167 return Res;
11168 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011169 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011170 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011171
11172 // If this load comes from anywhere in a constant global, and if the global
11173 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011174 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner8d2e8882007-08-11 18:48:48 +000011175 if (GV->isConstant() && GV->hasInitializer()) {
11176 if (GV->getInitializer()->isNullValue())
11177 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11178 else if (isa<UndefValue>(GV->getInitializer()))
11179 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11180 }
11181 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011182
Chris Lattner37366c12005-05-01 04:24:53 +000011183 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011184 // Change select and PHI nodes to select values instead of addresses: this
11185 // helps alias analysis out a lot, allows many others simplifications, and
11186 // exposes redundancy in the code.
11187 //
11188 // Note that we cannot do the transformation unless we know that the
11189 // introduced loads cannot trap! Something like this is valid as long as
11190 // the condition is always false: load (select bool %C, int* null, int* %G),
11191 // but it would not be valid if we transformed it to load from null
11192 // unconditionally.
11193 //
11194 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11195 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011196 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11197 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011198 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011199 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011200 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011201 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011202 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011203 }
11204
Chris Lattner684fe212004-09-23 15:46:00 +000011205 // load (select (cond, null, P)) -> load P
11206 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11207 if (C->isNullValue()) {
11208 LI.setOperand(0, SI->getOperand(2));
11209 return &LI;
11210 }
11211
11212 // load (select (cond, P, null)) -> load P
11213 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11214 if (C->isNullValue()) {
11215 LI.setOperand(0, SI->getOperand(1));
11216 return &LI;
11217 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011218 }
11219 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011220 return 0;
11221}
11222
Reid Spencer55af2b52007-01-19 21:20:31 +000011223/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011224/// when possible. This makes it generally easy to do alias analysis and/or
11225/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011226static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11227 User *CI = cast<User>(SI.getOperand(1));
11228 Value *CastOp = CI->getOperand(0);
11229
11230 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011231 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11232 if (SrcTy == 0) return 0;
11233
11234 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011235
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011236 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11237 return 0;
11238
Chris Lattner3914f722009-01-24 01:00:13 +000011239 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11240 /// to its first element. This allows us to handle things like:
11241 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11242 /// on 32-bit hosts.
11243 SmallVector<Value*, 4> NewGEPIndices;
11244
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011245 // If the source is an array, the code below will not succeed. Check to
11246 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11247 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011248 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11249 // Index through pointer.
11250 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11251 NewGEPIndices.push_back(Zero);
11252
11253 while (1) {
11254 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011255 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011256 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011257 NewGEPIndices.push_back(Zero);
11258 SrcPTy = STy->getElementType(0);
11259 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11260 NewGEPIndices.push_back(Zero);
11261 SrcPTy = ATy->getElementType();
11262 } else {
11263 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011264 }
Chris Lattner3914f722009-01-24 01:00:13 +000011265 }
11266
11267 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11268 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011269
11270 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11271 return 0;
11272
Chris Lattner71759c42009-01-16 20:12:52 +000011273 // If the pointers point into different address spaces or if they point to
11274 // values with different sizes, we can't do the transformation.
11275 if (SrcTy->getAddressSpace() !=
11276 cast<PointerType>(CI->getType())->getAddressSpace() ||
11277 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011278 IC.getTargetData().getTypeSizeInBits(DestPTy))
11279 return 0;
11280
11281 // Okay, we are casting from one integer or pointer type to another of
11282 // the same size. Instead of casting the pointer before
11283 // the store, cast the value to be stored.
11284 Value *NewCast;
11285 Value *SIOp0 = SI.getOperand(0);
11286 Instruction::CastOps opcode = Instruction::BitCast;
11287 const Type* CastSrcTy = SIOp0->getType();
11288 const Type* CastDstTy = SrcPTy;
11289 if (isa<PointerType>(CastDstTy)) {
11290 if (CastSrcTy->isInteger())
11291 opcode = Instruction::IntToPtr;
11292 } else if (isa<IntegerType>(CastDstTy)) {
11293 if (isa<PointerType>(SIOp0->getType()))
11294 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011295 }
Chris Lattner3914f722009-01-24 01:00:13 +000011296
11297 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11298 // emit a GEP to index into its first field.
11299 if (!NewGEPIndices.empty()) {
11300 if (Constant *C = dyn_cast<Constant>(CastOp))
11301 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11302 NewGEPIndices.size());
11303 else
11304 CastOp = IC.InsertNewInstBefore(
11305 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11306 NewGEPIndices.end()), SI);
11307 }
11308
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011309 if (Constant *C = dyn_cast<Constant>(SIOp0))
11310 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11311 else
11312 NewCast = IC.InsertNewInstBefore(
11313 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11314 SI);
11315 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011316}
11317
Chris Lattner4aebaee2008-11-27 08:56:30 +000011318/// equivalentAddressValues - Test if A and B will obviously have the same
11319/// value. This includes recognizing that %t0 and %t1 will have the same
11320/// value in code like this:
11321/// %t0 = getelementptr @a, 0, 3
11322/// store i32 0, i32* %t0
11323/// %t1 = getelementptr @a, 0, 3
11324/// %t2 = load i32* %t1
11325///
11326static bool equivalentAddressValues(Value *A, Value *B) {
11327 // Test if the values are trivially equivalent.
11328 if (A == B) return true;
11329
11330 // Test if the values come form identical arithmetic instructions.
11331 if (isa<BinaryOperator>(A) ||
11332 isa<CastInst>(A) ||
11333 isa<PHINode>(A) ||
11334 isa<GetElementPtrInst>(A))
11335 if (Instruction *BI = dyn_cast<Instruction>(B))
11336 if (cast<Instruction>(A)->isIdenticalTo(BI))
11337 return true;
11338
11339 // Otherwise they may not be equivalent.
11340 return false;
11341}
11342
Chris Lattner2f503e62005-01-31 05:36:43 +000011343Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11344 Value *Val = SI.getOperand(0);
11345 Value *Ptr = SI.getOperand(1);
11346
11347 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011348 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011349 ++NumCombined;
11350 return 0;
11351 }
Chris Lattner836692d2007-01-15 06:51:56 +000011352
11353 // If the RHS is an alloca with a single use, zapify the store, making the
11354 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000011355 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000011356 if (isa<AllocaInst>(Ptr)) {
11357 EraseInstFromFunction(SI);
11358 ++NumCombined;
11359 return 0;
11360 }
11361
11362 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11363 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11364 GEP->getOperand(0)->hasOneUse()) {
11365 EraseInstFromFunction(SI);
11366 ++NumCombined;
11367 return 0;
11368 }
11369 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011370
Dan Gohman9941f742007-07-20 16:34:21 +000011371 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000011372 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11373 if (KnownAlign >
11374 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11375 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000011376 SI.setAlignment(KnownAlign);
11377
Chris Lattner9ca96412006-02-08 03:25:32 +000011378 // Do really simple DSE, to catch cases where there are several consequtive
11379 // stores to the same location, separated by a few arithmetic operations. This
11380 // situation often occurs with bitfield accesses.
11381 BasicBlock::iterator BBI = &SI;
11382 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11383 --ScanInsts) {
11384 --BBI;
11385
11386 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11387 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011388 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11389 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011390 ++NumDeadStore;
11391 ++BBI;
11392 EraseInstFromFunction(*PrevSI);
11393 continue;
11394 }
11395 break;
11396 }
11397
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011398 // If this is a load, we have to stop. However, if the loaded value is from
11399 // the pointer we're loading and is producing the pointer we're storing,
11400 // then *this* store is dead (X = load P; store X -> P).
11401 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011402 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11403 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011404 EraseInstFromFunction(SI);
11405 ++NumCombined;
11406 return 0;
11407 }
11408 // Otherwise, this is a load from some other location. Stores before it
11409 // may not be dead.
11410 break;
11411 }
11412
Chris Lattner9ca96412006-02-08 03:25:32 +000011413 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011414 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011415 break;
11416 }
11417
11418
11419 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011420
11421 // store X, null -> turns into 'unreachable' in SimplifyCFG
11422 if (isa<ConstantPointerNull>(Ptr)) {
11423 if (!isa<UndefValue>(Val)) {
11424 SI.setOperand(0, UndefValue::get(Val->getType()));
11425 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000011426 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011427 ++NumCombined;
11428 }
11429 return 0; // Do not modify these!
11430 }
11431
11432 // store undef, Ptr -> noop
11433 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011434 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011435 ++NumCombined;
11436 return 0;
11437 }
11438
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011439 // If the pointer destination is a cast, see if we can fold the cast into the
11440 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011441 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011442 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11443 return Res;
11444 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011445 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011446 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11447 return Res;
11448
Chris Lattner408902b2005-09-12 23:23:25 +000011449
11450 // If this store is the last instruction in the basic block, and if the block
11451 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000011452 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000011453 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011454 if (BI->isUnconditional())
11455 if (SimplifyStoreAtEndOfBlock(SI))
11456 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011457
Chris Lattner2f503e62005-01-31 05:36:43 +000011458 return 0;
11459}
11460
Chris Lattner3284d1f2007-04-15 00:07:55 +000011461/// SimplifyStoreAtEndOfBlock - Turn things like:
11462/// if () { *P = v1; } else { *P = v2 }
11463/// into a phi node with a store in the successor.
11464///
Chris Lattner31755a02007-04-15 01:02:18 +000011465/// Simplify things like:
11466/// *P = v1; if () { *P = v2; }
11467/// into a phi node with a store in the successor.
11468///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011469bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11470 BasicBlock *StoreBB = SI.getParent();
11471
11472 // Check to see if the successor block has exactly two incoming edges. If
11473 // so, see if the other predecessor contains a store to the same location.
11474 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011475 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011476
11477 // Determine whether Dest has exactly two predecessors and, if so, compute
11478 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011479 pred_iterator PI = pred_begin(DestBB);
11480 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011481 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011482 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011483 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011484 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011485 return false;
11486
11487 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011488 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011489 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011490 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011491 }
Chris Lattner31755a02007-04-15 01:02:18 +000011492 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011493 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011494
11495 // Bail out if all the relevant blocks aren't distinct (this can happen,
11496 // for example, if SI is in an infinite loop)
11497 if (StoreBB == DestBB || OtherBB == DestBB)
11498 return false;
11499
Chris Lattner31755a02007-04-15 01:02:18 +000011500 // Verify that the other block ends in a branch and is not otherwise empty.
11501 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011502 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011503 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011504 return false;
11505
Chris Lattner31755a02007-04-15 01:02:18 +000011506 // If the other block ends in an unconditional branch, check for the 'if then
11507 // else' case. there is an instruction before the branch.
11508 StoreInst *OtherStore = 0;
11509 if (OtherBr->isUnconditional()) {
11510 // If this isn't a store, or isn't a store to the same location, bail out.
11511 --BBI;
11512 OtherStore = dyn_cast<StoreInst>(BBI);
11513 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11514 return false;
11515 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011516 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011517 // destinations is StoreBB, then we have the if/then case.
11518 if (OtherBr->getSuccessor(0) != StoreBB &&
11519 OtherBr->getSuccessor(1) != StoreBB)
11520 return false;
11521
11522 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011523 // if/then triangle. See if there is a store to the same ptr as SI that
11524 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011525 for (;; --BBI) {
11526 // Check to see if we find the matching store.
11527 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11528 if (OtherStore->getOperand(1) != SI.getOperand(1))
11529 return false;
11530 break;
11531 }
Eli Friedman6903a242008-06-13 22:02:12 +000011532 // If we find something that may be using or overwriting the stored
11533 // value, or if we run out of instructions, we can't do the xform.
11534 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011535 BBI == OtherBB->begin())
11536 return false;
11537 }
11538
11539 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011540 // make sure nothing reads or overwrites the stored value in
11541 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011542 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11543 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011544 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011545 return false;
11546 }
11547 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011548
Chris Lattner31755a02007-04-15 01:02:18 +000011549 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011550 Value *MergedVal = OtherStore->getOperand(0);
11551 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011552 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011553 PN->reserveOperandSpace(2);
11554 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011555 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11556 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011557 }
11558
11559 // Advance to a place where it is safe to insert the new store and
11560 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011561 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011562 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11563 OtherStore->isVolatile()), *BBI);
11564
11565 // Nuke the old stores.
11566 EraseInstFromFunction(SI);
11567 EraseInstFromFunction(*OtherStore);
11568 ++NumCombined;
11569 return true;
11570}
11571
Chris Lattner2f503e62005-01-31 05:36:43 +000011572
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011573Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11574 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011575 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011576 BasicBlock *TrueDest;
11577 BasicBlock *FalseDest;
11578 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11579 !isa<Constant>(X)) {
11580 // Swap Destinations and condition...
11581 BI.setCondition(X);
11582 BI.setSuccessor(0, FalseDest);
11583 BI.setSuccessor(1, TrueDest);
11584 return &BI;
11585 }
11586
Reid Spencere4d87aa2006-12-23 06:05:41 +000011587 // Cannonicalize fcmp_one -> fcmp_oeq
11588 FCmpInst::Predicate FPred; Value *Y;
11589 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11590 TrueDest, FalseDest)))
11591 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11592 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11593 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011594 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011595 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11596 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011597 // Swap Destinations and condition...
11598 BI.setCondition(NewSCC);
11599 BI.setSuccessor(0, FalseDest);
11600 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011601 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011602 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011603 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011604 return &BI;
11605 }
11606
11607 // Cannonicalize icmp_ne -> icmp_eq
11608 ICmpInst::Predicate IPred;
11609 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11610 TrueDest, FalseDest)))
11611 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11612 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11613 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11614 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011615 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011616 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11617 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011618 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011619 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011620 BI.setSuccessor(0, FalseDest);
11621 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011622 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011623 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011624 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011625 return &BI;
11626 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011627
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011628 return 0;
11629}
Chris Lattner0864acf2002-11-04 16:18:53 +000011630
Chris Lattner46238a62004-07-03 00:26:11 +000011631Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11632 Value *Cond = SI.getCondition();
11633 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11634 if (I->getOpcode() == Instruction::Add)
11635 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11636 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11637 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011638 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011639 AddRHS));
11640 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011641 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011642 return &SI;
11643 }
11644 }
11645 return 0;
11646}
11647
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011648Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011649 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011650
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011651 if (!EV.hasIndices())
11652 return ReplaceInstUsesWith(EV, Agg);
11653
11654 if (Constant *C = dyn_cast<Constant>(Agg)) {
11655 if (isa<UndefValue>(C))
11656 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11657
11658 if (isa<ConstantAggregateZero>(C))
11659 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11660
11661 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11662 // Extract the element indexed by the first index out of the constant
11663 Value *V = C->getOperand(*EV.idx_begin());
11664 if (EV.getNumIndices() > 1)
11665 // Extract the remaining indices out of the constant indexed by the
11666 // first index
11667 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11668 else
11669 return ReplaceInstUsesWith(EV, V);
11670 }
11671 return 0; // Can't handle other constants
11672 }
11673 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11674 // We're extracting from an insertvalue instruction, compare the indices
11675 const unsigned *exti, *exte, *insi, *inse;
11676 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11677 exte = EV.idx_end(), inse = IV->idx_end();
11678 exti != exte && insi != inse;
11679 ++exti, ++insi) {
11680 if (*insi != *exti)
11681 // The insert and extract both reference distinctly different elements.
11682 // This means the extract is not influenced by the insert, and we can
11683 // replace the aggregate operand of the extract with the aggregate
11684 // operand of the insert. i.e., replace
11685 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11686 // %E = extractvalue { i32, { i32 } } %I, 0
11687 // with
11688 // %E = extractvalue { i32, { i32 } } %A, 0
11689 return ExtractValueInst::Create(IV->getAggregateOperand(),
11690 EV.idx_begin(), EV.idx_end());
11691 }
11692 if (exti == exte && insi == inse)
11693 // Both iterators are at the end: Index lists are identical. Replace
11694 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11695 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11696 // with "i32 42"
11697 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11698 if (exti == exte) {
11699 // The extract list is a prefix of the insert list. i.e. replace
11700 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11701 // %E = extractvalue { i32, { i32 } } %I, 1
11702 // with
11703 // %X = extractvalue { i32, { i32 } } %A, 1
11704 // %E = insertvalue { i32 } %X, i32 42, 0
11705 // by switching the order of the insert and extract (though the
11706 // insertvalue should be left in, since it may have other uses).
11707 Value *NewEV = InsertNewInstBefore(
11708 ExtractValueInst::Create(IV->getAggregateOperand(),
11709 EV.idx_begin(), EV.idx_end()),
11710 EV);
11711 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11712 insi, inse);
11713 }
11714 if (insi == inse)
11715 // The insert list is a prefix of the extract list
11716 // We can simply remove the common indices from the extract and make it
11717 // operate on the inserted value instead of the insertvalue result.
11718 // i.e., replace
11719 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11720 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11721 // with
11722 // %E extractvalue { i32 } { i32 42 }, 0
11723 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11724 exti, exte);
11725 }
11726 // Can't simplify extracts from other values. Note that nested extracts are
11727 // already simplified implicitely by the above (extract ( extract (insert) )
11728 // will be translated into extract ( insert ( extract ) ) first and then just
11729 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011730 return 0;
11731}
11732
Chris Lattner220b0cf2006-03-05 00:22:33 +000011733/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11734/// is to leave as a vector operation.
11735static bool CheapToScalarize(Value *V, bool isConstant) {
11736 if (isa<ConstantAggregateZero>(V))
11737 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011738 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011739 if (isConstant) return true;
11740 // If all elts are the same, we can extract.
11741 Constant *Op0 = C->getOperand(0);
11742 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11743 if (C->getOperand(i) != Op0)
11744 return false;
11745 return true;
11746 }
11747 Instruction *I = dyn_cast<Instruction>(V);
11748 if (!I) return false;
11749
11750 // Insert element gets simplified to the inserted element or is deleted if
11751 // this is constant idx extract element and its a constant idx insertelt.
11752 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11753 isa<ConstantInt>(I->getOperand(2)))
11754 return true;
11755 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11756 return true;
11757 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11758 if (BO->hasOneUse() &&
11759 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11760 CheapToScalarize(BO->getOperand(1), isConstant)))
11761 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011762 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11763 if (CI->hasOneUse() &&
11764 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11765 CheapToScalarize(CI->getOperand(1), isConstant)))
11766 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011767
11768 return false;
11769}
11770
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011771/// Read and decode a shufflevector mask.
11772///
11773/// It turns undef elements into values that are larger than the number of
11774/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011775static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11776 unsigned NElts = SVI->getType()->getNumElements();
11777 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11778 return std::vector<unsigned>(NElts, 0);
11779 if (isa<UndefValue>(SVI->getOperand(2)))
11780 return std::vector<unsigned>(NElts, 2*NElts);
11781
11782 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011783 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000011784 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11785 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000011786 Result.push_back(NElts*2); // undef -> 8
11787 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000011788 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011789 return Result;
11790}
11791
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011792/// FindScalarElement - Given a vector and an element number, see if the scalar
11793/// value is already around as a register, for example if it were inserted then
11794/// extracted from the vector.
11795static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011796 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11797 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011798 unsigned Width = PTy->getNumElements();
11799 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011800 return UndefValue::get(PTy->getElementType());
11801
11802 if (isa<UndefValue>(V))
11803 return UndefValue::get(PTy->getElementType());
11804 else if (isa<ConstantAggregateZero>(V))
11805 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011806 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011807 return CP->getOperand(EltNo);
11808 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11809 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011810 if (!isa<ConstantInt>(III->getOperand(2)))
11811 return 0;
11812 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011813
11814 // If this is an insert to the element we are looking for, return the
11815 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011816 if (EltNo == IIElt)
11817 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011818
11819 // Otherwise, the insertelement doesn't modify the value, recurse on its
11820 // vector input.
11821 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011822 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000011823 unsigned LHSWidth =
11824 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000011825 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000011826 if (InEl < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011827 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011828 else if (InEl < LHSWidth*2)
11829 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattner863bcff2006-05-25 23:48:38 +000011830 else
11831 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011832 }
11833
11834 // Otherwise, we don't know.
11835 return 0;
11836}
11837
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011838Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000011839 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011840 if (isa<UndefValue>(EI.getOperand(0)))
11841 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11842
Dan Gohman07a96762007-07-16 14:29:03 +000011843 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011844 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11845 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11846
Reid Spencer9d6565a2007-02-15 02:26:10 +000011847 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000011848 // If vector val is constant with all elements the same, replace EI with
11849 // that element. When the elements are not identical, we cannot replace yet
11850 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000011851 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011852 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011853 if (C->getOperand(i) != op0) {
11854 op0 = 0;
11855 break;
11856 }
11857 if (op0)
11858 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011859 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011860
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011861 // If extracting a specified index from the vector, see if we can recursively
11862 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011863 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011864 unsigned IndexVal = IdxC->getZExtValue();
11865 unsigned VectorWidth =
11866 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11867
11868 // If this is extracting an invalid index, turn this into undef, to avoid
11869 // crashing the code below.
11870 if (IndexVal >= VectorWidth)
11871 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11872
Chris Lattner867b99f2006-10-05 06:55:50 +000011873 // This instruction only demands the single element from the input vector.
11874 // If the input vector has a single use, simplify it based on this use
11875 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011876 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000011877 APInt UndefElts(VectorWidth, 0);
11878 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000011879 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000011880 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011881 EI.setOperand(0, V);
11882 return &EI;
11883 }
11884 }
11885
Reid Spencerb83eb642006-10-20 07:07:24 +000011886 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011887 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011888
11889 // If the this extractelement is directly using a bitcast from a vector of
11890 // the same number of elements, see if we can find the source element from
11891 // it. In this case, we will end up needing to bitcast the scalars.
11892 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11893 if (const VectorType *VT =
11894 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11895 if (VT->getNumElements() == VectorWidth)
11896 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11897 return new BitCastInst(Elt, EI.getType());
11898 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011899 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011900
Chris Lattner73fa49d2006-05-25 22:53:38 +000011901 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011902 if (I->hasOneUse()) {
11903 // Push extractelement into predecessor operation if legal and
11904 // profitable to do so
11905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011906 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11907 if (CheapToScalarize(BO, isConstantElt)) {
11908 ExtractElementInst *newEI0 =
11909 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11910 EI.getName()+".lhs");
11911 ExtractElementInst *newEI1 =
11912 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11913 EI.getName()+".rhs");
11914 InsertNewInstBefore(newEI0, EI);
11915 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011916 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011917 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011918 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011919 unsigned AS =
11920 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011921 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11922 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011923 GetElementPtrInst *GEP =
11924 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011925 InsertNewInstBefore(GEP, EI);
11926 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011927 }
11928 }
11929 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11930 // Extracting the inserted element?
11931 if (IE->getOperand(2) == EI.getOperand(1))
11932 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11933 // If the inserted and extracted elements are constants, they must not
11934 // be the same value, extract from the pre-inserted value instead.
11935 if (isa<Constant>(IE->getOperand(2)) &&
11936 isa<Constant>(EI.getOperand(1))) {
11937 AddUsesToWorkList(EI);
11938 EI.setOperand(0, IE->getOperand(0));
11939 return &EI;
11940 }
11941 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11942 // If this is extracting an element from a shufflevector, figure out where
11943 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011944 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11945 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011946 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000011947 unsigned LHSWidth =
11948 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11949
11950 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000011951 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000011952 else if (SrcIdx < LHSWidth*2) {
11953 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000011954 Src = SVI->getOperand(1);
11955 } else {
11956 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011957 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011958 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011959 }
11960 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011961 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011962 return 0;
11963}
11964
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011965/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11966/// elements from either LHS or RHS, return the shuffle mask and true.
11967/// Otherwise, return false.
11968static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11969 std::vector<Constant*> &Mask) {
11970 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11971 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011972 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011973
11974 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011975 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011976 return true;
11977 } else if (V == LHS) {
11978 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011979 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011980 return true;
11981 } else if (V == RHS) {
11982 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011983 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011984 return true;
11985 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11986 // If this is an insert of an extract from some other vector, include it.
11987 Value *VecOp = IEI->getOperand(0);
11988 Value *ScalarOp = IEI->getOperand(1);
11989 Value *IdxOp = IEI->getOperand(2);
11990
Chris Lattnerd929f062006-04-27 21:14:21 +000011991 if (!isa<ConstantInt>(IdxOp))
11992 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011993 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011994
11995 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11996 // Okay, we can handle this if the vector we are insertinting into is
11997 // transitively ok.
11998 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11999 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000012000 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000012001 return true;
12002 }
12003 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12004 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012005 EI->getOperand(0)->getType() == V->getType()) {
12006 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012007 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012008
12009 // This must be extracting from either LHS or RHS.
12010 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12011 // Okay, we can handle this if the vector we are insertinting into is
12012 // transitively ok.
12013 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12014 // If so, update the mask to reflect the inserted value.
12015 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012016 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012017 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012018 } else {
12019 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012020 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012021 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012022
12023 }
12024 return true;
12025 }
12026 }
12027 }
12028 }
12029 }
12030 // TODO: Handle shufflevector here!
12031
12032 return false;
12033}
12034
12035/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12036/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12037/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012038static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012039 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012040 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012041 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012042 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012043 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012044
12045 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012046 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012047 return V;
12048 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012049 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012050 return V;
12051 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12052 // If this is an insert of an extract from some other vector, include it.
12053 Value *VecOp = IEI->getOperand(0);
12054 Value *ScalarOp = IEI->getOperand(1);
12055 Value *IdxOp = IEI->getOperand(2);
12056
12057 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12058 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12059 EI->getOperand(0)->getType() == V->getType()) {
12060 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012061 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12062 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012063
12064 // Either the extracted from or inserted into vector must be RHSVec,
12065 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012066 if (EI->getOperand(0) == RHS || RHS == 0) {
12067 RHS = EI->getOperand(0);
12068 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012069 Mask[InsertedIdx % NumElts] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000012070 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012071 return V;
12072 }
12073
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012074 if (VecOp == RHS) {
12075 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000012076 // Everything but the extracted element is replaced with the RHS.
12077 for (unsigned i = 0; i != NumElts; ++i) {
12078 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012079 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012080 }
12081 return V;
12082 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012083
12084 // If this insertelement is a chain that comes from exactly these two
12085 // vectors, return the vector and the effective shuffle.
12086 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12087 return EI->getOperand(0);
12088
Chris Lattnerefb47352006-04-15 01:39:45 +000012089 }
12090 }
12091 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012092 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012093
12094 // Otherwise, can't do anything fancy. Return an identity vector.
12095 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012096 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012097 return V;
12098}
12099
12100Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12101 Value *VecOp = IE.getOperand(0);
12102 Value *ScalarOp = IE.getOperand(1);
12103 Value *IdxOp = IE.getOperand(2);
12104
Chris Lattner599ded12007-04-09 01:11:16 +000012105 // Inserting an undef or into an undefined place, remove this.
12106 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12107 ReplaceInstUsesWith(IE, VecOp);
12108
Chris Lattnerefb47352006-04-15 01:39:45 +000012109 // If the inserted element was extracted from some other vector, and if the
12110 // indexes are constant, try to turn this into a shufflevector operation.
12111 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12112 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12113 EI->getOperand(0)->getType() == IE.getType()) {
12114 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012115 unsigned ExtractedIdx =
12116 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012117 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012118
12119 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12120 return ReplaceInstUsesWith(IE, VecOp);
12121
12122 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12123 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12124
12125 // If we are extracting a value from a vector, then inserting it right
12126 // back into the same place, just use the input vector.
12127 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12128 return ReplaceInstUsesWith(IE, VecOp);
12129
12130 // We could theoretically do this for ANY input. However, doing so could
12131 // turn chains of insertelement instructions into a chain of shufflevector
12132 // instructions, and right now we do not merge shufflevectors. As such,
12133 // only do this in a situation where it is clear that there is benefit.
12134 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12135 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12136 // the values of VecOp, except then one read from EIOp0.
12137 // Build a new shuffle mask.
12138 std::vector<Constant*> Mask;
12139 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000012140 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000012141 else {
12142 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000012143 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000012144 NumVectorElts));
12145 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000012146 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012147 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000012148 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012149 }
12150
12151 // If this insertelement isn't used by some other insertelement, turn it
12152 // (and any insertelements it points to), into one big shuffle.
12153 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12154 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012155 Value *RHS = 0;
12156 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12157 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12158 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000012159 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012160 }
12161 }
12162 }
12163
12164 return 0;
12165}
12166
12167
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012168Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12169 Value *LHS = SVI.getOperand(0);
12170 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012171 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012172
12173 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012174
Chris Lattner867b99f2006-10-05 06:55:50 +000012175 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012176 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012177 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012178
Dan Gohman488fbfc2008-09-09 18:11:14 +000012179 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012180
12181 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12182 return 0;
12183
Evan Cheng388df622009-02-03 10:05:09 +000012184 APInt UndefElts(VWidth, 0);
12185 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12186 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012187 LHS = SVI.getOperand(0);
12188 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012189 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012190 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012191
Chris Lattner863bcff2006-05-25 23:48:38 +000012192 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12193 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12194 if (LHS == RHS || isa<UndefValue>(LHS)) {
12195 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012196 // shuffle(undef,undef,mask) -> undef.
12197 return ReplaceInstUsesWith(SVI, LHS);
12198 }
12199
Chris Lattner863bcff2006-05-25 23:48:38 +000012200 // Remap any references to RHS to use LHS.
12201 std::vector<Constant*> Elts;
12202 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012203 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000012204 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012205 else {
12206 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012207 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012208 Mask[i] = 2*e; // Turn into undef.
Dan Gohman4ce96272008-08-06 18:17:32 +000012209 Elts.push_back(UndefValue::get(Type::Int32Ty));
12210 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012211 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohman4ce96272008-08-06 18:17:32 +000012212 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12213 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012214 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012215 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012216 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012217 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000012218 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012219 LHS = SVI.getOperand(0);
12220 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012221 MadeChange = true;
12222 }
12223
Chris Lattner7b2e27922006-05-26 00:29:06 +000012224 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012225 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012226
Chris Lattner863bcff2006-05-25 23:48:38 +000012227 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12228 if (Mask[i] >= e*2) continue; // Ignore undef values.
12229 // Is this an identity shuffle of the LHS value?
12230 isLHSID &= (Mask[i] == i);
12231
12232 // Is this an identity shuffle of the RHS value?
12233 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012234 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012235
Chris Lattner863bcff2006-05-25 23:48:38 +000012236 // Eliminate identity shuffles.
12237 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12238 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012239
Chris Lattner7b2e27922006-05-26 00:29:06 +000012240 // If the LHS is a shufflevector itself, see if we can combine it with this
12241 // one without producing an unusual shuffle. Here we are really conservative:
12242 // we are absolutely afraid of producing a shuffle mask not in the input
12243 // program, because the code gen may not be smart enough to turn a merged
12244 // shuffle into two specific shuffles: it may produce worse code. As such,
12245 // we only merge two shuffles if the result is one of the two input shuffle
12246 // masks. In this case, merging the shuffles just removes one instruction,
12247 // which we know is safe. This is good for things like turning:
12248 // (splat(splat)) -> splat.
12249 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12250 if (isa<UndefValue>(RHS)) {
12251 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12252
12253 std::vector<unsigned> NewMask;
12254 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12255 if (Mask[i] >= 2*e)
12256 NewMask.push_back(2*e);
12257 else
12258 NewMask.push_back(LHSMask[Mask[i]]);
12259
12260 // If the result mask is equal to the src shuffle or this shuffle mask, do
12261 // the replacement.
12262 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012263 unsigned LHSInNElts =
12264 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012265 std::vector<Constant*> Elts;
12266 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012267 if (NewMask[i] >= LHSInNElts*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012268 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012269 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000012270 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012271 }
12272 }
12273 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12274 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000012275 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012276 }
12277 }
12278 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012279
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012280 return MadeChange ? &SVI : 0;
12281}
12282
12283
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012284
Chris Lattnerea1c4542004-12-08 23:43:58 +000012285
12286/// TryToSinkInstruction - Try to move the specified instruction from its
12287/// current block into the beginning of DestBlock, which can only happen if it's
12288/// safe to move the instruction past all of the instructions between it and the
12289/// end of its block.
12290static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12291 assert(I->hasOneUse() && "Invariants didn't hold!");
12292
Chris Lattner108e9022005-10-27 17:13:11 +000012293 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012294 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12295 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012296
Chris Lattnerea1c4542004-12-08 23:43:58 +000012297 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012298 if (isa<AllocaInst>(I) && I->getParent() ==
12299 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012300 return false;
12301
Chris Lattner96a52a62004-12-09 07:14:34 +000012302 // We can only sink load instructions if there is nothing between the load and
12303 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012304 if (I->mayReadFromMemory()) {
12305 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012306 Scan != E; ++Scan)
12307 if (Scan->mayWriteToMemory())
12308 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012309 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012310
Dan Gohman02dea8b2008-05-23 21:05:58 +000012311 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012312
Chris Lattner4bc5f802005-08-08 19:11:57 +000012313 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012314 ++NumSunkInst;
12315 return true;
12316}
12317
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012318
12319/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12320/// all reachable code to the worklist.
12321///
12322/// This has a couple of tricks to make the code faster and more powerful. In
12323/// particular, we constant fold and DCE instructions as we go, to avoid adding
12324/// them to the worklist (this significantly speeds up instcombine on code where
12325/// many instructions are dead or constant). Additionally, if we find a branch
12326/// whose condition is a known constant, we only visit the reachable successors.
12327///
12328static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012329 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012330 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012331 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012332 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012333 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012334
Chris Lattner2c7718a2007-03-23 19:17:18 +000012335 while (!Worklist.empty()) {
12336 BB = Worklist.back();
12337 Worklist.pop_back();
12338
12339 // We have now visited this block! If we've already been here, ignore it.
12340 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012341
12342 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012343 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12344 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012345
Chris Lattner2c7718a2007-03-23 19:17:18 +000012346 // DCE instruction if trivially dead.
12347 if (isInstructionTriviallyDead(Inst)) {
12348 ++NumDeadInst;
12349 DOUT << "IC: DCE: " << *Inst;
12350 Inst->eraseFromParent();
12351 continue;
12352 }
12353
12354 // ConstantProp instruction if trivially constant.
12355 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12356 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12357 Inst->replaceAllUsesWith(C);
12358 ++NumConstProp;
12359 Inst->eraseFromParent();
12360 continue;
12361 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012362
Devang Patel7fe1dec2008-11-19 18:56:50 +000012363 // If there are two consecutive llvm.dbg.stoppoint calls then
12364 // it is likely that the optimizer deleted code in between these
12365 // two intrinsics.
12366 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12367 if (DBI_Next) {
12368 if (DBI_Prev
12369 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12370 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12371 IC.RemoveFromWorkList(DBI_Prev);
12372 DBI_Prev->eraseFromParent();
12373 }
12374 DBI_Prev = DBI_Next;
12375 }
12376
Chris Lattner2c7718a2007-03-23 19:17:18 +000012377 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012378 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012379
12380 // Recursively visit successors. If this is a branch or switch on a
12381 // constant, only visit the reachable successor.
12382 TerminatorInst *TI = BB->getTerminator();
12383 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12384 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12385 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012386 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012387 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012388 continue;
12389 }
12390 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12391 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12392 // See if this is an explicit destination.
12393 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12394 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012395 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012396 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012397 continue;
12398 }
12399
12400 // Otherwise it is the default destination.
12401 Worklist.push_back(SI->getSuccessor(0));
12402 continue;
12403 }
12404 }
12405
12406 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12407 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012408 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012409}
12410
Chris Lattnerec9c3582007-03-03 02:04:50 +000012411bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012412 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000012413 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012414
12415 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12416 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012417
Chris Lattnerb3d59702005-07-07 20:40:38 +000012418 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012419 // Do a depth-first traversal of the function, populate the worklist with
12420 // the reachable instructions. Ignore blocks that are not reachable. Keep
12421 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012422 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012423 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012424
Chris Lattnerb3d59702005-07-07 20:40:38 +000012425 // Do a quick scan over the function. If we find any blocks that are
12426 // unreachable, remove any instructions inside of them. This prevents
12427 // the instcombine code from having to deal with some bad special cases.
12428 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12429 if (!Visited.count(BB)) {
12430 Instruction *Term = BB->getTerminator();
12431 while (Term != BB->begin()) { // Remove instrs bottom-up
12432 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012433
Bill Wendlingb7427032006-11-26 09:46:52 +000012434 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012435 ++NumDeadInst;
12436
12437 if (!I->use_empty())
12438 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12439 I->eraseFromParent();
Chris Lattner1e19d602009-01-31 07:04:22 +000012440 Changed = true;
Chris Lattnerb3d59702005-07-07 20:40:38 +000012441 }
12442 }
12443 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012444
Chris Lattnerdbab3862007-03-02 21:28:56 +000012445 while (!Worklist.empty()) {
12446 Instruction *I = RemoveOneFromWorkList();
12447 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012448
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012449 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012450 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012451 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000012452 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012453 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000012454 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012455
Bill Wendlingb7427032006-11-26 09:46:52 +000012456 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012457
12458 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012459 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012460 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012461 continue;
12462 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012463
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012464 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000012465 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012466 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000012467
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012468 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000012469 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000012470 ReplaceInstUsesWith(*I, C);
12471
Chris Lattner62b14df2002-09-02 04:59:56 +000012472 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012473 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012474 RemoveFromWorkList(I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012475 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012476 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012477 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012478
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012479 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12480 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012481 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12482 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012483 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012484 if (NewC != CE) {
12485 i->set(NewC);
12486 Changed = true;
12487 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012488 }
12489
Chris Lattnerea1c4542004-12-08 23:43:58 +000012490 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012491 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012492 BasicBlock *BB = I->getParent();
12493 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12494 if (UserParent != BB) {
12495 bool UserIsSuccessor = false;
12496 // See if the user is one of our successors.
12497 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12498 if (*SI == UserParent) {
12499 UserIsSuccessor = true;
12500 break;
12501 }
12502
12503 // If the user is one of our immediate successors, and if that successor
12504 // only has us as a predecessors (we'd have to split the critical edge
12505 // otherwise), we can keep going.
12506 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12507 next(pred_begin(UserParent)) == pred_end(UserParent))
12508 // Okay, the CFG is simple enough, try to sink this instruction.
12509 Changed |= TryToSinkInstruction(I, UserParent);
12510 }
12511 }
12512
Chris Lattner8a2a3112001-12-14 16:52:21 +000012513 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000012514#ifndef NDEBUG
12515 std::string OrigI;
12516#endif
12517 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000012518 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012519 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012520 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012521 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000012522 DOUT << "IC: Old = " << *I
12523 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000012524
Chris Lattnerf523d062004-06-09 05:08:07 +000012525 // Everything uses the new instruction now.
12526 I->replaceAllUsesWith(Result);
12527
12528 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012529 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000012530 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012531
Chris Lattner6934a042007-02-11 01:23:03 +000012532 // Move the name to the new instruction first.
12533 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012534
12535 // Insert the new instruction into the basic block...
12536 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012537 BasicBlock::iterator InsertPos = I;
12538
12539 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12540 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12541 ++InsertPos;
12542
12543 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012544
Chris Lattner00d51312004-05-01 23:27:23 +000012545 // Make sure that we reprocess all operands now that we reduced their
12546 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012547 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000012548
Chris Lattnerf523d062004-06-09 05:08:07 +000012549 // Instructions can end up on the worklist more than once. Make sure
12550 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012551 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012552
12553 // Erase the old instruction.
12554 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012555 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012556#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012557 DOUT << "IC: Mod = " << OrigI
12558 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012559#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012560
Chris Lattner90ac28c2002-08-02 19:29:35 +000012561 // If the instruction was modified, it's possible that it is now dead.
12562 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012563 if (isInstructionTriviallyDead(I)) {
12564 // Make sure we process all operands now that we are reducing their
12565 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012566 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012567
Chris Lattner00d51312004-05-01 23:27:23 +000012568 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012569 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012570 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012571 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012572 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012573 AddToWorkList(I);
12574 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012575 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012576 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012577 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012578 }
12579 }
12580
Chris Lattnerec9c3582007-03-03 02:04:50 +000012581 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012582
12583 // Do an explicit clear, this shrinks the map if needed.
12584 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012585 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012586}
12587
Chris Lattnerec9c3582007-03-03 02:04:50 +000012588
12589bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012590 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12591
Chris Lattnerec9c3582007-03-03 02:04:50 +000012592 bool EverMadeChange = false;
12593
12594 // Iterate while there is work to do.
12595 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012596 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012597 EverMadeChange = true;
12598 return EverMadeChange;
12599}
12600
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012601FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012602 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012603}