blob: 82d9fa87432018780ade7818c8b029e1fc13e028 [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 Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108
Chris Lattnerdbab3862007-03-02 21:28:56 +0000109
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000118 }
119
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000147
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000148 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152
Chris Lattner97e52e42002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 }
158
Chris Lattner28977af2004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000167 //
Chris Lattner7e708292002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194 Instruction *LHS,
195 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000198
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000202 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000205 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000209 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000210 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000216 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000217 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000220 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000225 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000226 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000227 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000228 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000229 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000230 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000231 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000234
235 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000236 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000237
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000239 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000241 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
Chris Lattner9fe38862003-06-19 17:00:31 +0000244
Chris Lattner28977af2004-04-05 01:30:19 +0000245 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000246 // InsertNewInstBefore - insert an instruction New before instruction Old
247 // in the program. Add the new instruction to the worklist.
248 //
Chris Lattner955f3312004-09-28 21:48:02 +0000249 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000250 assert(New && New->getParent() == 0 &&
251 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000252 BasicBlock *BB = Old.getParent();
253 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000254 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000255 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000256 }
257
Chris Lattner0c967662004-09-24 15:21:34 +0000258 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
259 /// This also adds the cast to the worklist. Finally, this returns the
260 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000261 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
262 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000263 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000264
Chris Lattnere2ed0572006-04-06 19:19:17 +0000265 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000266 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000267
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000268 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000269 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000270 return C;
271 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000272
273 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
274 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
275 }
276
Chris Lattner0c967662004-09-24 15:21:34 +0000277
Chris Lattner8b170942002-08-09 23:47:40 +0000278 // ReplaceInstUsesWith - This method is to be used when an instruction is
279 // found to be dead, replacable with another preexisting expression. Here
280 // we add all uses of I to the worklist, replace all uses of I with the new
281 // value, then return I, so that the inst combiner will know that I was
282 // modified.
283 //
284 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000285 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000286 if (&I != V) {
287 I.replaceAllUsesWith(V);
288 return &I;
289 } else {
290 // If we are replacing the instruction with itself, this must be in a
291 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000292 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000293 return &I;
294 }
Chris Lattner8b170942002-08-09 23:47:40 +0000295 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000296
Chris Lattner6dce1a72006-02-07 06:56:34 +0000297 // UpdateValueUsesWith - This method is to be used when an value is
298 // found to be replacable with another preexisting expression or was
299 // updated. Here we add all uses of I to the worklist, replace all uses of
300 // I with the new value (unless the instruction was just updated), then
301 // return true, so that the inst combiner will know that I was modified.
302 //
303 bool UpdateValueUsesWith(Value *Old, Value *New) {
304 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
305 if (Old != New)
306 Old->replaceAllUsesWith(New);
307 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000308 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000309 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000310 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000311 return true;
312 }
313
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000314 // EraseInstFromFunction - When dealing with an instruction that has side
315 // effects or produces a void value, we can't rely on DCE to delete the
316 // instruction. Instead, visit methods should return the value returned by
317 // this function.
318 Instruction *EraseInstFromFunction(Instruction &I) {
319 assert(I.use_empty() && "Cannot erase instruction that is used!");
320 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000321 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000322 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000323 return 0; // Don't do anything with FI
324 }
325
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000326 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000327 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
328 /// InsertBefore instruction. This is specialized a bit to avoid inserting
329 /// casts that are known to not do anything...
330 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000331 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
332 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000333 Instruction *InsertBefore);
334
Reid Spencere4d87aa2006-12-23 06:05:41 +0000335 /// SimplifyCommutative - This performs a few simplifications for
336 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000337 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000338
Reid Spencere4d87aa2006-12-23 06:05:41 +0000339 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
340 /// most-complex to least-complex order.
341 bool SimplifyCompare(CmpInst &I);
342
Reid Spencer2ec619a2007-03-23 21:24:59 +0000343 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
344 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000345 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
346 APInt& KnownZero, APInt& KnownOne,
347 unsigned Depth = 0);
348
Chris Lattner867b99f2006-10-05 06:55:50 +0000349 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
350 uint64_t &UndefElts, unsigned Depth = 0);
351
Chris Lattner4e998b22004-09-29 05:07:12 +0000352 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
353 // PHI node as operand #0, see if we can fold the instruction into the PHI
354 // (which is only possible if all operands to the PHI are constants).
355 Instruction *FoldOpIntoPhi(Instruction &I);
356
Chris Lattnerbac32862004-11-14 19:13:23 +0000357 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
358 // operator and they all are only used by the PHI, PHI together their
359 // inputs, and do the operation once, to the result of the PHI.
360 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000361 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
362
363
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000364 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
365 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000366
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000367 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000368 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000369 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000370 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000371 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000372 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000373 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000374 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000375 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000376
Chris Lattnerafe91a52006-06-15 19:07:26 +0000377
Reid Spencerc55b2432006-12-13 18:21:21 +0000378 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000379
380 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Dan Gohman45b4e482008-05-19 22:14:15 +0000381 APInt& KnownOne, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000382 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
Dan Gohman45b4e482008-05-19 22:14:15 +0000383 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000384 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
385 unsigned CastOpc,
386 int &NumCastsRemoved);
387 unsigned GetOrEnforceKnownAlignment(Value *V,
388 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000389 };
390}
391
Dan Gohman844731a2008-05-13 00:00:25 +0000392char InstCombiner::ID = 0;
393static RegisterPass<InstCombiner>
394X("instcombine", "Combine redundant instructions");
395
Chris Lattner4f98c562003-03-10 21:43:22 +0000396// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000397// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000398static unsigned getComplexity(Value *V) {
399 if (isa<Instruction>(V)) {
400 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000401 return 3;
402 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000403 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000404 if (isa<Argument>(V)) return 3;
405 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000406}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000407
Chris Lattnerc8802d22003-03-11 00:12:48 +0000408// isOnlyUse - Return true if this instruction will be deleted if we stop using
409// it.
410static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000411 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000412}
413
Chris Lattner4cb170c2004-02-23 06:38:22 +0000414// getPromotedType - Return the specified type promoted as it would be to pass
415// though a va_arg area...
416static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000417 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
418 if (ITy->getBitWidth() < 32)
419 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000420 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000421 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000422}
423
Reid Spencer3da59db2006-11-27 01:05:10 +0000424/// getBitCastOperand - If the specified operand is a CastInst or a constant
425/// expression bitcast, return the operand value, otherwise return null.
426static Value *getBitCastOperand(Value *V) {
427 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000428 return I->getOperand(0);
429 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000430 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000431 return CE->getOperand(0);
432 return 0;
433}
434
Reid Spencer3da59db2006-11-27 01:05:10 +0000435/// This function is a wrapper around CastInst::isEliminableCastPair. It
436/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000437static Instruction::CastOps
438isEliminableCastPair(
439 const CastInst *CI, ///< The first cast instruction
440 unsigned opcode, ///< The opcode of the second cast instruction
441 const Type *DstTy, ///< The target type for the second cast instruction
442 TargetData *TD ///< The target data for pointer size
443) {
444
445 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
446 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000447
Reid Spencer3da59db2006-11-27 01:05:10 +0000448 // Get the opcodes of the two Cast instructions
449 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
450 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000451
Reid Spencer3da59db2006-11-27 01:05:10 +0000452 return Instruction::CastOps(
453 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
454 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000455}
456
457/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
458/// in any code being generated. It does not require codegen if V is simple
459/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000460static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
461 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000462 if (V->getType() == Ty || isa<Constant>(V)) return false;
463
Chris Lattner01575b72006-05-25 23:24:33 +0000464 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000465 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000466 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000467 return false;
468 return true;
469}
470
471/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
472/// InsertBefore instruction. This is specialized a bit to avoid inserting
473/// casts that are known to not do anything...
474///
Reid Spencer17212df2006-12-12 09:18:51 +0000475Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
476 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000477 Instruction *InsertBefore) {
478 if (V->getType() == DestTy) return V;
479 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000480 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000481
Reid Spencer17212df2006-12-12 09:18:51 +0000482 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000483}
484
Chris Lattner4f98c562003-03-10 21:43:22 +0000485// SimplifyCommutative - This performs a few simplifications for commutative
486// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000487//
Chris Lattner4f98c562003-03-10 21:43:22 +0000488// 1. Order operands such that they are listed from right (least complex) to
489// left (most complex). This puts constants before unary operators before
490// binary operators.
491//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000492// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
493// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000494//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000495bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000496 bool Changed = false;
497 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
498 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000499
Chris Lattner4f98c562003-03-10 21:43:22 +0000500 if (!I.isAssociative()) return Changed;
501 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000502 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
503 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
504 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000505 Constant *Folded = ConstantExpr::get(I.getOpcode(),
506 cast<Constant>(I.getOperand(1)),
507 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508 I.setOperand(0, Op->getOperand(0));
509 I.setOperand(1, Folded);
510 return true;
511 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
512 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
513 isOnlyUse(Op) && isOnlyUse(Op1)) {
514 Constant *C1 = cast<Constant>(Op->getOperand(1));
515 Constant *C2 = cast<Constant>(Op1->getOperand(1));
516
517 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000518 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000519 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 Op1->getOperand(0),
521 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000522 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000523 I.setOperand(0, New);
524 I.setOperand(1, Folded);
525 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000526 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000527 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000528 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000529}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000530
Reid Spencere4d87aa2006-12-23 06:05:41 +0000531/// SimplifyCompare - For a CmpInst this function just orders the operands
532/// so that theyare listed from right (least complex) to left (most complex).
533/// This puts constants before unary operators before binary operators.
534bool InstCombiner::SimplifyCompare(CmpInst &I) {
535 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
536 return false;
537 I.swapOperands();
538 // Compare instructions are not associative so there's nothing else we can do.
539 return true;
540}
541
Chris Lattner8d969642003-03-10 23:06:50 +0000542// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
543// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000544//
Chris Lattner8d969642003-03-10 23:06:50 +0000545static inline Value *dyn_castNegVal(Value *V) {
546 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000547 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000548
Chris Lattner0ce85802004-12-14 20:08:06 +0000549 // Constants can be considered to be negated values if they can be folded.
550 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
551 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000552 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000553}
554
Chris Lattner8d969642003-03-10 23:06:50 +0000555static inline Value *dyn_castNotVal(Value *V) {
556 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000557 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000558
559 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000560 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000561 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000562 return 0;
563}
564
Chris Lattnerc8802d22003-03-11 00:12:48 +0000565// dyn_castFoldableMul - If this value is a multiply that can be folded into
566// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000567// non-constant operand of the multiply, and set CST to point to the multiplier.
568// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000569//
Chris Lattner50af16a2004-11-13 19:50:12 +0000570static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000571 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000572 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000573 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000574 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000576 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000577 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000578 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000579 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000580 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000581 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000582 return I->getOperand(0);
583 }
584 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000585 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000586}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000587
Chris Lattner574da9b2005-01-13 20:14:25 +0000588/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
589/// expression, return it.
590static User *dyn_castGetElementPtr(Value *V) {
591 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
592 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
593 if (CE->getOpcode() == Instruction::GetElementPtr)
594 return cast<User>(V);
595 return false;
596}
597
Dan Gohmaneee962e2008-04-10 18:43:06 +0000598/// getOpcode - If this is an Instruction or a ConstantExpr, return the
599/// opcode value. Otherwise return UserOp1.
Dan Gohman45b4e482008-05-19 22:14:15 +0000600static unsigned getOpcode(Value *V) {
601 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000602 return I->getOpcode();
Dan Gohman45b4e482008-05-19 22:14:15 +0000603 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000604 return CE->getOpcode();
605 // Use UserOp1 to mean there's no opcode.
606 return Instruction::UserOp1;
607}
608
Reid Spencer7177c3a2007-03-25 05:33:51 +0000609/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000610static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000611 APInt Val(C->getValue());
612 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000613}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000614/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000615static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000616 APInt Val(C->getValue());
617 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000618}
619/// Add - Add two ConstantInts together
620static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
621 return ConstantInt::get(C1->getValue() + C2->getValue());
622}
623/// And - Bitwise AND two ConstantInts together
624static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
625 return ConstantInt::get(C1->getValue() & C2->getValue());
626}
627/// Subtract - Subtract one ConstantInt from another
628static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
629 return ConstantInt::get(C1->getValue() - C2->getValue());
630}
631/// Multiply - Multiply two ConstantInts together
632static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
633 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000634}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000635/// MultiplyOverflows - True if the multiply can not be expressed in an int
636/// this size.
637static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
638 uint32_t W = C1->getBitWidth();
639 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
640 if (sign) {
641 LHSExt.sext(W * 2);
642 RHSExt.sext(W * 2);
643 } else {
644 LHSExt.zext(W * 2);
645 RHSExt.zext(W * 2);
646 }
647
648 APInt MulExt = LHSExt * RHSExt;
649
650 if (sign) {
651 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
652 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
653 return MulExt.slt(Min) || MulExt.sgt(Max);
654 } else
655 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
656}
Chris Lattner955f3312004-09-28 21:48:02 +0000657
Chris Lattner68d5ff22006-02-09 07:38:58 +0000658/// ComputeMaskedBits - Determine which of the bits specified in Mask are
659/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000660/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
661/// processing.
662/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
663/// we cannot optimize based on the assumption that it is zero without changing
664/// it to be an explicit zero. If we don't change it to zero, other code could
665/// optimized based on the contradictory assumption that it is non-zero.
666/// Because instcombine aggressively folds operations with undef args anyway,
667/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000668void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
669 APInt& KnownZero, APInt& KnownOne,
Dan Gohman45b4e482008-05-19 22:14:15 +0000670 unsigned Depth) const {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000671 assert(V && "No Value?");
672 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000673 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000674 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
675 "Not integer or pointer type!");
676 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
677 (!isa<IntegerType>(V->getType()) ||
678 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000679 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000680 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000681 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Dan Gohman45b4e482008-05-19 22:14:15 +0000682
Reid Spencer3e7594f2007-03-08 01:46:38 +0000683 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
684 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000685 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000686 KnownZero = ~KnownOne & Mask;
687 return;
688 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000689 // Null is all-zeros.
690 if (isa<ConstantPointerNull>(V)) {
691 KnownOne.clear();
692 KnownZero = Mask;
693 return;
694 }
695 // The address of an aligned GlobalValue has trailing zeros.
696 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
697 unsigned Align = GV->getAlignment();
698 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
699 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
700 if (Align > 0)
701 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
702 CountTrailingZeros_32(Align));
703 else
704 KnownZero.clear();
705 KnownOne.clear();
706 return;
707 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000708
Dan Gohman23e8b712008-04-28 17:02:21 +0000709 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
710
Reid Spencer3e7594f2007-03-08 01:46:38 +0000711 if (Depth == 6 || Mask == 0)
712 return; // Limit search depth.
713
Dan Gohmaneee962e2008-04-10 18:43:06 +0000714 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000715 if (!I) return;
716
717 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000718 switch (getOpcode(I)) {
719 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000720 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 // If either the LHS or the RHS are Zero, the result is zero.
722 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000723 APInt Mask2(Mask & ~KnownZero);
724 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000725 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
726 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
727
728 // Output known-1 bits are only known if set in both the LHS & RHS.
729 KnownOne &= KnownOne2;
730 // Output known-0 are known to be clear if zero in either the LHS | RHS.
731 KnownZero |= KnownZero2;
732 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000733 }
734 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000735 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000736 APInt Mask2(Mask & ~KnownOne);
737 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000738 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
739 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
740
741 // Output known-0 bits are only known if clear in both the LHS & RHS.
742 KnownZero &= KnownZero2;
743 // Output known-1 are known to be set if set in either the LHS | RHS.
744 KnownOne |= KnownOne2;
745 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000746 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000747 case Instruction::Xor: {
748 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
749 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
750 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
751 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
752
753 // Output known-0 bits are known if clear or set in both the LHS & RHS.
754 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
755 // Output known-1 are known to be set if set in only one of the LHS, RHS.
756 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
757 KnownZero = KnownZeroOut;
758 return;
759 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000760 case Instruction::Mul: {
761 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
762 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
763 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
764 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
765 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
766
767 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000768 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000769 // More trickiness is possible, but this is sufficient for the
770 // interesting case of alignment computation.
771 KnownOne.clear();
772 unsigned TrailZ = KnownZero.countTrailingOnes() +
773 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000774 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000775 KnownZero2.countLeadingOnes(),
776 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000777
Dan Gohmaneee962e2008-04-10 18:43:06 +0000778 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000779 LeadZ = std::min(LeadZ, BitWidth);
780 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
781 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000782 KnownZero &= Mask;
783 return;
784 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000785 case Instruction::UDiv: {
786 // For the purposes of computing leading zeros we can conservatively
787 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000788 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000789 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
790 ComputeMaskedBits(I->getOperand(0),
791 AllOnes, KnownZero2, KnownOne2, Depth+1);
792 unsigned LeadZ = KnownZero2.countLeadingOnes();
793
794 KnownOne2.clear();
795 KnownZero2.clear();
796 ComputeMaskedBits(I->getOperand(1),
797 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000798 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
799 if (RHSUnknownLeadingOnes != BitWidth)
800 LeadZ = std::min(BitWidth,
801 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000802
803 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
804 return;
805 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000806 case Instruction::Select:
807 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
808 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
809 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
810 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
811
812 // Only known if known in both the LHS and RHS.
813 KnownOne &= KnownOne2;
814 KnownZero &= KnownZero2;
815 return;
816 case Instruction::FPTrunc:
817 case Instruction::FPExt:
818 case Instruction::FPToUI:
819 case Instruction::FPToSI:
820 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000821 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000822 return; // Can't work with floating point.
823 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000824 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000825 // We can't handle these if we don't know the pointer size.
826 if (!TD) return;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000827 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000828 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000829 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000830 // Note that we handle pointer operands here because of inttoptr/ptrtoint
831 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000832 const Type *SrcTy = I->getOperand(0)->getType();
833 uint32_t SrcBitWidth = TD ?
834 TD->getTypeSizeInBits(SrcTy) :
835 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000836 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000837 MaskIn.zextOrTrunc(SrcBitWidth);
838 KnownZero.zextOrTrunc(SrcBitWidth);
839 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000840 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000841 KnownZero.zextOrTrunc(BitWidth);
842 KnownOne.zextOrTrunc(BitWidth);
843 // Any top bits are known to be zero.
844 if (BitWidth > SrcBitWidth)
845 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000846 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000847 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000848 case Instruction::BitCast: {
849 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000850 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000851 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
852 return;
853 }
854 break;
855 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000856 case Instruction::SExt: {
857 // Compute the bits in the result that are not present in the input.
858 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000859 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000860
Zhou Shengaa305ab2007-03-28 02:19:03 +0000861 APInt MaskIn(Mask);
862 MaskIn.trunc(SrcBitWidth);
863 KnownZero.trunc(SrcBitWidth);
864 KnownOne.trunc(SrcBitWidth);
865 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000866 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000867 KnownZero.zext(BitWidth);
868 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000869
870 // If the sign bit of the input is known set or clear, then we know the
871 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000872 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000873 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000874 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000875 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000876 return;
877 }
878 case Instruction::Shl:
879 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
880 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000881 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000882 APInt Mask2(Mask.lshr(ShiftAmt));
883 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000884 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000885 KnownZero <<= ShiftAmt;
886 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000887 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000888 return;
889 }
890 break;
891 case Instruction::LShr:
892 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
893 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
894 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000895 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000896
897 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000898 APInt Mask2(Mask.shl(ShiftAmt));
899 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000900 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
901 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
902 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000903 // high bits known zero.
904 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000905 return;
906 }
907 break;
908 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000909 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000910 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
911 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000912 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000913
914 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000915 APInt Mask2(Mask.shl(ShiftAmt));
916 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000917 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
918 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
919 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
920
Zhou Shengaa305ab2007-03-28 02:19:03 +0000921 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
922 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000923 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000924 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000925 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000926 return;
927 }
928 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000929 case Instruction::Sub: {
930 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
931 // We know that the top bits of C-X are clear if X contains less bits
932 // than C (i.e. no wrap-around can happen). For example, 20-X is
933 // positive if we can prove that X is >= 0 and < 16.
934 if (!CLHS->getValue().isNegative()) {
935 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
936 // NLZ can't be BitWidth with no sign bit
937 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000938 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
939 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000940
Dan Gohman23e8b712008-04-28 17:02:21 +0000941 // If all of the MaskV bits are known to be zero, then we know the
942 // output top bits are zero, because we now know that the output is
943 // from [0-C].
944 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000945 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
946 // Top bits known zero.
947 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000948 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000949 }
950 }
951 }
952 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000953 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000954 // Output known-0 bits are known if clear or set in both the low clear bits
955 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
956 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000957 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
958 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
959 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
960 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
961
962 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
963 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
964 KnownZeroOut = std::min(KnownZeroOut,
965 KnownZero2.countTrailingOnes());
966
967 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000968 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000969 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000970 case Instruction::SRem:
971 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
972 APInt RA = Rem->getValue();
973 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000974 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000975 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
976 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
977
978 // The sign of a remainder is equal to the sign of the first
979 // operand (zero being positive).
980 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
981 KnownZero2 |= ~LowBits;
982 else if (KnownOne2[BitWidth-1])
983 KnownOne2 |= ~LowBits;
984
985 KnownZero |= KnownZero2 & Mask;
986 KnownOne |= KnownOne2 & Mask;
987
988 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
989 }
990 }
991 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000992 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000993 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
994 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +0000995 if (RA.isPowerOf2()) {
996 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000997 APInt Mask2 = LowBits & Mask;
998 KnownZero |= ~LowBits & Mask;
999 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1000 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001001 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001002 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001003 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001004
1005 // Since the result is less than or equal to either operand, any leading
1006 // zero bits in either operand must also exist in the result.
1007 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1008 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1009 Depth+1);
1010 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1011 Depth+1);
1012
1013 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1014 KnownZero2.countLeadingOnes());
1015 KnownOne.clear();
1016 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001017 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001018 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001019
1020 case Instruction::Alloca:
1021 case Instruction::Malloc: {
1022 AllocationInst *AI = cast<AllocationInst>(V);
1023 unsigned Align = AI->getAlignment();
1024 if (Align == 0 && TD) {
1025 if (isa<AllocaInst>(AI))
1026 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1027 else if (isa<MallocInst>(AI)) {
1028 // Malloc returns maximally aligned memory.
1029 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1030 Align =
1031 std::max(Align,
1032 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1033 Align =
1034 std::max(Align,
1035 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1036 }
1037 }
1038
1039 if (Align > 0)
1040 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1041 CountTrailingZeros_32(Align));
1042 break;
1043 }
1044 case Instruction::GetElementPtr: {
1045 // Analyze all of the subscripts of this getelementptr instruction
1046 // to determine if we can prove known low zero bits.
1047 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1048 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1049 ComputeMaskedBits(I->getOperand(0), LocalMask,
1050 LocalKnownZero, LocalKnownOne, Depth+1);
1051 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1052
1053 gep_type_iterator GTI = gep_type_begin(I);
1054 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1055 Value *Index = I->getOperand(i);
1056 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1057 // Handle struct member offset arithmetic.
1058 if (!TD) return;
1059 const StructLayout *SL = TD->getStructLayout(STy);
1060 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1061 uint64_t Offset = SL->getElementOffset(Idx);
1062 TrailZ = std::min(TrailZ,
1063 CountTrailingZeros_64(Offset));
1064 } else {
1065 // Handle array index arithmetic.
1066 const Type *IndexedTy = GTI.getIndexedType();
1067 if (!IndexedTy->isSized()) return;
1068 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1069 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1070 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1071 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1072 ComputeMaskedBits(Index, LocalMask,
1073 LocalKnownZero, LocalKnownOne, Depth+1);
1074 TrailZ = std::min(TrailZ,
1075 CountTrailingZeros_64(TypeSize) +
1076 LocalKnownZero.countTrailingOnes());
1077 }
1078 }
1079
1080 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1081 break;
1082 }
1083 case Instruction::PHI: {
1084 PHINode *P = cast<PHINode>(I);
1085 // Handle the case of a simple two-predecessor recurrence PHI.
1086 // There's a lot more that could theoretically be done here, but
1087 // this is sufficient to catch some interesting cases.
1088 if (P->getNumIncomingValues() == 2) {
1089 for (unsigned i = 0; i != 2; ++i) {
1090 Value *L = P->getIncomingValue(i);
1091 Value *R = P->getIncomingValue(!i);
1092 User *LU = dyn_cast<User>(L);
1093 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1094 // Check for operations that have the property that if
1095 // both their operands have low zero bits, the result
1096 // will have low zero bits.
1097 if (Opcode == Instruction::Add ||
1098 Opcode == Instruction::Sub ||
1099 Opcode == Instruction::And ||
1100 Opcode == Instruction::Or ||
1101 Opcode == Instruction::Mul) {
1102 Value *LL = LU->getOperand(0);
1103 Value *LR = LU->getOperand(1);
1104 // Find a recurrence.
1105 if (LL == I)
1106 L = LR;
1107 else if (LR == I)
1108 L = LL;
1109 else
1110 break;
1111 // Ok, we have a PHI of the form L op= R. Check for low
1112 // zero bits.
1113 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1114 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1115 Mask2 = APInt::getLowBitsSet(BitWidth,
1116 KnownZero2.countTrailingOnes());
1117 KnownOne2.clear();
1118 KnownZero2.clear();
1119 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1120 KnownZero = Mask &
1121 APInt::getLowBitsSet(BitWidth,
1122 KnownZero2.countTrailingOnes());
1123 break;
1124 }
1125 }
1126 }
1127 break;
1128 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001129 case Instruction::Call:
1130 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1131 switch (II->getIntrinsicID()) {
1132 default: break;
1133 case Intrinsic::ctpop:
1134 case Intrinsic::ctlz:
1135 case Intrinsic::cttz: {
1136 unsigned LowBits = Log2_32(BitWidth)+1;
1137 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1138 break;
1139 }
1140 }
1141 }
1142 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001143 }
1144}
1145
Reid Spencere7816b52007-03-08 01:52:58 +00001146/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1147/// this predicate to simplify operations downstream. Mask is known to be zero
1148/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001149bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1150 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001151 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001152 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1153 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1154 return (KnownZero & Mask) == Mask;
1155}
1156
Chris Lattner255d8912006-02-11 09:31:47 +00001157/// ShrinkDemandedConstant - Check to see if the specified operand of the
1158/// specified instruction is a constant integer. If so, check to see if there
1159/// are any bits set in the constant that are not demanded. If so, shrink the
1160/// constant and return true.
1161static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001162 APInt Demanded) {
1163 assert(I && "No instruction?");
1164 assert(OpNo < I->getNumOperands() && "Operand index too large");
1165
1166 // If the operand is not a constant integer, nothing to do.
1167 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1168 if (!OpC) return false;
1169
1170 // If there are no bits set that aren't demanded, nothing to do.
1171 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1172 if ((~Demanded & OpC->getValue()) == 0)
1173 return false;
1174
1175 // This instruction is producing bits that are not demanded. Shrink the RHS.
1176 Demanded &= OpC->getValue();
1177 I->setOperand(OpNo, ConstantInt::get(Demanded));
1178 return true;
1179}
1180
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001181// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1182// set of known zero and one bits, compute the maximum and minimum values that
1183// could have the specified known zero and known one bits, returning them in
1184// min/max.
1185static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001186 const APInt& KnownZero,
1187 const APInt& KnownOne,
1188 APInt& Min, APInt& Max) {
1189 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1190 assert(KnownZero.getBitWidth() == BitWidth &&
1191 KnownOne.getBitWidth() == BitWidth &&
1192 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1193 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001194 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001195
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001196 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1197 // bit if it is unknown.
1198 Min = KnownOne;
1199 Max = KnownOne|UnknownBits;
1200
Zhou Sheng4acf1552007-03-28 05:15:57 +00001201 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001202 Min.set(BitWidth-1);
1203 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001204 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001205}
1206
1207// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1208// a set of known zero and one bits, compute the maximum and minimum values that
1209// could have the specified known zero and known one bits, returning them in
1210// min/max.
1211static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001212 const APInt &KnownZero,
1213 const APInt &KnownOne,
1214 APInt &Min, APInt &Max) {
1215 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001216 assert(KnownZero.getBitWidth() == BitWidth &&
1217 KnownOne.getBitWidth() == BitWidth &&
1218 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1219 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001220 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001221
1222 // The minimum value is when the unknown bits are all zeros.
1223 Min = KnownOne;
1224 // The maximum value is when the unknown bits are all ones.
1225 Max = KnownOne|UnknownBits;
1226}
Chris Lattner255d8912006-02-11 09:31:47 +00001227
Reid Spencer8cb68342007-03-12 17:25:59 +00001228/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1229/// value based on the demanded bits. When this function is called, it is known
1230/// that only the bits set in DemandedMask of the result of V are ever used
1231/// downstream. Consequently, depending on the mask and V, it may be possible
1232/// to replace V with a constant or one of its operands. In such cases, this
1233/// function does the replacement and returns true. In all other cases, it
1234/// returns false after analyzing the expression and setting KnownOne and known
1235/// to be one in the expression. KnownZero contains all the bits that are known
1236/// to be zero in the expression. These are provided to potentially allow the
1237/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1238/// the expression. KnownOne and KnownZero always follow the invariant that
1239/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1240/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1241/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1242/// and KnownOne must all be the same.
1243bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1244 APInt& KnownZero, APInt& KnownOne,
1245 unsigned Depth) {
1246 assert(V != 0 && "Null pointer of Value???");
1247 assert(Depth <= 6 && "Limit Search Depth");
1248 uint32_t BitWidth = DemandedMask.getBitWidth();
1249 const IntegerType *VTy = cast<IntegerType>(V->getType());
1250 assert(VTy->getBitWidth() == BitWidth &&
1251 KnownZero.getBitWidth() == BitWidth &&
1252 KnownOne.getBitWidth() == BitWidth &&
1253 "Value *V, DemandedMask, KnownZero and KnownOne \
1254 must have same BitWidth");
1255 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1256 // We know all of the bits for a constant!
1257 KnownOne = CI->getValue() & DemandedMask;
1258 KnownZero = ~KnownOne & DemandedMask;
1259 return false;
1260 }
1261
Zhou Sheng96704452007-03-14 03:21:24 +00001262 KnownZero.clear();
1263 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001264 if (!V->hasOneUse()) { // Other users may use these bits.
1265 if (Depth != 0) { // Not at the root.
1266 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1267 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1268 return false;
1269 }
1270 // If this is the root being simplified, allow it to have multiple uses,
1271 // just set the DemandedMask to all bits.
1272 DemandedMask = APInt::getAllOnesValue(BitWidth);
1273 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1274 if (V != UndefValue::get(VTy))
1275 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1276 return false;
1277 } else if (Depth == 6) { // Limit search depth.
1278 return false;
1279 }
1280
1281 Instruction *I = dyn_cast<Instruction>(V);
1282 if (!I) return false; // Only analyze instructions.
1283
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1285 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1286 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001287 default:
1288 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1289 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 case Instruction::And:
1291 // If either the LHS or the RHS are Zero, the result is zero.
1292 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1293 RHSKnownZero, RHSKnownOne, Depth+1))
1294 return true;
1295 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1296 "Bits known to be one AND zero?");
1297
1298 // If something is known zero on the RHS, the bits aren't demanded on the
1299 // LHS.
1300 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1301 LHSKnownZero, LHSKnownOne, Depth+1))
1302 return true;
1303 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1304 "Bits known to be one AND zero?");
1305
1306 // If all of the demanded bits are known 1 on one side, return the other.
1307 // These bits cannot contribute to the result of the 'and'.
1308 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1309 (DemandedMask & ~LHSKnownZero))
1310 return UpdateValueUsesWith(I, I->getOperand(0));
1311 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1312 (DemandedMask & ~RHSKnownZero))
1313 return UpdateValueUsesWith(I, I->getOperand(1));
1314
1315 // If all of the demanded bits in the inputs are known zeros, return zero.
1316 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1317 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1318
1319 // If the RHS is a constant, see if we can simplify it.
1320 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1321 return UpdateValueUsesWith(I, I);
1322
1323 // Output known-1 bits are only known if set in both the LHS & RHS.
1324 RHSKnownOne &= LHSKnownOne;
1325 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1326 RHSKnownZero |= LHSKnownZero;
1327 break;
1328 case Instruction::Or:
1329 // If either the LHS or the RHS are One, the result is One.
1330 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1331 RHSKnownZero, RHSKnownOne, Depth+1))
1332 return true;
1333 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1334 "Bits known to be one AND zero?");
1335 // If something is known one on the RHS, the bits aren't demanded on the
1336 // LHS.
1337 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1338 LHSKnownZero, LHSKnownOne, Depth+1))
1339 return true;
1340 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1341 "Bits known to be one AND zero?");
1342
1343 // If all of the demanded bits are known zero on one side, return the other.
1344 // These bits cannot contribute to the result of the 'or'.
1345 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1346 (DemandedMask & ~LHSKnownOne))
1347 return UpdateValueUsesWith(I, I->getOperand(0));
1348 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1349 (DemandedMask & ~RHSKnownOne))
1350 return UpdateValueUsesWith(I, I->getOperand(1));
1351
1352 // If all of the potentially set bits on one side are known to be set on
1353 // the other side, just use the 'other' side.
1354 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1355 (DemandedMask & (~RHSKnownZero)))
1356 return UpdateValueUsesWith(I, I->getOperand(0));
1357 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1358 (DemandedMask & (~LHSKnownZero)))
1359 return UpdateValueUsesWith(I, I->getOperand(1));
1360
1361 // If the RHS is a constant, see if we can simplify it.
1362 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1363 return UpdateValueUsesWith(I, I);
1364
1365 // Output known-0 bits are only known if clear in both the LHS & RHS.
1366 RHSKnownZero &= LHSKnownZero;
1367 // Output known-1 are known to be set if set in either the LHS | RHS.
1368 RHSKnownOne |= LHSKnownOne;
1369 break;
1370 case Instruction::Xor: {
1371 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1372 RHSKnownZero, RHSKnownOne, Depth+1))
1373 return true;
1374 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1375 "Bits known to be one AND zero?");
1376 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1377 LHSKnownZero, LHSKnownOne, Depth+1))
1378 return true;
1379 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1380 "Bits known to be one AND zero?");
1381
1382 // If all of the demanded bits are known zero on one side, return the other.
1383 // These bits cannot contribute to the result of the 'xor'.
1384 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1385 return UpdateValueUsesWith(I, I->getOperand(0));
1386 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1387 return UpdateValueUsesWith(I, I->getOperand(1));
1388
1389 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1390 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1391 (RHSKnownOne & LHSKnownOne);
1392 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1393 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1394 (RHSKnownOne & LHSKnownZero);
1395
1396 // If all of the demanded bits are known to be zero on one side or the
1397 // other, turn this into an *inclusive* or.
1398 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1399 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1400 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001401 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001402 I->getName());
1403 InsertNewInstBefore(Or, *I);
1404 return UpdateValueUsesWith(I, Or);
1405 }
1406
1407 // If all of the demanded bits on one side are known, and all of the set
1408 // bits on that side are also known to be set on the other side, turn this
1409 // into an AND, as we know the bits will be cleared.
1410 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1411 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1412 // all known
1413 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1414 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1415 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001416 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001417 InsertNewInstBefore(And, *I);
1418 return UpdateValueUsesWith(I, And);
1419 }
1420 }
1421
1422 // If the RHS is a constant, see if we can simplify it.
1423 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1424 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1425 return UpdateValueUsesWith(I, I);
1426
1427 RHSKnownZero = KnownZeroOut;
1428 RHSKnownOne = KnownOneOut;
1429 break;
1430 }
1431 case Instruction::Select:
1432 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1433 RHSKnownZero, RHSKnownOne, Depth+1))
1434 return true;
1435 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1436 LHSKnownZero, LHSKnownOne, Depth+1))
1437 return true;
1438 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1439 "Bits known to be one AND zero?");
1440 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1441 "Bits known to be one AND zero?");
1442
1443 // If the operands are constants, see if we can simplify them.
1444 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1445 return UpdateValueUsesWith(I, I);
1446 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1447 return UpdateValueUsesWith(I, I);
1448
1449 // Only known if known in both the LHS and RHS.
1450 RHSKnownOne &= LHSKnownOne;
1451 RHSKnownZero &= LHSKnownZero;
1452 break;
1453 case Instruction::Trunc: {
1454 uint32_t truncBf =
1455 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001456 DemandedMask.zext(truncBf);
1457 RHSKnownZero.zext(truncBf);
1458 RHSKnownOne.zext(truncBf);
1459 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1460 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001461 return true;
1462 DemandedMask.trunc(BitWidth);
1463 RHSKnownZero.trunc(BitWidth);
1464 RHSKnownOne.trunc(BitWidth);
1465 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1466 "Bits known to be one AND zero?");
1467 break;
1468 }
1469 case Instruction::BitCast:
1470 if (!I->getOperand(0)->getType()->isInteger())
1471 return false;
1472
1473 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1474 RHSKnownZero, RHSKnownOne, Depth+1))
1475 return true;
1476 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1477 "Bits known to be one AND zero?");
1478 break;
1479 case Instruction::ZExt: {
1480 // Compute the bits in the result that are not present in the input.
1481 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001482 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001483
Zhou Shengd48653a2007-03-29 04:45:55 +00001484 DemandedMask.trunc(SrcBitWidth);
1485 RHSKnownZero.trunc(SrcBitWidth);
1486 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001487 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1488 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001489 return true;
1490 DemandedMask.zext(BitWidth);
1491 RHSKnownZero.zext(BitWidth);
1492 RHSKnownOne.zext(BitWidth);
1493 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1494 "Bits known to be one AND zero?");
1495 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001496 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001497 break;
1498 }
1499 case Instruction::SExt: {
1500 // Compute the bits in the result that are not present in the input.
1501 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001502 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001503
Reid Spencer8cb68342007-03-12 17:25:59 +00001504 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001505 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001506
Zhou Sheng01542f32007-03-29 02:26:30 +00001507 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001508 // If any of the sign extended bits are demanded, we know that the sign
1509 // bit is demanded.
1510 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001511 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001512
Zhou Shengd48653a2007-03-29 04:45:55 +00001513 InputDemandedBits.trunc(SrcBitWidth);
1514 RHSKnownZero.trunc(SrcBitWidth);
1515 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001516 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1517 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001518 return true;
1519 InputDemandedBits.zext(BitWidth);
1520 RHSKnownZero.zext(BitWidth);
1521 RHSKnownOne.zext(BitWidth);
1522 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1523 "Bits known to be one AND zero?");
1524
1525 // If the sign bit of the input is known set or clear, then we know the
1526 // top bits of the result.
1527
1528 // If the input sign bit is known zero, or if the NewBits are not demanded
1529 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001530 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001531 {
1532 // Convert to ZExt cast
1533 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1534 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001535 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001536 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001537 }
1538 break;
1539 }
1540 case Instruction::Add: {
1541 // Figure out what the input bits are. If the top bits of the and result
1542 // are not demanded, then the add doesn't demand them from its input
1543 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001544 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001545
1546 // If there is a constant on the RHS, there are a variety of xformations
1547 // we can do.
1548 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1549 // If null, this should be simplified elsewhere. Some of the xforms here
1550 // won't work if the RHS is zero.
1551 if (RHS->isZero())
1552 break;
1553
1554 // If the top bit of the output is demanded, demand everything from the
1555 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001556 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001557
1558 // Find information about known zero/one bits in the input.
1559 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1560 LHSKnownZero, LHSKnownOne, Depth+1))
1561 return true;
1562
1563 // If the RHS of the add has bits set that can't affect the input, reduce
1564 // the constant.
1565 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1566 return UpdateValueUsesWith(I, I);
1567
1568 // Avoid excess work.
1569 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1570 break;
1571
1572 // Turn it into OR if input bits are zero.
1573 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1574 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001575 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001576 I->getName());
1577 InsertNewInstBefore(Or, *I);
1578 return UpdateValueUsesWith(I, Or);
1579 }
1580
1581 // We can say something about the output known-zero and known-one bits,
1582 // depending on potential carries from the input constant and the
1583 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1584 // bits set and the RHS constant is 0x01001, then we know we have a known
1585 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1586
1587 // To compute this, we first compute the potential carry bits. These are
1588 // the bits which may be modified. I'm not aware of a better way to do
1589 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001590 const APInt& RHSVal = RHS->getValue();
1591 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001592
1593 // Now that we know which bits have carries, compute the known-1/0 sets.
1594
1595 // Bits are known one if they are known zero in one operand and one in the
1596 // other, and there is no input carry.
1597 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1598 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1599
1600 // Bits are known zero if they are known zero in both operands and there
1601 // is no input carry.
1602 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1603 } else {
1604 // If the high-bits of this ADD are not demanded, then it does not demand
1605 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001606 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001607 // Right fill the mask of bits for this ADD to demand the most
1608 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001609 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001610 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1611 LHSKnownZero, LHSKnownOne, Depth+1))
1612 return true;
1613 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1614 LHSKnownZero, LHSKnownOne, Depth+1))
1615 return true;
1616 }
1617 }
1618 break;
1619 }
1620 case Instruction::Sub:
1621 // If the high-bits of this SUB are not demanded, then it does not demand
1622 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001623 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001624 // Right fill the mask of bits for this SUB to demand the most
1625 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001626 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001627 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001628 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1629 LHSKnownZero, LHSKnownOne, Depth+1))
1630 return true;
1631 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1632 LHSKnownZero, LHSKnownOne, Depth+1))
1633 return true;
1634 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001635 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1636 // the known zeros and ones.
1637 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001638 break;
1639 case Instruction::Shl:
1640 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001641 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001642 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1643 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001644 RHSKnownZero, RHSKnownOne, Depth+1))
1645 return true;
1646 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1647 "Bits known to be one AND zero?");
1648 RHSKnownZero <<= ShiftAmt;
1649 RHSKnownOne <<= ShiftAmt;
1650 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001651 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001652 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001653 }
1654 break;
1655 case Instruction::LShr:
1656 // For a logical shift right
1657 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001658 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001659
Reid Spencer8cb68342007-03-12 17:25:59 +00001660 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001661 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1662 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001663 RHSKnownZero, RHSKnownOne, Depth+1))
1664 return true;
1665 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1666 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001667 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1668 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001669 if (ShiftAmt) {
1670 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001671 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001672 RHSKnownZero |= HighBits; // high bits known zero.
1673 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001674 }
1675 break;
1676 case Instruction::AShr:
1677 // If this is an arithmetic shift right and only the low-bit is set, we can
1678 // always convert this into a logical shr, even if the shift amount is
1679 // variable. The low bit of the shift cannot be an input sign bit unless
1680 // the shift amount is >= the size of the datatype, which is undefined.
1681 if (DemandedMask == 1) {
1682 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001683 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001684 I->getOperand(0), I->getOperand(1), I->getName());
1685 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1686 return UpdateValueUsesWith(I, NewVal);
1687 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001688
1689 // If the sign bit is the only bit demanded by this ashr, then there is no
1690 // need to do it, the shift doesn't change the high bit.
1691 if (DemandedMask.isSignBit())
1692 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001693
1694 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001695 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001696
Reid Spencer8cb68342007-03-12 17:25:59 +00001697 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001698 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001699 // If any of the "high bits" are demanded, we should set the sign bit as
1700 // demanded.
1701 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1702 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001703 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001704 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001705 RHSKnownZero, RHSKnownOne, Depth+1))
1706 return true;
1707 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1708 "Bits known to be one AND zero?");
1709 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001710 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001711 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1712 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1713
1714 // Handle the sign bits.
1715 APInt SignBit(APInt::getSignBit(BitWidth));
1716 // Adjust to where it is now in the mask.
1717 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1718
1719 // If the input sign bit is known to be zero, or if none of the top bits
1720 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001721 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001722 (HighBits & ~DemandedMask) == HighBits) {
1723 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001724 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001725 I->getOperand(0), SA, I->getName());
1726 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1727 return UpdateValueUsesWith(I, NewVal);
1728 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1729 RHSKnownOne |= HighBits;
1730 }
1731 }
1732 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001733 case Instruction::SRem:
1734 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1735 APInt RA = Rem->getValue();
1736 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001737 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001738 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1739 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1740 LHSKnownZero, LHSKnownOne, Depth+1))
1741 return true;
1742
1743 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1744 LHSKnownZero |= ~LowBits;
1745 else if (LHSKnownOne[BitWidth-1])
1746 LHSKnownOne |= ~LowBits;
1747
1748 KnownZero |= LHSKnownZero & DemandedMask;
1749 KnownOne |= LHSKnownOne & DemandedMask;
1750
1751 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1752 }
1753 }
1754 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001755 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001756 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1757 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001758 if (RA.isPowerOf2()) {
1759 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001760 APInt Mask2 = LowBits & DemandedMask;
1761 KnownZero |= ~LowBits & DemandedMask;
1762 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1763 KnownZero, KnownOne, Depth+1))
1764 return true;
1765
1766 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001767 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001768 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001769 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001770
1771 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1772 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001773 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1774 KnownZero2, KnownOne2, Depth+1))
1775 return true;
1776
Dan Gohman23e8b712008-04-28 17:02:21 +00001777 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001778 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001779 KnownZero2, KnownOne2, Depth+1))
1780 return true;
1781
1782 Leaders = std::max(Leaders,
1783 KnownZero2.countLeadingOnes());
1784 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001785 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001786 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001787 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001788
1789 // If the client is only demanding bits that we know, return the known
1790 // constant.
1791 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1792 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1793 return false;
1794}
1795
Chris Lattner867b99f2006-10-05 06:55:50 +00001796
1797/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1798/// 64 or fewer elements. DemandedElts contains the set of elements that are
1799/// actually used by the caller. This method analyzes which elements of the
1800/// operand are undef and returns that information in UndefElts.
1801///
1802/// If the information about demanded elements can be used to simplify the
1803/// operation, the operation is simplified, then the resultant value is
1804/// returned. This returns null if no change was made.
1805Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1806 uint64_t &UndefElts,
1807 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001808 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001809 assert(VWidth <= 64 && "Vector too wide to analyze!");
1810 uint64_t EltMask = ~0ULL >> (64-VWidth);
1811 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1812 "Invalid DemandedElts!");
1813
1814 if (isa<UndefValue>(V)) {
1815 // If the entire vector is undefined, just return this info.
1816 UndefElts = EltMask;
1817 return 0;
1818 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1819 UndefElts = EltMask;
1820 return UndefValue::get(V->getType());
1821 }
1822
1823 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001824 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1825 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001826 Constant *Undef = UndefValue::get(EltTy);
1827
1828 std::vector<Constant*> Elts;
1829 for (unsigned i = 0; i != VWidth; ++i)
1830 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1831 Elts.push_back(Undef);
1832 UndefElts |= (1ULL << i);
1833 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1834 Elts.push_back(Undef);
1835 UndefElts |= (1ULL << i);
1836 } else { // Otherwise, defined.
1837 Elts.push_back(CP->getOperand(i));
1838 }
1839
1840 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001841 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001842 return NewCP != CP ? NewCP : 0;
1843 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001844 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001845 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001846 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001847 Constant *Zero = Constant::getNullValue(EltTy);
1848 Constant *Undef = UndefValue::get(EltTy);
1849 std::vector<Constant*> Elts;
1850 for (unsigned i = 0; i != VWidth; ++i)
1851 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1852 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001853 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001854 }
1855
1856 if (!V->hasOneUse()) { // Other users may use these bits.
1857 if (Depth != 0) { // Not at the root.
1858 // TODO: Just compute the UndefElts information recursively.
1859 return false;
1860 }
1861 return false;
1862 } else if (Depth == 10) { // Limit search depth.
1863 return false;
1864 }
1865
1866 Instruction *I = dyn_cast<Instruction>(V);
1867 if (!I) return false; // Only analyze instructions.
1868
1869 bool MadeChange = false;
1870 uint64_t UndefElts2;
1871 Value *TmpV;
1872 switch (I->getOpcode()) {
1873 default: break;
1874
1875 case Instruction::InsertElement: {
1876 // If this is a variable index, we don't know which element it overwrites.
1877 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001878 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001879 if (Idx == 0) {
1880 // Note that we can't propagate undef elt info, because we don't know
1881 // which elt is getting updated.
1882 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1883 UndefElts2, Depth+1);
1884 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1885 break;
1886 }
1887
1888 // If this is inserting an element that isn't demanded, remove this
1889 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001890 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001891 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1892 return AddSoonDeadInstToWorklist(*I, 0);
1893
1894 // Otherwise, the element inserted overwrites whatever was there, so the
1895 // input demanded set is simpler than the output set.
1896 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1897 DemandedElts & ~(1ULL << IdxNo),
1898 UndefElts, Depth+1);
1899 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1900
1901 // The inserted element is defined.
1902 UndefElts |= 1ULL << IdxNo;
1903 break;
1904 }
Chris Lattner69878332007-04-14 22:29:23 +00001905 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001906 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001907 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1908 if (!VTy) break;
1909 unsigned InVWidth = VTy->getNumElements();
1910 uint64_t InputDemandedElts = 0;
1911 unsigned Ratio;
1912
1913 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001914 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001915 // elements as are demanded of us.
1916 Ratio = 1;
1917 InputDemandedElts = DemandedElts;
1918 } else if (VWidth > InVWidth) {
1919 // Untested so far.
1920 break;
1921
1922 // If there are more elements in the result than there are in the source,
1923 // then an input element is live if any of the corresponding output
1924 // elements are live.
1925 Ratio = VWidth/InVWidth;
1926 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1927 if (DemandedElts & (1ULL << OutIdx))
1928 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1929 }
1930 } else {
1931 // Untested so far.
1932 break;
1933
1934 // If there are more elements in the source than there are in the result,
1935 // then an input element is live if the corresponding output element is
1936 // live.
1937 Ratio = InVWidth/VWidth;
1938 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1939 if (DemandedElts & (1ULL << InIdx/Ratio))
1940 InputDemandedElts |= 1ULL << InIdx;
1941 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001942
Chris Lattner69878332007-04-14 22:29:23 +00001943 // div/rem demand all inputs, because they don't want divide by zero.
1944 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1945 UndefElts2, Depth+1);
1946 if (TmpV) {
1947 I->setOperand(0, TmpV);
1948 MadeChange = true;
1949 }
1950
1951 UndefElts = UndefElts2;
1952 if (VWidth > InVWidth) {
1953 assert(0 && "Unimp");
1954 // If there are more elements in the result than there are in the source,
1955 // then an output element is undef if the corresponding input element is
1956 // undef.
1957 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1958 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1959 UndefElts |= 1ULL << OutIdx;
1960 } else if (VWidth < InVWidth) {
1961 assert(0 && "Unimp");
1962 // If there are more elements in the source than there are in the result,
1963 // then a result element is undef if all of the corresponding input
1964 // elements are undef.
1965 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1966 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1967 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1968 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1969 }
1970 break;
1971 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001972 case Instruction::And:
1973 case Instruction::Or:
1974 case Instruction::Xor:
1975 case Instruction::Add:
1976 case Instruction::Sub:
1977 case Instruction::Mul:
1978 // div/rem demand all inputs, because they don't want divide by zero.
1979 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1980 UndefElts, Depth+1);
1981 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1982 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1983 UndefElts2, Depth+1);
1984 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1985
1986 // Output elements are undefined if both are undefined. Consider things
1987 // like undef&0. The result is known zero, not undef.
1988 UndefElts &= UndefElts2;
1989 break;
1990
1991 case Instruction::Call: {
1992 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1993 if (!II) break;
1994 switch (II->getIntrinsicID()) {
1995 default: break;
1996
1997 // Binary vector operations that work column-wise. A dest element is a
1998 // function of the corresponding input elements from the two inputs.
1999 case Intrinsic::x86_sse_sub_ss:
2000 case Intrinsic::x86_sse_mul_ss:
2001 case Intrinsic::x86_sse_min_ss:
2002 case Intrinsic::x86_sse_max_ss:
2003 case Intrinsic::x86_sse2_sub_sd:
2004 case Intrinsic::x86_sse2_mul_sd:
2005 case Intrinsic::x86_sse2_min_sd:
2006 case Intrinsic::x86_sse2_max_sd:
2007 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2008 UndefElts, Depth+1);
2009 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2010 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2011 UndefElts2, Depth+1);
2012 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2013
2014 // If only the low elt is demanded and this is a scalarizable intrinsic,
2015 // scalarize it now.
2016 if (DemandedElts == 1) {
2017 switch (II->getIntrinsicID()) {
2018 default: break;
2019 case Intrinsic::x86_sse_sub_ss:
2020 case Intrinsic::x86_sse_mul_ss:
2021 case Intrinsic::x86_sse2_sub_sd:
2022 case Intrinsic::x86_sse2_mul_sd:
2023 // TODO: Lower MIN/MAX/ABS/etc
2024 Value *LHS = II->getOperand(1);
2025 Value *RHS = II->getOperand(2);
2026 // Extract the element as scalars.
2027 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2028 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2029
2030 switch (II->getIntrinsicID()) {
2031 default: assert(0 && "Case stmts out of sync!");
2032 case Intrinsic::x86_sse_sub_ss:
2033 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002034 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002035 II->getName()), *II);
2036 break;
2037 case Intrinsic::x86_sse_mul_ss:
2038 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002039 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002040 II->getName()), *II);
2041 break;
2042 }
2043
2044 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002045 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2046 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002047 InsertNewInstBefore(New, *II);
2048 AddSoonDeadInstToWorklist(*II, 0);
2049 return New;
2050 }
2051 }
2052
2053 // Output elements are undefined if both are undefined. Consider things
2054 // like undef&0. The result is known zero, not undef.
2055 UndefElts &= UndefElts2;
2056 break;
2057 }
2058 break;
2059 }
2060 }
2061 return MadeChange ? I : 0;
2062}
2063
Dan Gohman45b4e482008-05-19 22:14:15 +00002064/// ComputeNumSignBits - Return the number of times the sign bit of the
2065/// register is replicated into the other bits. We know that at least 1 bit
2066/// is always equal to the sign bit (itself), but other cases can give us
2067/// information. For example, immediately after an "ashr X, 2", we know that
2068/// the top 3 bits are all equal to each other, so we return 3.
2069///
2070unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2071 const IntegerType *Ty = cast<IntegerType>(V->getType());
2072 unsigned TyBits = Ty->getBitWidth();
2073 unsigned Tmp, Tmp2;
2074
2075 if (Depth == 6)
2076 return 1; // Limit search depth.
2077
2078 User *U = dyn_cast<User>(V);
2079 switch (getOpcode(V)) {
2080 default: break;
2081 case Instruction::SExt:
2082 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2083 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2084
2085 case Instruction::AShr:
2086 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2087 // SRA X, C -> adds C sign bits.
2088 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2089 Tmp += C->getZExtValue();
2090 if (Tmp > TyBits) Tmp = TyBits;
2091 }
2092 return Tmp;
2093 case Instruction::Shl:
2094 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2095 // shl destroys sign bits.
2096 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2097 if (C->getZExtValue() >= TyBits || // Bad shift.
2098 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2099 return Tmp - C->getZExtValue();
2100 }
2101 break;
2102 case Instruction::And:
2103 case Instruction::Or:
2104 case Instruction::Xor: // NOT is handled here.
2105 // Logical binary ops preserve the number of sign bits.
2106 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2107 if (Tmp == 1) return 1; // Early out.
2108 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2109 return std::min(Tmp, Tmp2);
2110
2111 case Instruction::Select:
2112 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2113 if (Tmp == 1) return 1; // Early out.
2114 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2115 return std::min(Tmp, Tmp2);
2116
2117 case Instruction::Add:
2118 // Add can have at most one carry bit. Thus we know that the output
2119 // is, at worst, one more bit than the inputs.
2120 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2121 if (Tmp == 1) return 1; // Early out.
2122
2123 // Special case decrementing a value (ADD X, -1):
2124 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2125 if (CRHS->isAllOnesValue()) {
2126 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2127 APInt Mask = APInt::getAllOnesValue(TyBits);
2128 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2129
2130 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2131 // sign bits set.
2132 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2133 return TyBits;
2134
2135 // If we are subtracting one from a positive number, there is no carry
2136 // out of the result.
2137 if (KnownZero.isNegative())
2138 return Tmp;
2139 }
2140
2141 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2142 if (Tmp2 == 1) return 1;
2143 return std::min(Tmp, Tmp2)-1;
2144 break;
2145
2146 case Instruction::Sub:
2147 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2148 if (Tmp2 == 1) return 1;
2149
2150 // Handle NEG.
2151 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2152 if (CLHS->isNullValue()) {
2153 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2154 APInt Mask = APInt::getAllOnesValue(TyBits);
2155 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2156 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2157 // sign bits set.
2158 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2159 return TyBits;
2160
2161 // If the input is known to be positive (the sign bit is known clear),
2162 // the output of the NEG has the same number of sign bits as the input.
2163 if (KnownZero.isNegative())
2164 return Tmp2;
2165
2166 // Otherwise, we treat this like a SUB.
2167 }
2168
2169 // Sub can have at most one carry bit. Thus we know that the output
2170 // is, at worst, one more bit than the inputs.
2171 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2172 if (Tmp == 1) return 1; // Early out.
2173 return std::min(Tmp, Tmp2)-1;
2174 break;
2175 case Instruction::Trunc:
2176 // FIXME: it's tricky to do anything useful for this, but it is an important
2177 // case for targets like X86.
2178 break;
2179 }
2180
2181 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2182 // use this information.
2183 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2184 APInt Mask = APInt::getAllOnesValue(TyBits);
2185 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2186
2187 if (KnownZero.isNegative()) { // sign bit is 0
2188 Mask = KnownZero;
2189 } else if (KnownOne.isNegative()) { // sign bit is 1;
2190 Mask = KnownOne;
2191 } else {
2192 // Nothing known.
2193 return 1;
2194 }
2195
2196 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2197 // the number of identical bits in the top of the input value.
2198 Mask = ~Mask;
2199 Mask <<= Mask.getBitWidth()-TyBits;
2200 // Return # leading zeros. We use 'min' here in case Val was zero before
2201 // shifting. We don't want to return '64' as for an i32 "0".
2202 return std::min(TyBits, Mask.countLeadingZeros());
2203}
2204
2205
Chris Lattner564a7272003-08-13 19:01:45 +00002206/// AssociativeOpt - Perform an optimization on an associative operator. This
2207/// function is designed to check a chain of associative operators for a
2208/// potential to apply a certain optimization. Since the optimization may be
2209/// applicable if the expression was reassociated, this checks the chain, then
2210/// reassociates the expression as necessary to expose the optimization
2211/// opportunity. This makes use of a special Functor, which must define
2212/// 'shouldApply' and 'apply' methods.
2213///
2214template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002215static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002216 unsigned Opcode = Root.getOpcode();
2217 Value *LHS = Root.getOperand(0);
2218
2219 // Quick check, see if the immediate LHS matches...
2220 if (F.shouldApply(LHS))
2221 return F.apply(Root);
2222
2223 // Otherwise, if the LHS is not of the same opcode as the root, return.
2224 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002225 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002226 // Should we apply this transform to the RHS?
2227 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2228
2229 // If not to the RHS, check to see if we should apply to the LHS...
2230 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2231 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2232 ShouldApply = true;
2233 }
2234
2235 // If the functor wants to apply the optimization to the RHS of LHSI,
2236 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2237 if (ShouldApply) {
2238 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002239
Chris Lattner564a7272003-08-13 19:01:45 +00002240 // Now all of the instructions are in the current basic block, go ahead
2241 // and perform the reassociation.
2242 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2243
2244 // First move the selected RHS to the LHS of the root...
2245 Root.setOperand(0, LHSI->getOperand(1));
2246
2247 // Make what used to be the LHS of the root be the user of the root...
2248 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002249 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002250 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2251 return 0;
2252 }
Chris Lattner65725312004-04-16 18:08:07 +00002253 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002254 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002255 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2256 BasicBlock::iterator ARI = &Root; ++ARI;
2257 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2258 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002259
2260 // Now propagate the ExtraOperand down the chain of instructions until we
2261 // get to LHSI.
2262 while (TmpLHSI != LHSI) {
2263 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002264 // Move the instruction to immediately before the chain we are
2265 // constructing to avoid breaking dominance properties.
2266 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2267 BB->getInstList().insert(ARI, NextLHSI);
2268 ARI = NextLHSI;
2269
Chris Lattner564a7272003-08-13 19:01:45 +00002270 Value *NextOp = NextLHSI->getOperand(1);
2271 NextLHSI->setOperand(1, ExtraOperand);
2272 TmpLHSI = NextLHSI;
2273 ExtraOperand = NextOp;
2274 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002275
Chris Lattner564a7272003-08-13 19:01:45 +00002276 // Now that the instructions are reassociated, have the functor perform
2277 // the transformation...
2278 return F.apply(Root);
2279 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002280
Chris Lattner564a7272003-08-13 19:01:45 +00002281 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2282 }
2283 return 0;
2284}
2285
Dan Gohman844731a2008-05-13 00:00:25 +00002286namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002287
2288// AddRHS - Implements: X + X --> X << 1
2289struct AddRHS {
2290 Value *RHS;
2291 AddRHS(Value *rhs) : RHS(rhs) {}
2292 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2293 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002294 return BinaryOperator::CreateShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002295 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002296 }
2297};
2298
2299// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2300// iff C1&C2 == 0
2301struct AddMaskingAnd {
2302 Constant *C2;
2303 AddMaskingAnd(Constant *c) : C2(c) {}
2304 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002305 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002306 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002307 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002308 }
2309 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002310 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002311 }
2312};
2313
Dan Gohman844731a2008-05-13 00:00:25 +00002314}
2315
Chris Lattner6e7ba452005-01-01 16:22:27 +00002316static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002317 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002318 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002319 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002320 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002321
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002322 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002323 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002324 }
2325
Chris Lattner2eefe512004-04-09 19:05:30 +00002326 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002327 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2328 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002329
Chris Lattner2eefe512004-04-09 19:05:30 +00002330 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2331 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002332 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2333 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002334 }
2335
2336 Value *Op0 = SO, *Op1 = ConstOperand;
2337 if (!ConstIsRHS)
2338 std::swap(Op0, Op1);
2339 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002340 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002341 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002342 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002343 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002344 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002345 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002346 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002347 abort();
2348 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002349 return IC->InsertNewInstBefore(New, I);
2350}
2351
2352// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2353// constant as the other operand, try to fold the binary operator into the
2354// select arguments. This also works for Cast instructions, which obviously do
2355// not have a second operand.
2356static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2357 InstCombiner *IC) {
2358 // Don't modify shared select instructions
2359 if (!SI->hasOneUse()) return 0;
2360 Value *TV = SI->getOperand(1);
2361 Value *FV = SI->getOperand(2);
2362
2363 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002364 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002365 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002366
Chris Lattner6e7ba452005-01-01 16:22:27 +00002367 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2368 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2369
Gabor Greif051a9502008-04-06 20:25:17 +00002370 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2371 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002372 }
2373 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002374}
2375
Chris Lattner4e998b22004-09-29 05:07:12 +00002376
2377/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2378/// node as operand #0, see if we can fold the instruction into the PHI (which
2379/// is only possible if all operands to the PHI are constants).
2380Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2381 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002382 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002383 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002384
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002385 // Check to see if all of the operands of the PHI are constants. If there is
2386 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002387 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002388 BasicBlock *NonConstBB = 0;
2389 for (unsigned i = 0; i != NumPHIValues; ++i)
2390 if (!isa<Constant>(PN->getIncomingValue(i))) {
2391 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002392 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002393 NonConstBB = PN->getIncomingBlock(i);
2394
2395 // If the incoming non-constant value is in I's block, we have an infinite
2396 // loop.
2397 if (NonConstBB == I.getParent())
2398 return 0;
2399 }
2400
2401 // If there is exactly one non-constant value, we can insert a copy of the
2402 // operation in that block. However, if this is a critical edge, we would be
2403 // inserting the computation one some other paths (e.g. inside a loop). Only
2404 // do this if the pred block is unconditionally branching into the phi block.
2405 if (NonConstBB) {
2406 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2407 if (!BI || !BI->isUnconditional()) return 0;
2408 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002409
2410 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002411 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002412 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002413 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002414 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002415
2416 // Next, add all of the operands to the PHI.
2417 if (I.getNumOperands() == 2) {
2418 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002419 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002420 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002421 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002422 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2423 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2424 else
2425 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002426 } else {
2427 assert(PN->getIncomingBlock(i) == NonConstBB);
2428 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002429 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002430 PN->getIncomingValue(i), C, "phitmp",
2431 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002432 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002433 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002434 CI->getPredicate(),
2435 PN->getIncomingValue(i), C, "phitmp",
2436 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002437 else
2438 assert(0 && "Unknown binop!");
2439
Chris Lattnerdbab3862007-03-02 21:28:56 +00002440 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002441 }
2442 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002443 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002444 } else {
2445 CastInst *CI = cast<CastInst>(&I);
2446 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002447 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002448 Value *InV;
2449 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002450 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002451 } else {
2452 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002453 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002454 I.getType(), "phitmp",
2455 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002456 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002457 }
2458 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002459 }
2460 }
2461 return ReplaceInstUsesWith(I, NewPN);
2462}
2463
Chris Lattner2454a2e2008-01-29 06:52:45 +00002464
2465/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2466/// value is never equal to -0.0.
2467///
2468/// Note that this function will need to be revisited when we support nondefault
2469/// rounding modes!
2470///
2471static bool CannotBeNegativeZero(const Value *V) {
2472 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2473 return !CFP->getValueAPF().isNegZero();
2474
Chris Lattner2454a2e2008-01-29 06:52:45 +00002475 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002476 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002477 if (I->getOpcode() == Instruction::Add &&
2478 isa<ConstantFP>(I->getOperand(1)) &&
2479 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2480 return true;
2481
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002482 // sitofp and uitofp turn into +0.0 for zero.
2483 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2484 return true;
2485
Chris Lattner2454a2e2008-01-29 06:52:45 +00002486 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2487 if (II->getIntrinsicID() == Intrinsic::sqrt)
2488 return CannotBeNegativeZero(II->getOperand(1));
2489
2490 if (const CallInst *CI = dyn_cast<CallInst>(I))
2491 if (const Function *F = CI->getCalledFunction()) {
2492 if (F->isDeclaration()) {
2493 switch (F->getNameLen()) {
2494 case 3: // abs(x) != -0.0
2495 if (!strcmp(F->getNameStart(), "abs")) return true;
2496 break;
2497 case 4: // abs[lf](x) != -0.0
2498 if (!strcmp(F->getNameStart(), "absf")) return true;
2499 if (!strcmp(F->getNameStart(), "absl")) return true;
2500 break;
2501 }
2502 }
2503 }
2504 }
2505
2506 return false;
2507}
2508
2509
Chris Lattner7e708292002-06-25 16:13:24 +00002510Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002511 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002512 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002513
Chris Lattner66331a42004-04-10 22:01:55 +00002514 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002515 // X + undef -> undef
2516 if (isa<UndefValue>(RHS))
2517 return ReplaceInstUsesWith(I, RHS);
2518
Chris Lattner66331a42004-04-10 22:01:55 +00002519 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002520 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002521 if (RHSC->isNullValue())
2522 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002523 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002524 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2525 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002526 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002527 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002528
Chris Lattner66331a42004-04-10 22:01:55 +00002529 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002530 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002531 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002532 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002533 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002534 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002535
2536 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2537 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002538 if (!isa<VectorType>(I.getType())) {
2539 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2540 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2541 KnownZero, KnownOne))
2542 return &I;
2543 }
Chris Lattner66331a42004-04-10 22:01:55 +00002544 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002545
2546 if (isa<PHINode>(LHS))
2547 if (Instruction *NV = FoldOpIntoPhi(I))
2548 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002549
Chris Lattner4f637d42006-01-06 17:59:59 +00002550 ConstantInt *XorRHS = 0;
2551 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002552 if (isa<ConstantInt>(RHSC) &&
2553 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002554 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002555 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002556
Zhou Sheng4351c642007-04-02 08:20:41 +00002557 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002558 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2559 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002560 do {
2561 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002562 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2563 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002564 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2565 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002566 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002567 if (!MaskedValueIsZero(XorLHS,
2568 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002569 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002570 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002571 }
2572 }
2573 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002574 C0080Val = APIntOps::lshr(C0080Val, Size);
2575 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2576 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002577
Reid Spencer35c38852007-03-28 01:36:16 +00002578 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002579 // with funny bit widths then this switch statement should be removed. It
2580 // is just here to get the size of the "middle" type back up to something
2581 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002582 const Type *MiddleType = 0;
2583 switch (Size) {
2584 default: break;
2585 case 32: MiddleType = Type::Int32Ty; break;
2586 case 16: MiddleType = Type::Int16Ty; break;
2587 case 8: MiddleType = Type::Int8Ty; break;
2588 }
2589 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002590 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002591 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002592 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002593 }
2594 }
Chris Lattner66331a42004-04-10 22:01:55 +00002595 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002596
Chris Lattner564a7272003-08-13 19:01:45 +00002597 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002598 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002599 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002600
2601 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2602 if (RHSI->getOpcode() == Instruction::Sub)
2603 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2604 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2605 }
2606 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2607 if (LHSI->getOpcode() == Instruction::Sub)
2608 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2609 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2610 }
Robert Bocchino71698282004-07-27 21:02:21 +00002611 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002612
Chris Lattner5c4afb92002-05-08 22:46:53 +00002613 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002614 // -A + -B --> -(A + B)
2615 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002616 if (LHS->getType()->isIntOrIntVector()) {
2617 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002618 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002619 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002620 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002621 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002622 }
2623
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002624 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002625 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002626
2627 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002628 if (!isa<Constant>(RHS))
2629 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002630 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002631
Misha Brukmanfd939082005-04-21 23:48:37 +00002632
Chris Lattner50af16a2004-11-13 19:50:12 +00002633 ConstantInt *C2;
2634 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2635 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002636 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002637
2638 // X*C1 + X*C2 --> X * (C1+C2)
2639 ConstantInt *C1;
2640 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002641 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002642 }
2643
2644 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002645 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002646 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002647
Chris Lattnere617c9e2007-01-05 02:17:46 +00002648 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002649 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2650 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002651
Chris Lattnerad3448c2003-02-18 19:57:07 +00002652
Chris Lattner564a7272003-08-13 19:01:45 +00002653 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002654 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002655 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2656 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002657
2658 // A+B --> A|B iff A and B have no bits set in common.
2659 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2660 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2661 APInt LHSKnownOne(IT->getBitWidth(), 0);
2662 APInt LHSKnownZero(IT->getBitWidth(), 0);
2663 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2664 if (LHSKnownZero != 0) {
2665 APInt RHSKnownOne(IT->getBitWidth(), 0);
2666 APInt RHSKnownZero(IT->getBitWidth(), 0);
2667 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2668
2669 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002670 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002671 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002672 }
2673 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002674
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002675 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002676 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002677 Value *W, *X, *Y, *Z;
2678 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2679 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2680 if (W != Y) {
2681 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002682 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002683 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002684 std::swap(W, X);
2685 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002686 std::swap(Y, Z);
2687 std::swap(W, X);
2688 }
2689 }
2690
2691 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002692 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002693 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002694 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002695 }
2696 }
2697 }
2698
Chris Lattner6b032052003-10-02 15:11:26 +00002699 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002700 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002701 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002702 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002703
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002704 // (X & FF00) + xx00 -> (X+xx00) & FF00
2705 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002706 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002707 if (Anded == CRHS) {
2708 // See if all bits from the first bit set in the Add RHS up are included
2709 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002710 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002711
2712 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002713 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002714
2715 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002716 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002717
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002718 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2719 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002720 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002721 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002722 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002723 }
2724 }
2725 }
2726
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002727 // Try to fold constant add into select arguments.
2728 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002729 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002730 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002731 }
2732
Reid Spencer1628cec2006-10-26 06:15:43 +00002733 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002734 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002735 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002736 CastInst *CI = dyn_cast<CastInst>(LHS);
2737 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002738 if (!CI) {
2739 CI = dyn_cast<CastInst>(RHS);
2740 Other = LHS;
2741 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002742 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002743 (CI->getType()->getPrimitiveSizeInBits() ==
2744 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002745 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002746 unsigned AS =
2747 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002748 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2749 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002750 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002751 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002752 }
2753 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002754
Chris Lattner42790482007-12-20 01:56:58 +00002755 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002756 {
2757 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2758 Value *Other = RHS;
2759 if (!SI) {
2760 SI = dyn_cast<SelectInst>(RHS);
2761 Other = LHS;
2762 }
Chris Lattner42790482007-12-20 01:56:58 +00002763 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002764 Value *TV = SI->getTrueValue();
2765 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002766 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002767
2768 // Can we fold the add into the argument of the select?
2769 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002770 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2771 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002772 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002773 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2774 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002775 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002776 }
2777 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002778
2779 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2780 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2781 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2782 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002783
Chris Lattner7e708292002-06-25 16:13:24 +00002784 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002785}
2786
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002787// isSignBit - Return true if the value represented by the constant only has the
2788// highest order bit set.
2789static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002790 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002791 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002792}
2793
Chris Lattner7e708292002-06-25 16:13:24 +00002794Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002795 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002796
Chris Lattner233f7dc2002-08-12 21:17:25 +00002797 if (Op0 == Op1) // sub X, X -> 0
2798 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002799
Chris Lattner233f7dc2002-08-12 21:17:25 +00002800 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002801 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002802 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002803
Chris Lattnere87597f2004-10-16 18:11:37 +00002804 if (isa<UndefValue>(Op0))
2805 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2806 if (isa<UndefValue>(Op1))
2807 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2808
Chris Lattnerd65460f2003-11-05 01:06:05 +00002809 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2810 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002811 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002812 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002813
Chris Lattnerd65460f2003-11-05 01:06:05 +00002814 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002815 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002816 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002817 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002818
Chris Lattner76b7a062007-01-15 07:02:54 +00002819 // -(X >>u 31) -> (X >>s 31)
2820 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002821 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002822 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002823 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002824 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002825 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002826 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002827 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002828 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002829 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002830 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002831 }
2832 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002833 }
2834 else if (SI->getOpcode() == Instruction::AShr) {
2835 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2836 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002837 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002838 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002839 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002840 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002841 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002842 }
2843 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002844 }
2845 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002846 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002847
2848 // Try to fold constant sub into select arguments.
2849 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002850 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002851 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002852
2853 if (isa<PHINode>(Op0))
2854 if (Instruction *NV = FoldOpIntoPhi(I))
2855 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002856 }
2857
Chris Lattner43d84d62005-04-07 16:15:25 +00002858 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2859 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002860 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002861 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002862 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002863 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002864 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002865 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2866 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2867 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002868 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002869 Op1I->getOperand(0));
2870 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002871 }
2872
Chris Lattnerfd059242003-10-15 16:48:29 +00002873 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002874 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2875 // is not used by anyone else...
2876 //
Chris Lattner0517e722004-02-02 20:09:56 +00002877 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002878 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002879 // Swap the two operands of the subexpr...
2880 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2881 Op1I->setOperand(0, IIOp1);
2882 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002883
Chris Lattnera2881962003-02-18 19:28:33 +00002884 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002885 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002886 }
2887
2888 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2889 //
2890 if (Op1I->getOpcode() == Instruction::And &&
2891 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2892 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2893
Chris Lattnerf523d062004-06-09 05:08:07 +00002894 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002895 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2896 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002897 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002898
Reid Spencerac5209e2006-10-16 23:08:08 +00002899 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002900 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002901 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002902 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002903 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002904 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002905 ConstantExpr::getNeg(DivRHS));
2906
Chris Lattnerad3448c2003-02-18 19:57:07 +00002907 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002908 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002909 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002910 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002911 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002912 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002913
2914 // X - ((X / Y) * Y) --> X % Y
2915 if (Op1I->getOpcode() == Instruction::Mul)
2916 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2917 if (Op0 == I->getOperand(0) &&
2918 Op1I->getOperand(1) == I->getOperand(1)) {
2919 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002920 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002921 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002922 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002923 }
Chris Lattner40371712002-05-09 01:29:19 +00002924 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002925 }
Chris Lattnera2881962003-02-18 19:28:33 +00002926
Chris Lattner9919e3d2006-12-02 00:13:08 +00002927 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002928 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002929 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002930 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2931 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2932 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2933 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002934 } else if (Op0I->getOpcode() == Instruction::Sub) {
2935 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002936 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002937 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002938 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002939
Chris Lattner50af16a2004-11-13 19:50:12 +00002940 ConstantInt *C1;
2941 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002942 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002943 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002944
Chris Lattner50af16a2004-11-13 19:50:12 +00002945 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2946 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002947 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002948 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002949 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002950}
2951
Chris Lattnera0141b92007-07-15 20:42:37 +00002952/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2953/// comparison only checks the sign bit. If it only checks the sign bit, set
2954/// TrueIfSigned if the result of the comparison is true when the input value is
2955/// signed.
2956static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2957 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002958 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002959 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2960 TrueIfSigned = true;
2961 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002962 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2963 TrueIfSigned = true;
2964 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002965 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2966 TrueIfSigned = false;
2967 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002968 case ICmpInst::ICMP_UGT:
2969 // True if LHS u> RHS and RHS == high-bit-mask - 1
2970 TrueIfSigned = true;
2971 return RHS->getValue() ==
2972 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2973 case ICmpInst::ICMP_UGE:
2974 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2975 TrueIfSigned = true;
2976 return RHS->getValue() ==
2977 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002978 default:
2979 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002980 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002981}
2982
Chris Lattner7e708292002-06-25 16:13:24 +00002983Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002984 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002985 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002986
Chris Lattnere87597f2004-10-16 18:11:37 +00002987 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2988 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2989
Chris Lattner233f7dc2002-08-12 21:17:25 +00002990 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002991 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2992 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002993
2994 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002995 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002996 if (SI->getOpcode() == Instruction::Shl)
2997 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002998 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002999 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003000
Zhou Sheng843f07672007-04-19 05:39:12 +00003001 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003002 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3003 if (CI->equalsInt(1)) // X * 1 == X
3004 return ReplaceInstUsesWith(I, Op0);
3005 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003006 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003007
Zhou Sheng97b52c22007-03-29 01:57:21 +00003008 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003009 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003010 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003011 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003012 }
Robert Bocchino71698282004-07-27 21:02:21 +00003013 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003014 if (Op1F->isNullValue())
3015 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003016
Chris Lattnera2881962003-02-18 19:28:33 +00003017 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3018 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003019 // We need a better interface for long double here.
3020 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3021 if (Op1F->isExactlyValue(1.0))
3022 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003023 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003024
3025 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3026 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003027 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003028 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003029 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003030 Op1, "tmp");
3031 InsertNewInstBefore(Add, I);
3032 Value *C1C2 = ConstantExpr::getMul(Op1,
3033 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003035
3036 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003037
3038 // Try to fold constant mul into select arguments.
3039 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003040 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003041 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003042
3043 if (isa<PHINode>(Op0))
3044 if (Instruction *NV = FoldOpIntoPhi(I))
3045 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003046 }
3047
Chris Lattnera4f445b2003-03-10 23:23:04 +00003048 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3049 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003050 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003051
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003052 // If one of the operands of the multiply is a cast from a boolean value, then
3053 // we know the bool is either zero or one, so this is a 'masking' multiply.
3054 // See if we can simplify things based on how the boolean was originally
3055 // formed.
3056 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003057 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003058 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003059 BoolCast = CI;
3060 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003061 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003062 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003063 BoolCast = CI;
3064 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003065 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003066 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3067 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003068 bool TIS = false;
3069
Reid Spencere4d87aa2006-12-23 06:05:41 +00003070 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003071 // multiply into a shift/and combination.
3072 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003073 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3074 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003075 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003076 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003077 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003078 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003079 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003080 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003081 BoolCast->getOperand(0)->getName()+
3082 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003083
3084 // If the multiply type is not the same as the source type, sign extend
3085 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003086 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003087 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3088 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003089 Instruction::CastOps opcode =
3090 (SrcBits == DstBits ? Instruction::BitCast :
3091 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3092 V = InsertCastBefore(opcode, V, I.getType(), I);
3093 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003094
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003095 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003096 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003097 }
3098 }
3099 }
3100
Chris Lattner7e708292002-06-25 16:13:24 +00003101 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003102}
3103
Reid Spencer1628cec2006-10-26 06:15:43 +00003104/// This function implements the transforms on div instructions that work
3105/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3106/// used by the visitors to those instructions.
3107/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003108Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003109 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003110
Chris Lattner50b2ca42008-02-19 06:12:18 +00003111 // undef / X -> 0 for integer.
3112 // undef / X -> undef for FP (the undef could be a snan).
3113 if (isa<UndefValue>(Op0)) {
3114 if (Op0->getType()->isFPOrFPVector())
3115 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003116 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003117 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003118
3119 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003120 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003121 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003122
Chris Lattner25feae52008-01-28 00:58:18 +00003123 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3124 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003125 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003126 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3127 // the same basic block, then we replace the select with Y, and the
3128 // condition of the select with false (if the cond value is in the same BB).
3129 // If the select has uses other than the div, this allows them to be
3130 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3131 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003132 if (ST->isNullValue()) {
3133 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3134 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003135 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003136 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3137 I.setOperand(1, SI->getOperand(2));
3138 else
3139 UpdateValueUsesWith(SI, SI->getOperand(2));
3140 return &I;
3141 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003142
Chris Lattner25feae52008-01-28 00:58:18 +00003143 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3144 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003145 if (ST->isNullValue()) {
3146 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3147 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003148 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003149 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3150 I.setOperand(1, SI->getOperand(1));
3151 else
3152 UpdateValueUsesWith(SI, SI->getOperand(1));
3153 return &I;
3154 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003155 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003156
Reid Spencer1628cec2006-10-26 06:15:43 +00003157 return 0;
3158}
Misha Brukmanfd939082005-04-21 23:48:37 +00003159
Reid Spencer1628cec2006-10-26 06:15:43 +00003160/// This function implements the transforms common to both integer division
3161/// instructions (udiv and sdiv). It is called by the visitors to those integer
3162/// division instructions.
3163/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003164Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3166
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003167 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3168 if (Op0 == Op1)
3169 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3170
Reid Spencer1628cec2006-10-26 06:15:43 +00003171 if (Instruction *Common = commonDivTransforms(I))
3172 return Common;
3173
3174 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3175 // div X, 1 == X
3176 if (RHS->equalsInt(1))
3177 return ReplaceInstUsesWith(I, Op0);
3178
3179 // (X / C1) / C2 -> X / (C1*C2)
3180 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3181 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3182 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003183 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3184 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3185 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003186 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003187 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003188 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003189
Reid Spencerbca0e382007-03-23 20:05:17 +00003190 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003191 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3192 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3193 return R;
3194 if (isa<PHINode>(Op0))
3195 if (Instruction *NV = FoldOpIntoPhi(I))
3196 return NV;
3197 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003198 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003199
Chris Lattnera2881962003-02-18 19:28:33 +00003200 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003201 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003202 if (LHS->equalsInt(0))
3203 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3204
Reid Spencer1628cec2006-10-26 06:15:43 +00003205 return 0;
3206}
3207
3208Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3210
3211 // Handle the integer div common cases
3212 if (Instruction *Common = commonIDivTransforms(I))
3213 return Common;
3214
3215 // X udiv C^2 -> X >> C
3216 // Check to see if this is an unsigned division with an exact power of 2,
3217 // if so, convert to a right shift.
3218 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003219 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003220 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003221 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003222 }
3223
3224 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003225 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003226 if (RHSI->getOpcode() == Instruction::Shl &&
3227 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003228 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003229 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003230 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003231 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003232 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003233 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003234 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003235 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003236 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003237 }
3238 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003239 }
3240
Reid Spencer1628cec2006-10-26 06:15:43 +00003241 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3242 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003243 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003244 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003245 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003246 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003247 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003248 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003249 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003250 // Construct the "on true" case of the select
3251 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003252 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003253 Op0, TC, SI->getName()+".t");
3254 TSI = InsertNewInstBefore(TSI, I);
3255
3256 // Construct the "on false" case of the select
3257 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003258 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003259 Op0, FC, SI->getName()+".f");
3260 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003261
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003262 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003263 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003264 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003265 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003266 return 0;
3267}
3268
Reid Spencer1628cec2006-10-26 06:15:43 +00003269Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3271
3272 // Handle the integer div common cases
3273 if (Instruction *Common = commonIDivTransforms(I))
3274 return Common;
3275
3276 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3277 // sdiv X, -1 == -X
3278 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003279 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003280
3281 // -X/C -> X/-C
3282 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003283 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003284 }
3285
3286 // If the sign bits of both operands are zero (i.e. we can prove they are
3287 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003288 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003289 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003290 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003291 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003292 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003293 }
3294 }
3295
3296 return 0;
3297}
3298
3299Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3300 return commonDivTransforms(I);
3301}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003302
Reid Spencer0a783f72006-11-02 01:53:59 +00003303/// This function implements the transforms on rem instructions that work
3304/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3305/// is used by the visitors to those instructions.
3306/// @brief Transforms common to all three rem instructions
3307Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003308 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003309
Chris Lattner50b2ca42008-02-19 06:12:18 +00003310 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003311 if (Constant *LHS = dyn_cast<Constant>(Op0))
3312 if (LHS->isNullValue())
3313 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3314
Chris Lattner50b2ca42008-02-19 06:12:18 +00003315 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3316 if (I.getType()->isFPOrFPVector())
3317 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003318 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003319 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003320 if (isa<UndefValue>(Op1))
3321 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003322
3323 // Handle cases involving: rem X, (select Cond, Y, Z)
3324 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3325 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3326 // the same basic block, then we replace the select with Y, and the
3327 // condition of the select with false (if the cond value is in the same
3328 // BB). If the select has uses other than the div, this allows them to be
3329 // simplified also.
3330 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3331 if (ST->isNullValue()) {
3332 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3333 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003334 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003335 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3336 I.setOperand(1, SI->getOperand(2));
3337 else
3338 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003339 return &I;
3340 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003341 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3342 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3343 if (ST->isNullValue()) {
3344 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3345 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003346 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003347 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3348 I.setOperand(1, SI->getOperand(1));
3349 else
3350 UpdateValueUsesWith(SI, SI->getOperand(1));
3351 return &I;
3352 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003353 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003354
Reid Spencer0a783f72006-11-02 01:53:59 +00003355 return 0;
3356}
3357
3358/// This function implements the transforms common to both integer remainder
3359/// instructions (urem and srem). It is called by the visitors to those integer
3360/// remainder instructions.
3361/// @brief Common integer remainder transforms
3362Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3364
3365 if (Instruction *common = commonRemTransforms(I))
3366 return common;
3367
Chris Lattner857e8cd2004-12-12 21:48:58 +00003368 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003369 // X % 0 == undef, we don't need to preserve faults!
3370 if (RHS->equalsInt(0))
3371 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3372
Chris Lattnera2881962003-02-18 19:28:33 +00003373 if (RHS->equalsInt(1)) // X % 1 == 0
3374 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3375
Chris Lattner97943922006-02-28 05:49:21 +00003376 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3377 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3378 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3379 return R;
3380 } else if (isa<PHINode>(Op0I)) {
3381 if (Instruction *NV = FoldOpIntoPhi(I))
3382 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003383 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003384
3385 // See if we can fold away this rem instruction.
3386 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3387 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3388 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3389 KnownZero, KnownOne))
3390 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003391 }
Chris Lattnera2881962003-02-18 19:28:33 +00003392 }
3393
Reid Spencer0a783f72006-11-02 01:53:59 +00003394 return 0;
3395}
3396
3397Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3398 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3399
3400 if (Instruction *common = commonIRemTransforms(I))
3401 return common;
3402
3403 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3404 // X urem C^2 -> X and C
3405 // Check to see if this is an unsigned remainder with an exact power of 2,
3406 // if so, convert to a bitwise and.
3407 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003408 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003409 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003410 }
3411
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003412 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003413 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3414 if (RHSI->getOpcode() == Instruction::Shl &&
3415 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003416 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003417 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003418 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003419 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003420 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003421 }
3422 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003423 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003424
Reid Spencer0a783f72006-11-02 01:53:59 +00003425 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3426 // where C1&C2 are powers of two.
3427 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3428 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3429 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3430 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003431 if ((STO->getValue().isPowerOf2()) &&
3432 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003433 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003434 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003435 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003436 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003437 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003438 }
3439 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003440 }
3441
Chris Lattner3f5b8772002-05-06 16:14:14 +00003442 return 0;
3443}
3444
Reid Spencer0a783f72006-11-02 01:53:59 +00003445Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3446 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3447
Dan Gohmancff55092007-11-05 23:16:33 +00003448 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003449 if (Instruction *common = commonIRemTransforms(I))
3450 return common;
3451
3452 if (Value *RHSNeg = dyn_castNegVal(Op1))
3453 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003454 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003455 // X % -Y -> X % Y
3456 AddUsesToWorkList(I);
3457 I.setOperand(1, RHSNeg);
3458 return &I;
3459 }
3460
Dan Gohmancff55092007-11-05 23:16:33 +00003461 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003462 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003463 if (I.getType()->isInteger()) {
3464 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3465 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3466 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003467 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003468 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003469 }
3470
3471 return 0;
3472}
3473
3474Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003475 return commonRemTransforms(I);
3476}
3477
Chris Lattner8b170942002-08-09 23:47:40 +00003478// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003480 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003481 if (!isSigned)
3482 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3483 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003484}
3485
3486// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003487static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003488 if (!isSigned)
3489 return C->getValue() == 1; // unsigned
3490
3491 // Calculate 1111111111000000000000
3492 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3493 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003494}
3495
Chris Lattner457dd822004-06-09 07:59:58 +00003496// isOneBitSet - Return true if there is exactly one bit set in the specified
3497// constant.
3498static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003499 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003500}
3501
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003502// isHighOnes - Return true if the constant is of the form 1+0+.
3503// This is the same as lowones(~X).
3504static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003505 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003506}
3507
Reid Spencere4d87aa2006-12-23 06:05:41 +00003508/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003509/// are carefully arranged to allow folding of expressions such as:
3510///
3511/// (A < B) | (A > B) --> (A != B)
3512///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003513/// Note that this is only valid if the first and second predicates have the
3514/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003515///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003516/// Three bits are used to represent the condition, as follows:
3517/// 0 A > B
3518/// 1 A == B
3519/// 2 A < B
3520///
3521/// <=> Value Definition
3522/// 000 0 Always false
3523/// 001 1 A > B
3524/// 010 2 A == B
3525/// 011 3 A >= B
3526/// 100 4 A < B
3527/// 101 5 A != B
3528/// 110 6 A <= B
3529/// 111 7 Always true
3530///
3531static unsigned getICmpCode(const ICmpInst *ICI) {
3532 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003533 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003534 case ICmpInst::ICMP_UGT: return 1; // 001
3535 case ICmpInst::ICMP_SGT: return 1; // 001
3536 case ICmpInst::ICMP_EQ: return 2; // 010
3537 case ICmpInst::ICMP_UGE: return 3; // 011
3538 case ICmpInst::ICMP_SGE: return 3; // 011
3539 case ICmpInst::ICMP_ULT: return 4; // 100
3540 case ICmpInst::ICMP_SLT: return 4; // 100
3541 case ICmpInst::ICMP_NE: return 5; // 101
3542 case ICmpInst::ICMP_ULE: return 6; // 110
3543 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003544 // True -> 7
3545 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003546 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003547 return 0;
3548 }
3549}
3550
Reid Spencere4d87aa2006-12-23 06:05:41 +00003551/// getICmpValue - This is the complement of getICmpCode, which turns an
3552/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003553/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003554/// of predicate to use in new icmp instructions.
3555static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3556 switch (code) {
3557 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003558 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003559 case 1:
3560 if (sign)
3561 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3562 else
3563 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3564 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3565 case 3:
3566 if (sign)
3567 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3568 else
3569 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3570 case 4:
3571 if (sign)
3572 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3573 else
3574 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3575 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3576 case 6:
3577 if (sign)
3578 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3579 else
3580 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003581 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003582 }
3583}
3584
Reid Spencere4d87aa2006-12-23 06:05:41 +00003585static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3586 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3587 (ICmpInst::isSignedPredicate(p1) &&
3588 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3589 (ICmpInst::isSignedPredicate(p2) &&
3590 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3591}
3592
3593namespace {
3594// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3595struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003596 InstCombiner &IC;
3597 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003598 ICmpInst::Predicate pred;
3599 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3600 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3601 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003602 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003603 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3604 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003605 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3606 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003607 return false;
3608 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003609 Instruction *apply(Instruction &Log) const {
3610 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3611 if (ICI->getOperand(0) != LHS) {
3612 assert(ICI->getOperand(1) == LHS);
3613 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003614 }
3615
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003616 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003617 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003618 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003619 unsigned Code;
3620 switch (Log.getOpcode()) {
3621 case Instruction::And: Code = LHSCode & RHSCode; break;
3622 case Instruction::Or: Code = LHSCode | RHSCode; break;
3623 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003624 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003625 }
3626
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003627 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3628 ICmpInst::isSignedPredicate(ICI->getPredicate());
3629
3630 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003631 if (Instruction *I = dyn_cast<Instruction>(RV))
3632 return I;
3633 // Otherwise, it's a constant boolean value...
3634 return IC.ReplaceInstUsesWith(Log, RV);
3635 }
3636};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003637} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003638
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003639// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3640// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003641// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003642Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003643 ConstantInt *OpRHS,
3644 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003645 BinaryOperator &TheAnd) {
3646 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003647 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003648 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003649 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003650
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003651 switch (Op->getOpcode()) {
3652 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003653 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003654 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003655 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003656 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003657 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003658 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003659 }
3660 break;
3661 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003662 if (Together == AndRHS) // (X | C) & C --> C
3663 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003664
Chris Lattner6e7ba452005-01-01 16:22:27 +00003665 if (Op->hasOneUse() && Together != OpRHS) {
3666 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003667 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003668 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003669 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003670 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003671 }
3672 break;
3673 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003674 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003675 // Adding a one to a single bit bit-field should be turned into an XOR
3676 // of the bit. First thing to check is to see if this AND is with a
3677 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003678 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003679
3680 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003681 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003682 // Ok, at this point, we know that we are masking the result of the
3683 // ADD down to exactly one bit. If the constant we are adding has
3684 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003685 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003686
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003687 // Check to see if any bits below the one bit set in AndRHSV are set.
3688 if ((AddRHS & (AndRHSV-1)) == 0) {
3689 // If not, the only thing that can effect the output of the AND is
3690 // the bit specified by AndRHSV. If that bit is set, the effect of
3691 // the XOR is to toggle the bit. If it is clear, then the ADD has
3692 // no effect.
3693 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3694 TheAnd.setOperand(0, X);
3695 return &TheAnd;
3696 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003697 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003698 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003699 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003700 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003701 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003702 }
3703 }
3704 }
3705 }
3706 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003707
3708 case Instruction::Shl: {
3709 // We know that the AND will not produce any of the bits shifted in, so if
3710 // the anded constant includes them, clear them now!
3711 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003712 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003713 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003714 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3715 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003716
Zhou Sheng290bec52007-03-29 08:15:12 +00003717 if (CI->getValue() == ShlMask) {
3718 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003719 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3720 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003721 TheAnd.setOperand(1, CI);
3722 return &TheAnd;
3723 }
3724 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003725 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003726 case Instruction::LShr:
3727 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003728 // We know that the AND will not produce any of the bits shifted in, so if
3729 // the anded constant includes them, clear them now! This only applies to
3730 // unsigned shifts, because a signed shr may bring in set bits!
3731 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003732 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003733 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003734 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3735 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003736
Zhou Sheng290bec52007-03-29 08:15:12 +00003737 if (CI->getValue() == ShrMask) {
3738 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003739 return ReplaceInstUsesWith(TheAnd, Op);
3740 } else if (CI != AndRHS) {
3741 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3742 return &TheAnd;
3743 }
3744 break;
3745 }
3746 case Instruction::AShr:
3747 // Signed shr.
3748 // See if this is shifting in some sign extension, then masking it out
3749 // with an and.
3750 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003751 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003752 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003753 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3754 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003755 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003756 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003757 // Make the argument unsigned.
3758 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003759 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003760 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003761 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003762 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003763 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003764 }
3765 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003766 }
3767 return 0;
3768}
3769
Chris Lattner8b170942002-08-09 23:47:40 +00003770
Chris Lattnera96879a2004-09-29 17:40:11 +00003771/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3772/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003773/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3774/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003775/// insert new instructions.
3776Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003777 bool isSigned, bool Inside,
3778 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003779 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003780 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003781 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003782
Chris Lattnera96879a2004-09-29 17:40:11 +00003783 if (Inside) {
3784 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003785 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003786
Reid Spencere4d87aa2006-12-23 06:05:41 +00003787 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003788 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003789 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3791 return new ICmpInst(pred, V, Hi);
3792 }
3793
3794 // Emit V-Lo <u Hi-Lo
3795 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003796 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003797 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003798 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3799 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003800 }
3801
3802 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003803 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003804
Reid Spencere4e40032007-03-21 23:19:50 +00003805 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003806 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003807 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003808 ICmpInst::Predicate pred = (isSigned ?
3809 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3810 return new ICmpInst(pred, V, Hi);
3811 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003812
Reid Spencere4e40032007-03-21 23:19:50 +00003813 // Emit V-Lo >u Hi-1-Lo
3814 // Note that Hi has already had one subtracted from it, above.
3815 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003816 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003817 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003818 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3819 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003820}
3821
Chris Lattner7203e152005-09-18 07:22:02 +00003822// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3823// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3824// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3825// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003826static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003827 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003828 uint32_t BitWidth = Val->getType()->getBitWidth();
3829 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003830
3831 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003832 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003833 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003834 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003835 return true;
3836}
3837
Chris Lattner7203e152005-09-18 07:22:02 +00003838/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3839/// where isSub determines whether the operator is a sub. If we can fold one of
3840/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003841///
3842/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3843/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3844/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3845///
3846/// return (A +/- B).
3847///
3848Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003849 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003850 Instruction &I) {
3851 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3852 if (!LHSI || LHSI->getNumOperands() != 2 ||
3853 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3854
3855 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3856
3857 switch (LHSI->getOpcode()) {
3858 default: return 0;
3859 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003860 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003861 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003862 if ((Mask->getValue().countLeadingZeros() +
3863 Mask->getValue().countPopulation()) ==
3864 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003865 break;
3866
3867 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3868 // part, we don't need any explicit masks to take them out of A. If that
3869 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003870 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003871 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003872 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003873 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003874 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003875 break;
3876 }
3877 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003878 return 0;
3879 case Instruction::Or:
3880 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003881 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003882 if ((Mask->getValue().countLeadingZeros() +
3883 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003884 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003885 break;
3886 return 0;
3887 }
3888
3889 Instruction *New;
3890 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003891 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003892 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003893 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003894 return InsertNewInstBefore(New, I);
3895}
3896
Chris Lattner7e708292002-06-25 16:13:24 +00003897Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003898 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003899 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003900
Chris Lattnere87597f2004-10-16 18:11:37 +00003901 if (isa<UndefValue>(Op1)) // X & undef -> 0
3902 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3903
Chris Lattner6e7ba452005-01-01 16:22:27 +00003904 // and X, X = X
3905 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003906 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003907
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003908 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003909 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003910 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003911 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3912 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3913 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003914 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003915 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003916 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003917 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003918 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003919 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003920 } else if (isa<ConstantAggregateZero>(Op1)) {
3921 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003922 }
3923 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003924
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003925 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003926 const APInt& AndRHSMask = AndRHS->getValue();
3927 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003928
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003929 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003930 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003931 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003932 Value *Op0LHS = Op0I->getOperand(0);
3933 Value *Op0RHS = Op0I->getOperand(1);
3934 switch (Op0I->getOpcode()) {
3935 case Instruction::Xor:
3936 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003937 // If the mask is only needed on one incoming arm, push it up.
3938 if (Op0I->hasOneUse()) {
3939 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3940 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003941 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003942 Op0RHS->getName()+".masked");
3943 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003944 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003945 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003946 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003947 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003948 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3949 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003950 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003951 Op0LHS->getName()+".masked");
3952 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003953 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003954 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3955 }
3956 }
3957
Chris Lattner6e7ba452005-01-01 16:22:27 +00003958 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003959 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003960 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3961 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3962 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3963 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003964 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003965 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003966 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003967 break;
3968
3969 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003970 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3971 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3972 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3973 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003974 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003975 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003976 }
3977
Chris Lattner58403262003-07-23 19:25:52 +00003978 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003979 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003980 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003981 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003982 // If this is an integer truncation or change from signed-to-unsigned, and
3983 // if the source is an and/or with immediate, transform it. This
3984 // frequently occurs for bitfield accesses.
3985 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003986 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003987 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003988 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003989 if (CastOp->getOpcode() == Instruction::And) {
3990 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003991 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3992 // This will fold the two constants together, which may allow
3993 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003994 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003995 CastOp->getOperand(0), I.getType(),
3996 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003997 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003998 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003999 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004000 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004001 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004002 } else if (CastOp->getOpcode() == Instruction::Or) {
4003 // Change: and (cast (or X, C1) to T), C2
4004 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004005 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004006 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4007 return ReplaceInstUsesWith(I, AndRHS);
4008 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004009 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004010 }
Chris Lattner06782f82003-07-23 19:36:21 +00004011 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004012
4013 // Try to fold constant and into select arguments.
4014 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004015 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004016 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004017 if (isa<PHINode>(Op0))
4018 if (Instruction *NV = FoldOpIntoPhi(I))
4019 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004020 }
4021
Chris Lattner8d969642003-03-10 23:06:50 +00004022 Value *Op0NotVal = dyn_castNotVal(Op0);
4023 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004024
Chris Lattner5b62aa72004-06-18 06:07:51 +00004025 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4026 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4027
Misha Brukmancb6267b2004-07-30 12:50:08 +00004028 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004029 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004030 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004031 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004032 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004033 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004034 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004035
4036 {
Chris Lattner003b6202007-06-15 05:58:24 +00004037 Value *A = 0, *B = 0, *C = 0, *D = 0;
4038 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004039 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4040 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004041
4042 // (A|B) & ~(A&B) -> A^B
4043 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4044 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004045 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004046 }
4047 }
4048
4049 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004050 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4051 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004052
4053 // ~(A&B) & (A|B) -> A^B
4054 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4055 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004056 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004057 }
4058 }
Chris Lattner64daab52006-04-01 08:03:55 +00004059
4060 if (Op0->hasOneUse() &&
4061 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4062 if (A == Op1) { // (A^B)&A -> A&(A^B)
4063 I.swapOperands(); // Simplify below
4064 std::swap(Op0, Op1);
4065 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4066 cast<BinaryOperator>(Op0)->swapOperands();
4067 I.swapOperands(); // Simplify below
4068 std::swap(Op0, Op1);
4069 }
4070 }
4071 if (Op1->hasOneUse() &&
4072 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4073 if (B == Op0) { // B&(A^B) -> B&(B^A)
4074 cast<BinaryOperator>(Op1)->swapOperands();
4075 std::swap(A, B);
4076 }
4077 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004078 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004079 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004080 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004081 }
4082 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004083 }
4084
Reid Spencere4d87aa2006-12-23 06:05:41 +00004085 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4086 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4087 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004088 return R;
4089
Chris Lattner955f3312004-09-28 21:48:02 +00004090 Value *LHSVal, *RHSVal;
4091 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004092 ICmpInst::Predicate LHSCC, RHSCC;
4093 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4094 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4095 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4096 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4097 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4098 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4099 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004100 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4101
4102 // Don't try to fold ICMP_SLT + ICMP_ULT.
4103 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4104 ICmpInst::isSignedPredicate(LHSCC) ==
4105 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004106 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004107 ICmpInst::Predicate GT;
4108 if (ICmpInst::isSignedPredicate(LHSCC) ||
4109 (ICmpInst::isEquality(LHSCC) &&
4110 ICmpInst::isSignedPredicate(RHSCC)))
4111 GT = ICmpInst::ICMP_SGT;
4112 else
4113 GT = ICmpInst::ICMP_UGT;
4114
Reid Spencere4d87aa2006-12-23 06:05:41 +00004115 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4116 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004117 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004118 std::swap(LHS, RHS);
4119 std::swap(LHSCst, RHSCst);
4120 std::swap(LHSCC, RHSCC);
4121 }
4122
Reid Spencere4d87aa2006-12-23 06:05:41 +00004123 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004124 // comparing a value against two constants and and'ing the result
4125 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004126 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4127 // (from the FoldICmpLogical check above), that the two constants
4128 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004129 assert(LHSCst != RHSCst && "Compares not folded above?");
4130
4131 switch (LHSCC) {
4132 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004133 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004134 switch (RHSCC) {
4135 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004136 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4137 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4138 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004139 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004140 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4141 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4142 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004143 return ReplaceInstUsesWith(I, LHS);
4144 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004145 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004146 switch (RHSCC) {
4147 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004148 case ICmpInst::ICMP_ULT:
4149 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4150 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4151 break; // (X != 13 & X u< 15) -> no change
4152 case ICmpInst::ICMP_SLT:
4153 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4154 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4155 break; // (X != 13 & X s< 15) -> no change
4156 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4157 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4158 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004159 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004160 case ICmpInst::ICMP_NE:
4161 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004162 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004163 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004164 LHSVal->getName()+".off");
4165 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004166 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4167 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004168 }
4169 break; // (X != 13 & X != 15) -> no change
4170 }
4171 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004172 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004173 switch (RHSCC) {
4174 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004175 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4176 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004177 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004178 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4179 break;
4180 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4181 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004182 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004183 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4184 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004185 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004186 break;
4187 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004188 switch (RHSCC) {
4189 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004190 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4191 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004192 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004193 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4194 break;
4195 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4196 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004197 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004198 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4199 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004200 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004201 break;
4202 case ICmpInst::ICMP_UGT:
4203 switch (RHSCC) {
4204 default: assert(0 && "Unknown integer condition code!");
4205 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4206 return ReplaceInstUsesWith(I, LHS);
4207 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4208 return ReplaceInstUsesWith(I, RHS);
4209 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4210 break;
4211 case ICmpInst::ICMP_NE:
4212 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4213 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4214 break; // (X u> 13 & X != 15) -> no change
4215 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4216 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4217 true, I);
4218 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4219 break;
4220 }
4221 break;
4222 case ICmpInst::ICMP_SGT:
4223 switch (RHSCC) {
4224 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004225 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004226 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4227 return ReplaceInstUsesWith(I, RHS);
4228 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4229 break;
4230 case ICmpInst::ICMP_NE:
4231 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4232 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4233 break; // (X s> 13 & X != 15) -> no change
4234 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4235 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4236 true, I);
4237 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4238 break;
4239 }
4240 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004241 }
4242 }
4243 }
4244
Chris Lattner6fc205f2006-05-05 06:39:07 +00004245 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004246 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4247 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4248 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4249 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004250 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004251 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004252 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4253 I.getType(), TD) &&
4254 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4255 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004256 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004257 Op1C->getOperand(0),
4258 I.getName());
4259 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004260 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004261 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004262 }
Chris Lattnere511b742006-11-14 07:46:50 +00004263
4264 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004265 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4266 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4267 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004268 SI0->getOperand(1) == SI1->getOperand(1) &&
4269 (SI0->hasOneUse() || SI1->hasOneUse())) {
4270 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004271 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004272 SI1->getOperand(0),
4273 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004274 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004275 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004276 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004277 }
4278
Chris Lattner99c65742007-10-24 05:38:08 +00004279 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4280 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4281 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4282 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4283 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4284 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4285 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4286 // If either of the constants are nans, then the whole thing returns
4287 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004288 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004289 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4290 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4291 RHS->getOperand(0));
4292 }
4293 }
4294 }
4295
Chris Lattner7e708292002-06-25 16:13:24 +00004296 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004297}
4298
Chris Lattnerafe91a52006-06-15 19:07:26 +00004299/// CollectBSwapParts - Look to see if the specified value defines a single byte
4300/// in the result. If it does, and if the specified byte hasn't been filled in
4301/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004302static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004303 Instruction *I = dyn_cast<Instruction>(V);
4304 if (I == 0) return true;
4305
4306 // If this is an or instruction, it is an inner node of the bswap.
4307 if (I->getOpcode() == Instruction::Or)
4308 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4309 CollectBSwapParts(I->getOperand(1), ByteValues);
4310
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004311 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004312 // If this is a shift by a constant int, and it is "24", then its operand
4313 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004314 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004315 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004316 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004317 8*(ByteValues.size()-1))
4318 return true;
4319
4320 unsigned DestNo;
4321 if (I->getOpcode() == Instruction::Shl) {
4322 // X << 24 defines the top byte with the lowest of the input bytes.
4323 DestNo = ByteValues.size()-1;
4324 } else {
4325 // X >>u 24 defines the low byte with the highest of the input bytes.
4326 DestNo = 0;
4327 }
4328
4329 // If the destination byte value is already defined, the values are or'd
4330 // together, which isn't a bswap (unless it's an or of the same bits).
4331 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4332 return true;
4333 ByteValues[DestNo] = I->getOperand(0);
4334 return false;
4335 }
4336
4337 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4338 // don't have this.
4339 Value *Shift = 0, *ShiftLHS = 0;
4340 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4341 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4342 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4343 return true;
4344 Instruction *SI = cast<Instruction>(Shift);
4345
4346 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004347 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4348 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004349 return true;
4350
4351 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4352 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004353 if (AndAmt->getValue().getActiveBits() > 64)
4354 return true;
4355 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004356 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004357 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004358 break;
4359 // Unknown mask for bswap.
4360 if (DestByte == ByteValues.size()) return true;
4361
Reid Spencerb83eb642006-10-20 07:07:24 +00004362 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004363 unsigned SrcByte;
4364 if (SI->getOpcode() == Instruction::Shl)
4365 SrcByte = DestByte - ShiftBytes;
4366 else
4367 SrcByte = DestByte + ShiftBytes;
4368
4369 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4370 if (SrcByte != ByteValues.size()-DestByte-1)
4371 return true;
4372
4373 // If the destination byte value is already defined, the values are or'd
4374 // together, which isn't a bswap (unless it's an or of the same bits).
4375 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4376 return true;
4377 ByteValues[DestByte] = SI->getOperand(0);
4378 return false;
4379}
4380
4381/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4382/// If so, insert the new bswap intrinsic and return it.
4383Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004384 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4385 if (!ITy || ITy->getBitWidth() % 16)
4386 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004387
4388 /// ByteValues - For each byte of the result, we keep track of which value
4389 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004390 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004391 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004392
4393 // Try to find all the pieces corresponding to the bswap.
4394 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4395 CollectBSwapParts(I.getOperand(1), ByteValues))
4396 return 0;
4397
4398 // Check to see if all of the bytes come from the same value.
4399 Value *V = ByteValues[0];
4400 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4401
4402 // Check to make sure that all of the bytes come from the same value.
4403 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4404 if (ByteValues[i] != V)
4405 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004406 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004407 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004408 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004409 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004410}
4411
4412
Chris Lattner7e708292002-06-25 16:13:24 +00004413Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004414 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004415 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004416
Chris Lattner42593e62007-03-24 23:56:43 +00004417 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004418 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004419
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004420 // or X, X = X
4421 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004422 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004423
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004424 // See if we can simplify any instructions used by the instruction whose sole
4425 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004426 if (!isa<VectorType>(I.getType())) {
4427 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4428 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4429 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4430 KnownZero, KnownOne))
4431 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004432 } else if (isa<ConstantAggregateZero>(Op1)) {
4433 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4434 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4435 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4436 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004437 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004438
4439
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004440
Chris Lattner3f5b8772002-05-06 16:14:14 +00004441 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004442 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004443 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004444 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4445 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004446 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004447 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004448 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004449 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004450 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004451 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004452
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004453 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4454 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004455 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004456 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004457 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004458 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004459 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004460 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004461
4462 // Try to fold constant and into select arguments.
4463 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004465 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004466 if (isa<PHINode>(Op0))
4467 if (Instruction *NV = FoldOpIntoPhi(I))
4468 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004469 }
4470
Chris Lattner4f637d42006-01-06 17:59:59 +00004471 Value *A = 0, *B = 0;
4472 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004473
4474 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4475 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4476 return ReplaceInstUsesWith(I, Op1);
4477 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4478 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4479 return ReplaceInstUsesWith(I, Op0);
4480
Chris Lattner6423d4c2006-07-10 20:25:24 +00004481 // (A | B) | C and A | (B | C) -> bswap if possible.
4482 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004483 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004484 match(Op1, m_Or(m_Value(), m_Value())) ||
4485 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4486 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004487 if (Instruction *BSwap = MatchBSwap(I))
4488 return BSwap;
4489 }
4490
Chris Lattner6e4c6492005-05-09 04:58:36 +00004491 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4492 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004493 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004494 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004495 InsertNewInstBefore(NOr, I);
4496 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004497 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004498 }
4499
4500 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4501 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004502 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004503 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004504 InsertNewInstBefore(NOr, I);
4505 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004506 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004507 }
4508
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004509 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004510 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004511 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4512 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004513 Value *V1 = 0, *V2 = 0, *V3 = 0;
4514 C1 = dyn_cast<ConstantInt>(C);
4515 C2 = dyn_cast<ConstantInt>(D);
4516 if (C1 && C2) { // (A & C1)|(B & C2)
4517 // If we have: ((V + N) & C1) | (V & C2)
4518 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4519 // replace with V+N.
4520 if (C1->getValue() == ~C2->getValue()) {
4521 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4522 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4523 // Add commutes, try both ways.
4524 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4525 return ReplaceInstUsesWith(I, A);
4526 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4527 return ReplaceInstUsesWith(I, A);
4528 }
4529 // Or commutes, try both ways.
4530 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4531 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4532 // Add commutes, try both ways.
4533 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4534 return ReplaceInstUsesWith(I, B);
4535 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4536 return ReplaceInstUsesWith(I, B);
4537 }
4538 }
Chris Lattner044e5332007-04-08 08:01:49 +00004539 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004540 }
4541
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004542 // Check to see if we have any common things being and'ed. If so, find the
4543 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004544 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4545 if (A == B) // (A & C)|(A & D) == A & (C|D)
4546 V1 = A, V2 = C, V3 = D;
4547 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4548 V1 = A, V2 = B, V3 = C;
4549 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4550 V1 = C, V2 = A, V3 = D;
4551 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4552 V1 = C, V2 = A, V3 = B;
4553
4554 if (V1) {
4555 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004556 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4557 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004558 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004559 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004560 }
Chris Lattnere511b742006-11-14 07:46:50 +00004561
4562 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004563 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4564 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4565 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004566 SI0->getOperand(1) == SI1->getOperand(1) &&
4567 (SI0->hasOneUse() || SI1->hasOneUse())) {
4568 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004569 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004570 SI1->getOperand(0),
4571 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004572 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004573 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004574 }
4575 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004576
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004577 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4578 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004579 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004580 } else {
4581 A = 0;
4582 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004583 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004584 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4585 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004586 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004587
Misha Brukmancb6267b2004-07-30 12:50:08 +00004588 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004589 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004590 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004591 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004592 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004593 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004594 }
Chris Lattnera2881962003-02-18 19:28:33 +00004595
Reid Spencere4d87aa2006-12-23 06:05:41 +00004596 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4597 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4598 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004599 return R;
4600
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004601 Value *LHSVal, *RHSVal;
4602 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004603 ICmpInst::Predicate LHSCC, RHSCC;
4604 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4605 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4606 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4607 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4608 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4609 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4610 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004611 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4612 // We can't fold (ugt x, C) | (sgt x, C2).
4613 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004614 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004615 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004616 bool NeedsSwap;
4617 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004618 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004619 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004620 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004621
4622 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004623 std::swap(LHS, RHS);
4624 std::swap(LHSCst, RHSCst);
4625 std::swap(LHSCC, RHSCC);
4626 }
4627
Reid Spencere4d87aa2006-12-23 06:05:41 +00004628 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004629 // comparing a value against two constants and or'ing the result
4630 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004631 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4632 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004633 // equal.
4634 assert(LHSCst != RHSCst && "Compares not folded above?");
4635
4636 switch (LHSCC) {
4637 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004638 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004639 switch (RHSCC) {
4640 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004641 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004642 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4643 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004644 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004645 LHSVal->getName()+".off");
4646 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004647 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004648 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004649 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004650 break; // (X == 13 | X == 15) -> no change
4651 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4652 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004653 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004654 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4655 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4656 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004657 return ReplaceInstUsesWith(I, RHS);
4658 }
4659 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004660 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004661 switch (RHSCC) {
4662 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004663 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4664 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4665 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004666 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004667 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4668 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4669 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004670 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004671 }
4672 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004673 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004674 switch (RHSCC) {
4675 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004676 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004677 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004678 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004679 // If RHSCst is [us]MAXINT, it is always false. Not handling
4680 // this can cause overflow.
4681 if (RHSCst->isMaxValue(false))
4682 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004683 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4684 false, I);
4685 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4686 break;
4687 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4688 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004689 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004690 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4691 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004692 }
4693 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004694 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004695 switch (RHSCC) {
4696 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004697 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4698 break;
4699 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004700 // If RHSCst is [us]MAXINT, it is always false. Not handling
4701 // this can cause overflow.
4702 if (RHSCst->isMaxValue(true))
4703 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004704 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4705 false, I);
4706 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4707 break;
4708 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4709 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4710 return ReplaceInstUsesWith(I, RHS);
4711 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4712 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004713 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004714 break;
4715 case ICmpInst::ICMP_UGT:
4716 switch (RHSCC) {
4717 default: assert(0 && "Unknown integer condition code!");
4718 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4719 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4720 return ReplaceInstUsesWith(I, LHS);
4721 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4722 break;
4723 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4724 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004725 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004726 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4727 break;
4728 }
4729 break;
4730 case ICmpInst::ICMP_SGT:
4731 switch (RHSCC) {
4732 default: assert(0 && "Unknown integer condition code!");
4733 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4734 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4735 return ReplaceInstUsesWith(I, LHS);
4736 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4737 break;
4738 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4739 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004740 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004741 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4742 break;
4743 }
4744 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004745 }
4746 }
4747 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004748
4749 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004750 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004751 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004752 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004753 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4754 !isa<ICmpInst>(Op1C->getOperand(0))) {
4755 const Type *SrcTy = Op0C->getOperand(0)->getType();
4756 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4757 // Only do this if the casts both really cause code to be
4758 // generated.
4759 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4760 I.getType(), TD) &&
4761 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4762 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004763 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004764 Op1C->getOperand(0),
4765 I.getName());
4766 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004767 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004768 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004769 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004770 }
Chris Lattner99c65742007-10-24 05:38:08 +00004771 }
4772
4773
4774 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4775 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4776 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4777 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004778 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4779 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004780 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4781 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4782 // If either of the constants are nans, then the whole thing returns
4783 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004784 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004785 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4786
4787 // Otherwise, no need to compare the two constants, compare the
4788 // rest.
4789 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4790 RHS->getOperand(0));
4791 }
4792 }
4793 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004794
Chris Lattner7e708292002-06-25 16:13:24 +00004795 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004796}
4797
Dan Gohman844731a2008-05-13 00:00:25 +00004798namespace {
4799
Chris Lattnerc317d392004-02-16 01:20:27 +00004800// XorSelf - Implements: X ^ X --> 0
4801struct XorSelf {
4802 Value *RHS;
4803 XorSelf(Value *rhs) : RHS(rhs) {}
4804 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4805 Instruction *apply(BinaryOperator &Xor) const {
4806 return &Xor;
4807 }
4808};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004809
Dan Gohman844731a2008-05-13 00:00:25 +00004810}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004811
Chris Lattner7e708292002-06-25 16:13:24 +00004812Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004813 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004814 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004815
Evan Chengd34af782008-03-25 20:07:13 +00004816 if (isa<UndefValue>(Op1)) {
4817 if (isa<UndefValue>(Op0))
4818 // Handle undef ^ undef -> 0 special case. This is a common
4819 // idiom (misuse).
4820 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004821 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004822 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004823
Chris Lattnerc317d392004-02-16 01:20:27 +00004824 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4825 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004826 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004827 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004828 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004829
4830 // See if we can simplify any instructions used by the instruction whose sole
4831 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004832 if (!isa<VectorType>(I.getType())) {
4833 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4834 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4835 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4836 KnownZero, KnownOne))
4837 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004838 } else if (isa<ConstantAggregateZero>(Op1)) {
4839 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004840 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004841
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004842 // Is this a ~ operation?
4843 if (Value *NotOp = dyn_castNotVal(&I)) {
4844 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4845 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4846 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4847 if (Op0I->getOpcode() == Instruction::And ||
4848 Op0I->getOpcode() == Instruction::Or) {
4849 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4850 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4851 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004852 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004853 Op0I->getOperand(1)->getName()+".not");
4854 InsertNewInstBefore(NotY, I);
4855 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004856 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004857 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004858 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004859 }
4860 }
4861 }
4862 }
4863
4864
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004865 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004866 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4867 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4868 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869 return new ICmpInst(ICI->getInversePredicate(),
4870 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004871
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004872 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4873 return new FCmpInst(FCI->getInversePredicate(),
4874 FCI->getOperand(0), FCI->getOperand(1));
4875 }
4876
Reid Spencere4d87aa2006-12-23 06:05:41 +00004877 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004878 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004879 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4880 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004881 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4882 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004883 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004884 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004885 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004886
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004887 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004888 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004889 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004890 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004891 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004892 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004893 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004894 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004895 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004896 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004897 // (X + C) ^ signbit -> (X + C + signbit)
4898 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004899 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004900
Chris Lattner7c4049c2004-01-12 19:35:11 +00004901 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004902 } else if (Op0I->getOpcode() == Instruction::Or) {
4903 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004904 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004905 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4906 // Anything in both C1 and C2 is known to be zero, remove it from
4907 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004908 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004909 NewRHS = ConstantExpr::getAnd(NewRHS,
4910 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004911 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004912 I.setOperand(0, Op0I->getOperand(0));
4913 I.setOperand(1, NewRHS);
4914 return &I;
4915 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004916 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004917 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004918 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004919
4920 // Try to fold constant and into select arguments.
4921 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004922 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004923 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004924 if (isa<PHINode>(Op0))
4925 if (Instruction *NV = FoldOpIntoPhi(I))
4926 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004927 }
4928
Chris Lattner8d969642003-03-10 23:06:50 +00004929 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004930 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004931 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004932
Chris Lattner8d969642003-03-10 23:06:50 +00004933 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004934 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004935 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004936
Chris Lattner318bf792007-03-18 22:51:34 +00004937
4938 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4939 if (Op1I) {
4940 Value *A, *B;
4941 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4942 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004943 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004944 I.swapOperands();
4945 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004946 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004947 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004948 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004949 }
Chris Lattner318bf792007-03-18 22:51:34 +00004950 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4951 if (Op0 == A) // A^(A^B) == B
4952 return ReplaceInstUsesWith(I, B);
4953 else if (Op0 == B) // A^(B^A) == B
4954 return ReplaceInstUsesWith(I, A);
4955 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004956 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004957 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004958 std::swap(A, B);
4959 }
Chris Lattner318bf792007-03-18 22:51:34 +00004960 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004961 I.swapOperands(); // Simplified below.
4962 std::swap(Op0, Op1);
4963 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004964 }
Chris Lattner318bf792007-03-18 22:51:34 +00004965 }
4966
4967 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4968 if (Op0I) {
4969 Value *A, *B;
4970 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4971 if (A == Op1) // (B|A)^B == (A|B)^B
4972 std::swap(A, B);
4973 if (B == Op1) { // (A|B)^B == A & ~B
4974 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004975 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4976 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004977 }
Chris Lattner318bf792007-03-18 22:51:34 +00004978 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4979 if (Op1 == A) // (A^B)^A == B
4980 return ReplaceInstUsesWith(I, B);
4981 else if (Op1 == B) // (B^A)^A == B
4982 return ReplaceInstUsesWith(I, A);
4983 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4984 if (A == Op1) // (A&B)^A -> (B&A)^A
4985 std::swap(A, B);
4986 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004987 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004988 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004989 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4990 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004991 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004992 }
Chris Lattner318bf792007-03-18 22:51:34 +00004993 }
4994
4995 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4996 if (Op0I && Op1I && Op0I->isShift() &&
4997 Op0I->getOpcode() == Op1I->getOpcode() &&
4998 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4999 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5000 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005001 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005002 Op1I->getOperand(0),
5003 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005004 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005005 Op1I->getOperand(1));
5006 }
5007
5008 if (Op0I && Op1I) {
5009 Value *A, *B, *C, *D;
5010 // (A & B)^(A | B) -> A ^ B
5011 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5012 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5013 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005014 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005015 }
5016 // (A | B)^(A & B) -> A ^ B
5017 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5018 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5019 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005020 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005021 }
5022
5023 // (A & B)^(C & D)
5024 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5025 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5026 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5027 // (X & Y)^(X & Y) -> (Y^Z) & X
5028 Value *X = 0, *Y = 0, *Z = 0;
5029 if (A == C)
5030 X = A, Y = B, Z = D;
5031 else if (A == D)
5032 X = A, Y = B, Z = C;
5033 else if (B == C)
5034 X = B, Y = A, Z = D;
5035 else if (B == D)
5036 X = B, Y = A, Z = C;
5037
5038 if (X) {
5039 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005040 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5041 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005042 }
5043 }
5044 }
5045
Reid Spencere4d87aa2006-12-23 06:05:41 +00005046 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5047 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5048 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005049 return R;
5050
Chris Lattner6fc205f2006-05-05 06:39:07 +00005051 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005052 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005053 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005054 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5055 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005056 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005057 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005058 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5059 I.getType(), TD) &&
5060 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5061 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005062 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005063 Op1C->getOperand(0),
5064 I.getName());
5065 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005066 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005067 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005068 }
Chris Lattner99c65742007-10-24 05:38:08 +00005069 }
Chris Lattner7e708292002-06-25 16:13:24 +00005070 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005071}
5072
Chris Lattnera96879a2004-09-29 17:40:11 +00005073/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5074/// overflowed for this type.
5075static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005076 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005077 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005078
Reid Spencere4e40032007-03-21 23:19:50 +00005079 if (IsSigned)
5080 if (In2->getValue().isNegative())
5081 return Result->getValue().sgt(In1->getValue());
5082 else
5083 return Result->getValue().slt(In1->getValue());
5084 else
5085 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005086}
5087
Chris Lattner574da9b2005-01-13 20:14:25 +00005088/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5089/// code necessary to compute the offset from the base pointer (without adding
5090/// in the base pointer). Return the result as a signed integer of intptr size.
5091static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5092 TargetData &TD = IC.getTargetData();
5093 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005094 const Type *IntPtrTy = TD.getIntPtrType();
5095 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005096
5097 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005098 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005099 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005100
Chris Lattner574da9b2005-01-13 20:14:25 +00005101 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5102 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005103 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005104 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5105 if (OpC->isZero()) continue;
5106
5107 // Handle a struct index, which adds its field offset to the pointer.
5108 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5109 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5110
5111 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5112 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005113 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005114 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005115 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005116 ConstantInt::get(IntPtrTy, Size),
5117 GEP->getName()+".offs"), I);
5118 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005119 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005120
5121 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5122 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5123 Scale = ConstantExpr::getMul(OC, Scale);
5124 if (Constant *RC = dyn_cast<Constant>(Result))
5125 Result = ConstantExpr::getAdd(RC, Scale);
5126 else {
5127 // Emit an add instruction.
5128 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005129 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005130 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005131 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005132 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005133 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005134 // Convert to correct type.
5135 if (Op->getType() != IntPtrTy) {
5136 if (Constant *OpC = dyn_cast<Constant>(Op))
5137 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5138 else
5139 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5140 Op->getName()+".c"), I);
5141 }
5142 if (Size != 1) {
5143 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5144 if (Constant *OpC = dyn_cast<Constant>(Op))
5145 Op = ConstantExpr::getMul(OpC, Scale);
5146 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005147 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005148 GEP->getName()+".idx"), I);
5149 }
5150
5151 // Emit an add instruction.
5152 if (isa<Constant>(Op) && isa<Constant>(Result))
5153 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5154 cast<Constant>(Result));
5155 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005156 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005157 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005158 }
5159 return Result;
5160}
5161
Chris Lattner10c0d912008-04-22 02:53:33 +00005162
5163/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5164/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5165/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5166/// complex, and scales are involved. The above expression would also be legal
5167/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5168/// later form is less amenable to optimization though, and we are allowed to
5169/// generate the first by knowing that pointer arithmetic doesn't overflow.
5170///
5171/// If we can't emit an optimized form for this expression, this returns null.
5172///
5173static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5174 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005175 TargetData &TD = IC.getTargetData();
5176 gep_type_iterator GTI = gep_type_begin(GEP);
5177
5178 // Check to see if this gep only has a single variable index. If so, and if
5179 // any constant indices are a multiple of its scale, then we can compute this
5180 // in terms of the scale of the variable index. For example, if the GEP
5181 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5182 // because the expression will cross zero at the same point.
5183 unsigned i, e = GEP->getNumOperands();
5184 int64_t Offset = 0;
5185 for (i = 1; i != e; ++i, ++GTI) {
5186 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5187 // Compute the aggregate offset of constant indices.
5188 if (CI->isZero()) continue;
5189
5190 // Handle a struct index, which adds its field offset to the pointer.
5191 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5192 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5193 } else {
5194 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5195 Offset += Size*CI->getSExtValue();
5196 }
5197 } else {
5198 // Found our variable index.
5199 break;
5200 }
5201 }
5202
5203 // If there are no variable indices, we must have a constant offset, just
5204 // evaluate it the general way.
5205 if (i == e) return 0;
5206
5207 Value *VariableIdx = GEP->getOperand(i);
5208 // Determine the scale factor of the variable element. For example, this is
5209 // 4 if the variable index is into an array of i32.
5210 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5211
5212 // Verify that there are no other variable indices. If so, emit the hard way.
5213 for (++i, ++GTI; i != e; ++i, ++GTI) {
5214 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5215 if (!CI) return 0;
5216
5217 // Compute the aggregate offset of constant indices.
5218 if (CI->isZero()) continue;
5219
5220 // Handle a struct index, which adds its field offset to the pointer.
5221 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5222 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5223 } else {
5224 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5225 Offset += Size*CI->getSExtValue();
5226 }
5227 }
5228
5229 // Okay, we know we have a single variable index, which must be a
5230 // pointer/array/vector index. If there is no offset, life is simple, return
5231 // the index.
5232 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5233 if (Offset == 0) {
5234 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5235 // we don't need to bother extending: the extension won't affect where the
5236 // computation crosses zero.
5237 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5238 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5239 VariableIdx->getNameStart(), &I);
5240 return VariableIdx;
5241 }
5242
5243 // Otherwise, there is an index. The computation we will do will be modulo
5244 // the pointer size, so get it.
5245 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5246
5247 Offset &= PtrSizeMask;
5248 VariableScale &= PtrSizeMask;
5249
5250 // To do this transformation, any constant index must be a multiple of the
5251 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5252 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5253 // multiple of the variable scale.
5254 int64_t NewOffs = Offset / (int64_t)VariableScale;
5255 if (Offset != NewOffs*(int64_t)VariableScale)
5256 return 0;
5257
5258 // Okay, we can do this evaluation. Start by converting the index to intptr.
5259 const Type *IntPtrTy = TD.getIntPtrType();
5260 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005261 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005262 true /*SExt*/,
5263 VariableIdx->getNameStart(), &I);
5264 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005265 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005266}
5267
5268
Reid Spencere4d87aa2006-12-23 06:05:41 +00005269/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005270/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005271Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5272 ICmpInst::Predicate Cond,
5273 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005274 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005275
Chris Lattner10c0d912008-04-22 02:53:33 +00005276 // Look through bitcasts.
5277 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5278 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005279
Chris Lattner574da9b2005-01-13 20:14:25 +00005280 Value *PtrBase = GEPLHS->getOperand(0);
5281 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005282 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005283 // This transformation (ignoring the base and scales) is valid because we
5284 // know pointers can't overflow. See if we can output an optimized form.
5285 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5286
5287 // If not, synthesize the offset the hard way.
5288 if (Offset == 0)
5289 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005290 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5291 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005292 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005293 // If the base pointers are different, but the indices are the same, just
5294 // compare the base pointer.
5295 if (PtrBase != GEPRHS->getOperand(0)) {
5296 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005297 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005298 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005299 if (IndicesTheSame)
5300 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5301 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5302 IndicesTheSame = false;
5303 break;
5304 }
5305
5306 // If all indices are the same, just compare the base pointers.
5307 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005308 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5309 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005310
5311 // Otherwise, the base pointers are different and the indices are
5312 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005313 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005314 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005315
Chris Lattnere9d782b2005-01-13 22:25:21 +00005316 // If one of the GEPs has all zero indices, recurse.
5317 bool AllZeros = true;
5318 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5319 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5320 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5321 AllZeros = false;
5322 break;
5323 }
5324 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005325 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5326 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005327
5328 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005329 AllZeros = true;
5330 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5331 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5332 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5333 AllZeros = false;
5334 break;
5335 }
5336 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005337 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005338
Chris Lattner4401c9c2005-01-14 00:20:05 +00005339 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5340 // If the GEPs only differ by one index, compare it.
5341 unsigned NumDifferences = 0; // Keep track of # differences.
5342 unsigned DiffOperand = 0; // The operand that differs.
5343 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5344 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005345 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5346 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005347 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005348 NumDifferences = 2;
5349 break;
5350 } else {
5351 if (NumDifferences++) break;
5352 DiffOperand = i;
5353 }
5354 }
5355
5356 if (NumDifferences == 0) // SAME GEP?
5357 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005358 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005359 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005360
Chris Lattner4401c9c2005-01-14 00:20:05 +00005361 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005362 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5363 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005364 // Make sure we do a signed comparison here.
5365 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005366 }
5367 }
5368
Reid Spencere4d87aa2006-12-23 06:05:41 +00005369 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005370 // the result to fold to a constant!
5371 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5372 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5373 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5374 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5375 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005376 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005377 }
5378 }
5379 return 0;
5380}
5381
Chris Lattnera5406232008-05-19 20:18:56 +00005382/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5383///
5384Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5385 Instruction *LHSI,
5386 Constant *RHSC) {
5387 if (!isa<ConstantFP>(RHSC)) return 0;
5388 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5389
5390 // Get the width of the mantissa. We don't want to hack on conversions that
5391 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005392 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005393 if (MantissaWidth == -1) return 0; // Unknown.
5394
5395 // Check to see that the input is converted from an integer type that is small
5396 // enough that preserves all bits. TODO: check here for "known" sign bits.
5397 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5398 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5399
5400 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5401 if (isa<UIToFPInst>(LHSI))
5402 ++InputSize;
5403
5404 // If the conversion would lose info, don't hack on this.
5405 if ((int)InputSize > MantissaWidth)
5406 return 0;
5407
5408 // Otherwise, we can potentially simplify the comparison. We know that it
5409 // will always come through as an integer value and we know the constant is
5410 // not a NAN (it would have been previously simplified).
5411 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5412
5413 ICmpInst::Predicate Pred;
5414 switch (I.getPredicate()) {
5415 default: assert(0 && "Unexpected predicate!");
5416 case FCmpInst::FCMP_UEQ:
5417 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5418 case FCmpInst::FCMP_UGT:
5419 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5420 case FCmpInst::FCMP_UGE:
5421 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5422 case FCmpInst::FCMP_ULT:
5423 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5424 case FCmpInst::FCMP_ULE:
5425 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5426 case FCmpInst::FCMP_UNE:
5427 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5428 case FCmpInst::FCMP_ORD:
5429 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5430 case FCmpInst::FCMP_UNO:
5431 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5432 }
5433
5434 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5435
5436 // Now we know that the APFloat is a normal number, zero or inf.
5437
5438 // See if the FP constant is top large for the integer. For example,
5439 // comparing an i8 to 300.0.
5440 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5441
5442 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5443 // and large values.
5444 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5445 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5446 APFloat::rmNearestTiesToEven);
5447 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5448 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5449 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5450 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5451 }
5452
5453 // See if the RHS value is < SignedMin.
5454 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5455 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5456 APFloat::rmNearestTiesToEven);
5457 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5458 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5459 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5460 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5461 }
5462
5463 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5464 // it may still be fractional. See if it is fractional by casting the FP
5465 // value to the integer value and back, checking for equality. Don't do this
5466 // for zero, because -0.0 is not fractional.
5467 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5468 if (!RHS.isZero() &&
5469 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5470 // If we had a comparison against a fractional value, we have to adjust
5471 // the compare predicate and sometimes the value. RHSC is rounded towards
5472 // zero at this point.
5473 switch (Pred) {
5474 default: assert(0 && "Unexpected integer comparison!");
5475 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5476 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5477 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5478 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5479 case ICmpInst::ICMP_SLE:
5480 // (float)int <= 4.4 --> int <= 4
5481 // (float)int <= -4.4 --> int < -4
5482 if (RHS.isNegative())
5483 Pred = ICmpInst::ICMP_SLT;
5484 break;
5485 case ICmpInst::ICMP_SLT:
5486 // (float)int < -4.4 --> int < -4
5487 // (float)int < 4.4 --> int <= 4
5488 if (!RHS.isNegative())
5489 Pred = ICmpInst::ICMP_SLE;
5490 break;
5491 case ICmpInst::ICMP_SGT:
5492 // (float)int > 4.4 --> int > 4
5493 // (float)int > -4.4 --> int >= -4
5494 if (RHS.isNegative())
5495 Pred = ICmpInst::ICMP_SGE;
5496 break;
5497 case ICmpInst::ICMP_SGE:
5498 // (float)int >= -4.4 --> int >= -4
5499 // (float)int >= 4.4 --> int > 4
5500 if (!RHS.isNegative())
5501 Pred = ICmpInst::ICMP_SGT;
5502 break;
5503 }
5504 }
5505
5506 // Lower this FP comparison into an appropriate integer version of the
5507 // comparison.
5508 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5509}
5510
Reid Spencere4d87aa2006-12-23 06:05:41 +00005511Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5512 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005514
Chris Lattner58e97462007-01-14 19:42:17 +00005515 // Fold trivial predicates.
5516 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5517 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5518 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5519 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5520
5521 // Simplify 'fcmp pred X, X'
5522 if (Op0 == Op1) {
5523 switch (I.getPredicate()) {
5524 default: assert(0 && "Unknown predicate!");
5525 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5526 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5527 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5528 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5529 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5530 case FCmpInst::FCMP_OLT: // True if ordered and less than
5531 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5532 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5533
5534 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5535 case FCmpInst::FCMP_ULT: // True if unordered or less than
5536 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5537 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5538 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5539 I.setPredicate(FCmpInst::FCMP_UNO);
5540 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5541 return &I;
5542
5543 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5544 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5545 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5546 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5547 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5548 I.setPredicate(FCmpInst::FCMP_ORD);
5549 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5550 return &I;
5551 }
5552 }
5553
Reid Spencere4d87aa2006-12-23 06:05:41 +00005554 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005555 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005556
Reid Spencere4d87aa2006-12-23 06:05:41 +00005557 // Handle fcmp with constant RHS
5558 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005559 // If the constant is a nan, see if we can fold the comparison based on it.
5560 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5561 if (CFP->getValueAPF().isNaN()) {
5562 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5563 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5564 if (FCmpInst::isUnordered(I.getPredicate())) // True if unordered or...
5565 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5566 if (FCmpInst::isUnordered(I.getPredicate())) // Undef on unordered.
5567 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5568 }
5569 }
5570
Reid Spencere4d87aa2006-12-23 06:05:41 +00005571 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5572 switch (LHSI->getOpcode()) {
5573 case Instruction::PHI:
5574 if (Instruction *NV = FoldOpIntoPhi(I))
5575 return NV;
5576 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005577 case Instruction::SIToFP:
5578 case Instruction::UIToFP:
5579 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5580 return NV;
5581 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005582 case Instruction::Select:
5583 // If either operand of the select is a constant, we can fold the
5584 // comparison into the select arms, which will cause one to be
5585 // constant folded and the select turned into a bitwise or.
5586 Value *Op1 = 0, *Op2 = 0;
5587 if (LHSI->hasOneUse()) {
5588 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5589 // Fold the known value into the constant operand.
5590 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5591 // Insert a new FCmp of the other select operand.
5592 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5593 LHSI->getOperand(2), RHSC,
5594 I.getName()), I);
5595 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5596 // Fold the known value into the constant operand.
5597 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5598 // Insert a new FCmp of the other select operand.
5599 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5600 LHSI->getOperand(1), RHSC,
5601 I.getName()), I);
5602 }
5603 }
5604
5605 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005606 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005607 break;
5608 }
5609 }
5610
5611 return Changed ? &I : 0;
5612}
5613
5614Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5615 bool Changed = SimplifyCompare(I);
5616 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5617 const Type *Ty = Op0->getType();
5618
5619 // icmp X, X
5620 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005621 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005622 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005623
5624 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005625 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005626
Reid Spencere4d87aa2006-12-23 06:05:41 +00005627 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005628 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005629 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5630 isa<ConstantPointerNull>(Op0)) &&
5631 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005632 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005633 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005634 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005635
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005637 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005638 switch (I.getPredicate()) {
5639 default: assert(0 && "Invalid icmp instruction!");
5640 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005641 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005642 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005643 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005644 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005645 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005646 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005647
Reid Spencere4d87aa2006-12-23 06:05:41 +00005648 case ICmpInst::ICMP_UGT:
5649 case ICmpInst::ICMP_SGT:
5650 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005651 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005652 case ICmpInst::ICMP_ULT:
5653 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005654 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005655 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005656 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005657 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005658 case ICmpInst::ICMP_UGE:
5659 case ICmpInst::ICMP_SGE:
5660 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005661 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005662 case ICmpInst::ICMP_ULE:
5663 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005664 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005665 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005666 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005667 }
5668 }
Chris Lattner8b170942002-08-09 23:47:40 +00005669 }
5670
Chris Lattner2be51ae2004-06-09 04:24:29 +00005671 // See if we are doing a comparison between a constant and an instruction that
5672 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005673 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005674 Value *A, *B;
5675
Chris Lattnerb6566012008-01-05 01:18:20 +00005676 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5677 if (I.isEquality() && CI->isNullValue() &&
5678 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5679 // (icmp cond A B) if cond is equality
5680 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005681 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005682
Reid Spencere4d87aa2006-12-23 06:05:41 +00005683 switch (I.getPredicate()) {
5684 default: break;
5685 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5686 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005687 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005688 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5689 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5690 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5691 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005692 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5693 if (CI->isMinValue(true))
5694 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5695 ConstantInt::getAllOnesValue(Op0->getType()));
5696
Reid Spencere4d87aa2006-12-23 06:05:41 +00005697 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005698
Reid Spencere4d87aa2006-12-23 06:05:41 +00005699 case ICmpInst::ICMP_SLT:
5700 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005702 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5703 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5704 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5705 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5706 break;
5707
5708 case ICmpInst::ICMP_UGT:
5709 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005710 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005711 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5712 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5713 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5714 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005715
5716 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5717 if (CI->isMaxValue(true))
5718 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5719 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005720 break;
5721
5722 case ICmpInst::ICMP_SGT:
5723 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005724 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005725 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5726 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5727 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5728 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5729 break;
5730
5731 case ICmpInst::ICMP_ULE:
5732 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005733 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005734 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5735 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5736 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5737 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5738 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005739
Reid Spencere4d87aa2006-12-23 06:05:41 +00005740 case ICmpInst::ICMP_SLE:
5741 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005742 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005743 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5744 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5745 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5746 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5747 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005748
Reid Spencere4d87aa2006-12-23 06:05:41 +00005749 case ICmpInst::ICMP_UGE:
5750 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005751 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005752 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5753 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5754 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5755 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5756 break;
5757
5758 case ICmpInst::ICMP_SGE:
5759 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005760 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005761 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5762 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5763 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5764 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5765 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005766 }
5767
Reid Spencere4d87aa2006-12-23 06:05:41 +00005768 // If we still have a icmp le or icmp ge instruction, turn it into the
5769 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005770 // already been handled above, this requires little checking.
5771 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005772 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005773 default: break;
5774 case ICmpInst::ICMP_ULE:
5775 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5776 case ICmpInst::ICMP_SLE:
5777 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5778 case ICmpInst::ICMP_UGE:
5779 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5780 case ICmpInst::ICMP_SGE:
5781 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005782 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005783
5784 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005785 // in the input. If this comparison is a normal comparison, it demands all
5786 // bits, if it is a sign bit comparison, it only demands the sign bit.
5787
5788 bool UnusedBit;
5789 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5790
Reid Spencer0460fb32007-03-22 20:36:03 +00005791 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5792 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005793 if (SimplifyDemandedBits(Op0,
5794 isSignBit ? APInt::getSignBit(BitWidth)
5795 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005796 KnownZero, KnownOne, 0))
5797 return &I;
5798
5799 // Given the known and unknown bits, compute a range that the LHS could be
5800 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005801 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005802 // Compute the Min, Max and RHS values based on the known bits. For the
5803 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005804 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5805 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005806 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005807 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5808 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005809 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005810 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5811 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005812 }
5813 switch (I.getPredicate()) { // LE/GE have been folded already.
5814 default: assert(0 && "Unknown icmp opcode!");
5815 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005816 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005817 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005818 break;
5819 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005820 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005821 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005822 break;
5823 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005824 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005825 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005826 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005827 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005828 break;
5829 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005830 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005831 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005832 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005833 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005834 break;
5835 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005836 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005837 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005838 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005839 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005840 break;
5841 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005842 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005843 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005844 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005845 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005846 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005847 }
5848 }
5849
Reid Spencere4d87aa2006-12-23 06:05:41 +00005850 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005851 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005852 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005853 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005854 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5855 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005856 }
5857
Chris Lattner01deb9d2007-04-03 17:43:25 +00005858 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005859 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5860 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5861 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005862 case Instruction::GetElementPtr:
5863 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005864 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005865 bool isAllZeros = true;
5866 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5867 if (!isa<Constant>(LHSI->getOperand(i)) ||
5868 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5869 isAllZeros = false;
5870 break;
5871 }
5872 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005873 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005874 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5875 }
5876 break;
5877
Chris Lattner6970b662005-04-23 15:31:55 +00005878 case Instruction::PHI:
5879 if (Instruction *NV = FoldOpIntoPhi(I))
5880 return NV;
5881 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005882 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005883 // If either operand of the select is a constant, we can fold the
5884 // comparison into the select arms, which will cause one to be
5885 // constant folded and the select turned into a bitwise or.
5886 Value *Op1 = 0, *Op2 = 0;
5887 if (LHSI->hasOneUse()) {
5888 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5889 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005890 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5891 // Insert a new ICmp of the other select operand.
5892 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5893 LHSI->getOperand(2), RHSC,
5894 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005895 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5896 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005897 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5898 // Insert a new ICmp of the other select operand.
5899 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5900 LHSI->getOperand(1), RHSC,
5901 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005902 }
5903 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005904
Chris Lattner6970b662005-04-23 15:31:55 +00005905 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005906 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005907 break;
5908 }
Chris Lattner4802d902007-04-06 18:57:34 +00005909 case Instruction::Malloc:
5910 // If we have (malloc != null), and if the malloc has a single use, we
5911 // can assume it is successful and remove the malloc.
5912 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5913 AddToWorkList(LHSI);
5914 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005915 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005916 }
5917 break;
5918 }
Chris Lattner6970b662005-04-23 15:31:55 +00005919 }
5920
Reid Spencere4d87aa2006-12-23 06:05:41 +00005921 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005922 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005923 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005924 return NI;
5925 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005926 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5927 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005928 return NI;
5929
Reid Spencere4d87aa2006-12-23 06:05:41 +00005930 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005931 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5932 // now.
5933 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5934 if (isa<PointerType>(Op0->getType()) &&
5935 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005936 // We keep moving the cast from the left operand over to the right
5937 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005938 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005939
Chris Lattner57d86372007-01-06 01:45:59 +00005940 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5941 // so eliminate it as well.
5942 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5943 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005944
Chris Lattnerde90b762003-11-03 04:25:02 +00005945 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005946 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005947 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005948 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005949 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005950 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005951 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005952 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005953 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005954 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005955 }
Chris Lattner57d86372007-01-06 01:45:59 +00005956 }
5957
5958 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005959 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005960 // This comes up when you have code like
5961 // int X = A < B;
5962 // if (X) ...
5963 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005964 // with a constant or another cast from the same type.
5965 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005967 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005968 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005969
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005970 // ~x < ~y --> y < x
5971 { Value *A, *B;
5972 if (match(Op0, m_Not(m_Value(A))) &&
5973 match(Op1, m_Not(m_Value(B))))
5974 return new ICmpInst(I.getPredicate(), B, A);
5975 }
5976
Chris Lattner65b72ba2006-09-18 04:22:48 +00005977 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005978 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005979
5980 // -x == -y --> x == y
5981 if (match(Op0, m_Neg(m_Value(A))) &&
5982 match(Op1, m_Neg(m_Value(B))))
5983 return new ICmpInst(I.getPredicate(), A, B);
5984
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005985 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5986 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5987 Value *OtherVal = A == Op1 ? B : A;
5988 return new ICmpInst(I.getPredicate(), OtherVal,
5989 Constant::getNullValue(A->getType()));
5990 }
5991
5992 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5993 // A^c1 == C^c2 --> A == C^(c1^c2)
5994 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5995 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5996 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005997 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005998 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005999 return new ICmpInst(I.getPredicate(), A,
6000 InsertNewInstBefore(Xor, I));
6001 }
6002
6003 // A^B == A^D -> B == D
6004 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6005 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6006 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6007 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6008 }
6009 }
6010
6011 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6012 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006013 // A == (A^B) -> B == 0
6014 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006015 return new ICmpInst(I.getPredicate(), OtherVal,
6016 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006017 }
6018 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006019 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006020 return new ICmpInst(I.getPredicate(), B,
6021 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006022 }
6023 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006024 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006025 return new ICmpInst(I.getPredicate(), B,
6026 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006027 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006028
Chris Lattner9c2328e2006-11-14 06:06:06 +00006029 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6030 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6031 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6032 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6033 Value *X = 0, *Y = 0, *Z = 0;
6034
6035 if (A == C) {
6036 X = B; Y = D; Z = A;
6037 } else if (A == D) {
6038 X = B; Y = C; Z = A;
6039 } else if (B == C) {
6040 X = A; Y = D; Z = B;
6041 } else if (B == D) {
6042 X = A; Y = C; Z = B;
6043 }
6044
6045 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006046 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6047 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006048 I.setOperand(0, Op1);
6049 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6050 return &I;
6051 }
6052 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006053 }
Chris Lattner7e708292002-06-25 16:13:24 +00006054 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006055}
6056
Chris Lattner562ef782007-06-20 23:46:26 +00006057
6058/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6059/// and CmpRHS are both known to be integer constants.
6060Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6061 ConstantInt *DivRHS) {
6062 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6063 const APInt &CmpRHSV = CmpRHS->getValue();
6064
6065 // FIXME: If the operand types don't match the type of the divide
6066 // then don't attempt this transform. The code below doesn't have the
6067 // logic to deal with a signed divide and an unsigned compare (and
6068 // vice versa). This is because (x /s C1) <s C2 produces different
6069 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6070 // (x /u C1) <u C2. Simply casting the operands and result won't
6071 // work. :( The if statement below tests that condition and bails
6072 // if it finds it.
6073 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6074 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6075 return 0;
6076 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006077 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006078
6079 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6080 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6081 // C2 (CI). By solving for X we can turn this into a range check
6082 // instead of computing a divide.
6083 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6084
6085 // Determine if the product overflows by seeing if the product is
6086 // not equal to the divide. Make sure we do the same kind of divide
6087 // as in the LHS instruction that we're folding.
6088 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6089 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6090
6091 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006092 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006093
Chris Lattner1dbfd482007-06-21 18:11:19 +00006094 // Figure out the interval that is being checked. For example, a comparison
6095 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6096 // Compute this interval based on the constants involved and the signedness of
6097 // the compare/divide. This computes a half-open interval, keeping track of
6098 // whether either value in the interval overflows. After analysis each
6099 // overflow variable is set to 0 if it's corresponding bound variable is valid
6100 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6101 int LoOverflow = 0, HiOverflow = 0;
6102 ConstantInt *LoBound = 0, *HiBound = 0;
6103
6104
Chris Lattner562ef782007-06-20 23:46:26 +00006105 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006106 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006107 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006108 HiOverflow = LoOverflow = ProdOV;
6109 if (!HiOverflow)
6110 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006111 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006112 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006113 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006114 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6115 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006116 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006117 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6118 HiOverflow = LoOverflow = ProdOV;
6119 if (!HiOverflow)
6120 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006121 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006122 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006123 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6124 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006125 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006126 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006127 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006128 }
Dan Gohman76491272008-02-13 22:09:18 +00006129 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006130 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006131 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006132 LoBound = AddOne(DivRHS);
6133 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006134 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6135 HiOverflow = 1; // [INTMIN+1, overflow)
6136 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6137 }
Dan Gohman76491272008-02-13 22:09:18 +00006138 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006139 // e.g. X/-5 op 3 --> [-19, -14)
6140 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006141 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006142 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006143 HiBound = AddOne(Prod);
6144 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006145 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006146 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006147 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006148 HiBound = Subtract(Prod, DivRHS);
6149 }
6150
Chris Lattner1dbfd482007-06-21 18:11:19 +00006151 // Dividing by a negative swaps the condition. LT <-> GT
6152 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006153 }
6154
6155 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006156 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006157 default: assert(0 && "Unhandled icmp opcode!");
6158 case ICmpInst::ICMP_EQ:
6159 if (LoOverflow && HiOverflow)
6160 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6161 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006162 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006163 ICmpInst::ICMP_UGE, X, LoBound);
6164 else if (LoOverflow)
6165 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6166 ICmpInst::ICMP_ULT, X, HiBound);
6167 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006168 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006169 case ICmpInst::ICMP_NE:
6170 if (LoOverflow && HiOverflow)
6171 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6172 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006173 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006174 ICmpInst::ICMP_ULT, X, LoBound);
6175 else if (LoOverflow)
6176 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6177 ICmpInst::ICMP_UGE, X, HiBound);
6178 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006179 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006180 case ICmpInst::ICMP_ULT:
6181 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006182 if (LoOverflow == +1) // Low bound is greater than input range.
6183 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6184 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006185 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006186 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006187 case ICmpInst::ICMP_UGT:
6188 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006189 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006190 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006191 else if (HiOverflow == -1) // High bound less than input range.
6192 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6193 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006194 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6195 else
6196 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6197 }
6198}
6199
6200
Chris Lattner01deb9d2007-04-03 17:43:25 +00006201/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6202///
6203Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6204 Instruction *LHSI,
6205 ConstantInt *RHS) {
6206 const APInt &RHSV = RHS->getValue();
6207
6208 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006209 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006210 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6211 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6212 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006213 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6214 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006215 Value *CompareVal = LHSI->getOperand(0);
6216
6217 // If the sign bit of the XorCST is not set, there is no change to
6218 // the operation, just stop using the Xor.
6219 if (!XorCST->getValue().isNegative()) {
6220 ICI.setOperand(0, CompareVal);
6221 AddToWorkList(LHSI);
6222 return &ICI;
6223 }
6224
6225 // Was the old condition true if the operand is positive?
6226 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6227
6228 // If so, the new one isn't.
6229 isTrueIfPositive ^= true;
6230
6231 if (isTrueIfPositive)
6232 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6233 else
6234 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6235 }
6236 }
6237 break;
6238 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6239 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6240 LHSI->getOperand(0)->hasOneUse()) {
6241 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6242
6243 // If the LHS is an AND of a truncating cast, we can widen the
6244 // and/compare to be the input width without changing the value
6245 // produced, eliminating a cast.
6246 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6247 // We can do this transformation if either the AND constant does not
6248 // have its sign bit set or if it is an equality comparison.
6249 // Extending a relational comparison when we're checking the sign
6250 // bit would not work.
6251 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006252 (ICI.isEquality() ||
6253 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006254 uint32_t BitWidth =
6255 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6256 APInt NewCST = AndCST->getValue();
6257 NewCST.zext(BitWidth);
6258 APInt NewCI = RHSV;
6259 NewCI.zext(BitWidth);
6260 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006261 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006262 ConstantInt::get(NewCST),LHSI->getName());
6263 InsertNewInstBefore(NewAnd, ICI);
6264 return new ICmpInst(ICI.getPredicate(), NewAnd,
6265 ConstantInt::get(NewCI));
6266 }
6267 }
6268
6269 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6270 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6271 // happens a LOT in code produced by the C front-end, for bitfield
6272 // access.
6273 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6274 if (Shift && !Shift->isShift())
6275 Shift = 0;
6276
6277 ConstantInt *ShAmt;
6278 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6279 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6280 const Type *AndTy = AndCST->getType(); // Type of the and.
6281
6282 // We can fold this as long as we can't shift unknown bits
6283 // into the mask. This can only happen with signed shift
6284 // rights, as they sign-extend.
6285 if (ShAmt) {
6286 bool CanFold = Shift->isLogicalShift();
6287 if (!CanFold) {
6288 // To test for the bad case of the signed shr, see if any
6289 // of the bits shifted in could be tested after the mask.
6290 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6291 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6292
6293 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6294 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6295 AndCST->getValue()) == 0)
6296 CanFold = true;
6297 }
6298
6299 if (CanFold) {
6300 Constant *NewCst;
6301 if (Shift->getOpcode() == Instruction::Shl)
6302 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6303 else
6304 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6305
6306 // Check to see if we are shifting out any of the bits being
6307 // compared.
6308 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6309 // If we shifted bits out, the fold is not going to work out.
6310 // As a special case, check to see if this means that the
6311 // result is always true or false now.
6312 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6313 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6314 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6315 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6316 } else {
6317 ICI.setOperand(1, NewCst);
6318 Constant *NewAndCST;
6319 if (Shift->getOpcode() == Instruction::Shl)
6320 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6321 else
6322 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6323 LHSI->setOperand(1, NewAndCST);
6324 LHSI->setOperand(0, Shift->getOperand(0));
6325 AddToWorkList(Shift); // Shift is dead.
6326 AddUsesToWorkList(ICI);
6327 return &ICI;
6328 }
6329 }
6330 }
6331
6332 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6333 // preferable because it allows the C<<Y expression to be hoisted out
6334 // of a loop if Y is invariant and X is not.
6335 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6336 ICI.isEquality() && !Shift->isArithmeticShift() &&
6337 isa<Instruction>(Shift->getOperand(0))) {
6338 // Compute C << Y.
6339 Value *NS;
6340 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006341 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006342 Shift->getOperand(1), "tmp");
6343 } else {
6344 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006345 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006346 Shift->getOperand(1), "tmp");
6347 }
6348 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6349
6350 // Compute X & (C << Y).
6351 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006352 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006353 InsertNewInstBefore(NewAnd, ICI);
6354
6355 ICI.setOperand(0, NewAnd);
6356 return &ICI;
6357 }
6358 }
6359 break;
6360
Chris Lattnera0141b92007-07-15 20:42:37 +00006361 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6362 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6363 if (!ShAmt) break;
6364
6365 uint32_t TypeBits = RHSV.getBitWidth();
6366
6367 // Check that the shift amount is in range. If not, don't perform
6368 // undefined shifts. When the shift is visited it will be
6369 // simplified.
6370 if (ShAmt->uge(TypeBits))
6371 break;
6372
6373 if (ICI.isEquality()) {
6374 // If we are comparing against bits always shifted out, the
6375 // comparison cannot succeed.
6376 Constant *Comp =
6377 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6378 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6379 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6380 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6381 return ReplaceInstUsesWith(ICI, Cst);
6382 }
6383
6384 if (LHSI->hasOneUse()) {
6385 // Otherwise strength reduce the shift into an and.
6386 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6387 Constant *Mask =
6388 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006389
Chris Lattnera0141b92007-07-15 20:42:37 +00006390 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006391 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006392 Mask, LHSI->getName()+".mask");
6393 Value *And = InsertNewInstBefore(AndI, ICI);
6394 return new ICmpInst(ICI.getPredicate(), And,
6395 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006396 }
6397 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006398
6399 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6400 bool TrueIfSigned = false;
6401 if (LHSI->hasOneUse() &&
6402 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6403 // (X << 31) <s 0 --> (X&1) != 0
6404 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6405 (TypeBits-ShAmt->getZExtValue()-1));
6406 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006407 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006408 Mask, LHSI->getName()+".mask");
6409 Value *And = InsertNewInstBefore(AndI, ICI);
6410
6411 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6412 And, Constant::getNullValue(And->getType()));
6413 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006414 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006415 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006416
6417 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006418 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006419 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006420 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006421 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006422
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006423 // Check that the shift amount is in range. If not, don't perform
6424 // undefined shifts. When the shift is visited it will be
6425 // simplified.
6426 uint32_t TypeBits = RHSV.getBitWidth();
6427 if (ShAmt->uge(TypeBits))
6428 break;
6429
6430 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006431
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006432 // If we are comparing against bits always shifted out, the
6433 // comparison cannot succeed.
6434 APInt Comp = RHSV << ShAmtVal;
6435 if (LHSI->getOpcode() == Instruction::LShr)
6436 Comp = Comp.lshr(ShAmtVal);
6437 else
6438 Comp = Comp.ashr(ShAmtVal);
6439
6440 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6441 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6442 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6443 return ReplaceInstUsesWith(ICI, Cst);
6444 }
6445
6446 // Otherwise, check to see if the bits shifted out are known to be zero.
6447 // If so, we can compare against the unshifted value:
6448 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006449 if (LHSI->hasOneUse() &&
6450 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006451 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6452 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6453 ConstantExpr::getShl(RHS, ShAmt));
6454 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006455
Evan Chengf30752c2008-04-23 00:38:06 +00006456 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006457 // Otherwise strength reduce the shift into an and.
6458 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6459 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006460
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006461 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006462 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006463 Mask, LHSI->getName()+".mask");
6464 Value *And = InsertNewInstBefore(AndI, ICI);
6465 return new ICmpInst(ICI.getPredicate(), And,
6466 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006467 }
6468 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006469 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006470
6471 case Instruction::SDiv:
6472 case Instruction::UDiv:
6473 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6474 // Fold this div into the comparison, producing a range check.
6475 // Determine, based on the divide type, what the range is being
6476 // checked. If there is an overflow on the low or high side, remember
6477 // it, otherwise compute the range [low, hi) bounding the new value.
6478 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006479 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6480 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6481 DivRHS))
6482 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006483 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006484
6485 case Instruction::Add:
6486 // Fold: icmp pred (add, X, C1), C2
6487
6488 if (!ICI.isEquality()) {
6489 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6490 if (!LHSC) break;
6491 const APInt &LHSV = LHSC->getValue();
6492
6493 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6494 .subtract(LHSV);
6495
6496 if (ICI.isSignedPredicate()) {
6497 if (CR.getLower().isSignBit()) {
6498 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6499 ConstantInt::get(CR.getUpper()));
6500 } else if (CR.getUpper().isSignBit()) {
6501 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6502 ConstantInt::get(CR.getLower()));
6503 }
6504 } else {
6505 if (CR.getLower().isMinValue()) {
6506 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6507 ConstantInt::get(CR.getUpper()));
6508 } else if (CR.getUpper().isMinValue()) {
6509 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6510 ConstantInt::get(CR.getLower()));
6511 }
6512 }
6513 }
6514 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006515 }
6516
6517 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6518 if (ICI.isEquality()) {
6519 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6520
6521 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6522 // the second operand is a constant, simplify a bit.
6523 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6524 switch (BO->getOpcode()) {
6525 case Instruction::SRem:
6526 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6527 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6528 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6529 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6530 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006531 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006532 BO->getName());
6533 InsertNewInstBefore(NewRem, ICI);
6534 return new ICmpInst(ICI.getPredicate(), NewRem,
6535 Constant::getNullValue(BO->getType()));
6536 }
6537 }
6538 break;
6539 case Instruction::Add:
6540 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6541 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6542 if (BO->hasOneUse())
6543 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6544 Subtract(RHS, BOp1C));
6545 } else if (RHSV == 0) {
6546 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6547 // efficiently invertible, or if the add has just this one use.
6548 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6549
6550 if (Value *NegVal = dyn_castNegVal(BOp1))
6551 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6552 else if (Value *NegVal = dyn_castNegVal(BOp0))
6553 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6554 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006555 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006556 InsertNewInstBefore(Neg, ICI);
6557 Neg->takeName(BO);
6558 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6559 }
6560 }
6561 break;
6562 case Instruction::Xor:
6563 // For the xor case, we can xor two constants together, eliminating
6564 // the explicit xor.
6565 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6566 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6567 ConstantExpr::getXor(RHS, BOC));
6568
6569 // FALLTHROUGH
6570 case Instruction::Sub:
6571 // Replace (([sub|xor] A, B) != 0) with (A != B)
6572 if (RHSV == 0)
6573 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6574 BO->getOperand(1));
6575 break;
6576
6577 case Instruction::Or:
6578 // If bits are being or'd in that are not present in the constant we
6579 // are comparing against, then the comparison could never succeed!
6580 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6581 Constant *NotCI = ConstantExpr::getNot(RHS);
6582 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6583 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6584 isICMP_NE));
6585 }
6586 break;
6587
6588 case Instruction::And:
6589 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6590 // If bits are being compared against that are and'd out, then the
6591 // comparison can never succeed!
6592 if ((RHSV & ~BOC->getValue()) != 0)
6593 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6594 isICMP_NE));
6595
6596 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6597 if (RHS == BOC && RHSV.isPowerOf2())
6598 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6599 ICmpInst::ICMP_NE, LHSI,
6600 Constant::getNullValue(RHS->getType()));
6601
6602 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6603 if (isSignBit(BOC)) {
6604 Value *X = BO->getOperand(0);
6605 Constant *Zero = Constant::getNullValue(X->getType());
6606 ICmpInst::Predicate pred = isICMP_NE ?
6607 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6608 return new ICmpInst(pred, X, Zero);
6609 }
6610
6611 // ((X & ~7) == 0) --> X < 8
6612 if (RHSV == 0 && isHighOnes(BOC)) {
6613 Value *X = BO->getOperand(0);
6614 Constant *NegX = ConstantExpr::getNeg(BOC);
6615 ICmpInst::Predicate pred = isICMP_NE ?
6616 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6617 return new ICmpInst(pred, X, NegX);
6618 }
6619 }
6620 default: break;
6621 }
6622 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6623 // Handle icmp {eq|ne} <intrinsic>, intcst.
6624 if (II->getIntrinsicID() == Intrinsic::bswap) {
6625 AddToWorkList(II);
6626 ICI.setOperand(0, II->getOperand(1));
6627 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6628 return &ICI;
6629 }
6630 }
6631 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006632 // If the LHS is a cast from an integral value of the same size,
6633 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006634 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6635 Value *CastOp = Cast->getOperand(0);
6636 const Type *SrcTy = CastOp->getType();
6637 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6638 if (SrcTy->isInteger() &&
6639 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6640 // If this is an unsigned comparison, try to make the comparison use
6641 // smaller constant values.
6642 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6643 // X u< 128 => X s> -1
6644 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6645 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6646 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6647 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6648 // X u> 127 => X s< 0
6649 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6650 Constant::getNullValue(SrcTy));
6651 }
6652 }
6653 }
6654 }
6655 return 0;
6656}
6657
6658/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6659/// We only handle extending casts so far.
6660///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006661Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6662 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006663 Value *LHSCIOp = LHSCI->getOperand(0);
6664 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006665 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006666 Value *RHSCIOp;
6667
Chris Lattner8c756c12007-05-05 22:41:33 +00006668 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6669 // integer type is the same size as the pointer type.
6670 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6671 getTargetData().getPointerSizeInBits() ==
6672 cast<IntegerType>(DestTy)->getBitWidth()) {
6673 Value *RHSOp = 0;
6674 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006675 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006676 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6677 RHSOp = RHSC->getOperand(0);
6678 // If the pointer types don't match, insert a bitcast.
6679 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006680 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006681 }
6682
6683 if (RHSOp)
6684 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6685 }
6686
6687 // The code below only handles extension cast instructions, so far.
6688 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006689 if (LHSCI->getOpcode() != Instruction::ZExt &&
6690 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006691 return 0;
6692
Reid Spencere4d87aa2006-12-23 06:05:41 +00006693 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6694 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006695
Reid Spencere4d87aa2006-12-23 06:05:41 +00006696 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006697 // Not an extension from the same type?
6698 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006699 if (RHSCIOp->getType() != LHSCIOp->getType())
6700 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006701
Nick Lewycky4189a532008-01-28 03:48:02 +00006702 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006703 // and the other is a zext), then we can't handle this.
6704 if (CI->getOpcode() != LHSCI->getOpcode())
6705 return 0;
6706
Nick Lewycky4189a532008-01-28 03:48:02 +00006707 // Deal with equality cases early.
6708 if (ICI.isEquality())
6709 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6710
6711 // A signed comparison of sign extended values simplifies into a
6712 // signed comparison.
6713 if (isSignedCmp && isSignedExt)
6714 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6715
6716 // The other three cases all fold into an unsigned comparison.
6717 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006718 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006719
Reid Spencere4d87aa2006-12-23 06:05:41 +00006720 // If we aren't dealing with a constant on the RHS, exit early
6721 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6722 if (!CI)
6723 return 0;
6724
6725 // Compute the constant that would happen if we truncated to SrcTy then
6726 // reextended to DestTy.
6727 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6728 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6729
6730 // If the re-extended constant didn't change...
6731 if (Res2 == CI) {
6732 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6733 // For example, we might have:
6734 // %A = sext short %X to uint
6735 // %B = icmp ugt uint %A, 1330
6736 // It is incorrect to transform this into
6737 // %B = icmp ugt short %X, 1330
6738 // because %A may have negative value.
6739 //
6740 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6741 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006742 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006743 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6744 else
6745 return 0;
6746 }
6747
6748 // The re-extended constant changed so the constant cannot be represented
6749 // in the shorter type. Consequently, we cannot emit a simple comparison.
6750
6751 // First, handle some easy cases. We know the result cannot be equal at this
6752 // point so handle the ICI.isEquality() cases
6753 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006754 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006755 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006756 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006757
6758 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6759 // should have been folded away previously and not enter in here.
6760 Value *Result;
6761 if (isSignedCmp) {
6762 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006763 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006764 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006765 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006766 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006767 } else {
6768 // We're performing an unsigned comparison.
6769 if (isSignedExt) {
6770 // We're performing an unsigned comp with a sign extended value.
6771 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006772 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006773 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6774 NegOne, ICI.getName()), ICI);
6775 } else {
6776 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006777 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006778 }
6779 }
6780
6781 // Finally, return the value computed.
6782 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6783 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6784 return ReplaceInstUsesWith(ICI, Result);
6785 } else {
6786 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6787 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6788 "ICmp should be folded!");
6789 if (Constant *CI = dyn_cast<Constant>(Result))
6790 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6791 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006792 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006793 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006794}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006795
Reid Spencer832254e2007-02-02 02:16:23 +00006796Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6797 return commonShiftTransforms(I);
6798}
6799
6800Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6801 return commonShiftTransforms(I);
6802}
6803
6804Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006805 if (Instruction *R = commonShiftTransforms(I))
6806 return R;
6807
6808 Value *Op0 = I.getOperand(0);
6809
6810 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6811 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6812 if (CSI->isAllOnesValue())
6813 return ReplaceInstUsesWith(I, CSI);
6814
6815 // See if we can turn a signed shr into an unsigned shr.
6816 if (MaskedValueIsZero(Op0,
6817 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006818 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006819
6820 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006821}
6822
6823Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6824 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006825 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006826
6827 // shl X, 0 == X and shr X, 0 == X
6828 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006829 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006830 Op0 == Constant::getNullValue(Op0->getType()))
6831 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006832
Reid Spencere4d87aa2006-12-23 06:05:41 +00006833 if (isa<UndefValue>(Op0)) {
6834 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006835 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006836 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006837 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6838 }
6839 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006840 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6841 return ReplaceInstUsesWith(I, Op0);
6842 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006843 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006844 }
6845
Chris Lattner2eefe512004-04-09 19:05:30 +00006846 // Try to fold constant and into select arguments.
6847 if (isa<Constant>(Op0))
6848 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006849 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006850 return R;
6851
Reid Spencerb83eb642006-10-20 07:07:24 +00006852 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006853 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6854 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006855 return 0;
6856}
6857
Reid Spencerb83eb642006-10-20 07:07:24 +00006858Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006859 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006860 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006861
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006862 // See if we can simplify any instructions used by the instruction whose sole
6863 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006864 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6865 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6866 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006867 KnownZero, KnownOne))
6868 return &I;
6869
Chris Lattner4d5542c2006-01-06 07:12:35 +00006870 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6871 // of a signed value.
6872 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006873 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006874 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006875 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6876 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006877 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006878 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006879 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006880 }
6881
6882 // ((X*C1) << C2) == (X * (C1 << C2))
6883 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6884 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6885 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006886 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006887 ConstantExpr::getShl(BOOp, Op1));
6888
6889 // Try to fold constant and into select arguments.
6890 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6891 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6892 return R;
6893 if (isa<PHINode>(Op0))
6894 if (Instruction *NV = FoldOpIntoPhi(I))
6895 return NV;
6896
Chris Lattner8999dd32007-12-22 09:07:47 +00006897 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6898 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6899 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6900 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6901 // place. Don't try to do this transformation in this case. Also, we
6902 // require that the input operand is a shift-by-constant so that we have
6903 // confidence that the shifts will get folded together. We could do this
6904 // xform in more cases, but it is unlikely to be profitable.
6905 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6906 isa<ConstantInt>(TrOp->getOperand(1))) {
6907 // Okay, we'll do this xform. Make the shift of shift.
6908 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006909 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006910 I.getName());
6911 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6912
6913 // For logical shifts, the truncation has the effect of making the high
6914 // part of the register be zeros. Emulate this by inserting an AND to
6915 // clear the top bits as needed. This 'and' will usually be zapped by
6916 // other xforms later if dead.
6917 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6918 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6919 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6920
6921 // The mask we constructed says what the trunc would do if occurring
6922 // between the shifts. We want to know the effect *after* the second
6923 // shift. We know that it is a logical shift by a constant, so adjust the
6924 // mask as appropriate.
6925 if (I.getOpcode() == Instruction::Shl)
6926 MaskV <<= Op1->getZExtValue();
6927 else {
6928 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6929 MaskV = MaskV.lshr(Op1->getZExtValue());
6930 }
6931
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006932 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006933 TI->getName());
6934 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6935
6936 // Return the value truncated to the interesting size.
6937 return new TruncInst(And, I.getType());
6938 }
6939 }
6940
Chris Lattner4d5542c2006-01-06 07:12:35 +00006941 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006942 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6943 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6944 Value *V1, *V2;
6945 ConstantInt *CC;
6946 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006947 default: break;
6948 case Instruction::Add:
6949 case Instruction::And:
6950 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006951 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006952 // These operators commute.
6953 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006954 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6955 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006956 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006957 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006958 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006959 Op0BO->getName());
6960 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006961 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006962 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006963 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006964 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006965 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006966 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006967 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006968 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006969
Chris Lattner150f12a2005-09-18 06:30:59 +00006970 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006971 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006972 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006973 match(Op0BOOp1,
6974 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006975 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6976 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006977 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006978 Op0BO->getOperand(0), Op1,
6979 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006980 InsertNewInstBefore(YS, I); // (Y << C)
6981 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006982 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006983 V1->getName()+".mask");
6984 InsertNewInstBefore(XM, I); // X & (CC << C)
6985
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006986 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006987 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006988 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006989
Reid Spencera07cb7d2007-02-02 14:41:37 +00006990 // FALL THROUGH.
6991 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006992 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006993 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6994 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006995 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006996 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006997 Op0BO->getOperand(1), Op1,
6998 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006999 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007000 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007001 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007002 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007003 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007004 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007005 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007006 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007007 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007008
Chris Lattner13d4ab42006-05-31 21:14:00 +00007009 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007010 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7011 match(Op0BO->getOperand(0),
7012 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007013 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007014 cast<BinaryOperator>(Op0BO->getOperand(0))
7015 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007016 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007017 Op0BO->getOperand(1), Op1,
7018 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007019 InsertNewInstBefore(YS, I); // (Y << C)
7020 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007021 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007022 V1->getName()+".mask");
7023 InsertNewInstBefore(XM, I); // X & (CC << C)
7024
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007025 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007026 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007027
Chris Lattner11021cb2005-09-18 05:12:10 +00007028 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007029 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007030 }
7031
7032
7033 // If the operand is an bitwise operator with a constant RHS, and the
7034 // shift is the only use, we can pull it out of the shift.
7035 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7036 bool isValid = true; // Valid only for And, Or, Xor
7037 bool highBitSet = false; // Transform if high bit of constant set?
7038
7039 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007040 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007041 case Instruction::Add:
7042 isValid = isLeftShift;
7043 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007044 case Instruction::Or:
7045 case Instruction::Xor:
7046 highBitSet = false;
7047 break;
7048 case Instruction::And:
7049 highBitSet = true;
7050 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007051 }
7052
7053 // If this is a signed shift right, and the high bit is modified
7054 // by the logical operation, do not perform the transformation.
7055 // The highBitSet boolean indicates the value of the high bit of
7056 // the constant which would cause it to be modified for this
7057 // operation.
7058 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007059 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007060 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007061
7062 if (isValid) {
7063 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7064
7065 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007066 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007067 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007068 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007069
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007070 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007071 NewRHS);
7072 }
7073 }
7074 }
7075 }
7076
Chris Lattnerad0124c2006-01-06 07:52:12 +00007077 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007078 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7079 if (ShiftOp && !ShiftOp->isShift())
7080 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007081
Reid Spencerb83eb642006-10-20 07:07:24 +00007082 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007083 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007084 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7085 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007086 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7087 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7088 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007089
Zhou Sheng4351c642007-04-02 08:20:41 +00007090 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007091 if (AmtSum > TypeBits)
7092 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007093
7094 const IntegerType *Ty = cast<IntegerType>(I.getType());
7095
7096 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007097 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007098 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007099 ConstantInt::get(Ty, AmtSum));
7100 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7101 I.getOpcode() == Instruction::AShr) {
7102 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007103 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007104 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7105 I.getOpcode() == Instruction::LShr) {
7106 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7107 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007108 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007109 InsertNewInstBefore(Shift, I);
7110
Zhou Shenge9e03f62007-03-28 15:02:20 +00007111 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007112 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007113 }
7114
Chris Lattnerb87056f2007-02-05 00:57:54 +00007115 // Okay, if we get here, one shift must be left, and the other shift must be
7116 // right. See if the amounts are equal.
7117 if (ShiftAmt1 == ShiftAmt2) {
7118 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7119 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007120 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007121 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007122 }
7123 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7124 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007125 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007126 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007127 }
7128 // We can simplify ((X << C) >>s C) into a trunc + sext.
7129 // NOTE: we could do this for any C, but that would make 'unusual' integer
7130 // types. For now, just stick to ones well-supported by the code
7131 // generators.
7132 const Type *SExtType = 0;
7133 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007134 case 1 :
7135 case 8 :
7136 case 16 :
7137 case 32 :
7138 case 64 :
7139 case 128:
7140 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7141 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007142 default: break;
7143 }
7144 if (SExtType) {
7145 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7146 InsertNewInstBefore(NewTrunc, I);
7147 return new SExtInst(NewTrunc, Ty);
7148 }
7149 // Otherwise, we can't handle it yet.
7150 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007151 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007152
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007153 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007154 if (I.getOpcode() == Instruction::Shl) {
7155 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7156 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007157 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007158 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007159 InsertNewInstBefore(Shift, I);
7160
Reid Spencer55702aa2007-03-25 21:11:44 +00007161 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007162 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007163 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007164
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007165 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007166 if (I.getOpcode() == Instruction::LShr) {
7167 assert(ShiftOp->getOpcode() == Instruction::Shl);
7168 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007169 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007170 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007171
Reid Spencerd5e30f02007-03-26 17:18:58 +00007172 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007173 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007174 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007175
7176 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7177 } else {
7178 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007179 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007180
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007181 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007182 if (I.getOpcode() == Instruction::Shl) {
7183 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7184 ShiftOp->getOpcode() == Instruction::AShr);
7185 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007186 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007187 ConstantInt::get(Ty, ShiftDiff));
7188 InsertNewInstBefore(Shift, I);
7189
Reid Spencer55702aa2007-03-25 21:11:44 +00007190 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007191 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007192 }
7193
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007194 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007195 if (I.getOpcode() == Instruction::LShr) {
7196 assert(ShiftOp->getOpcode() == Instruction::Shl);
7197 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007198 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007199 InsertNewInstBefore(Shift, I);
7200
Reid Spencer68d27cf2007-03-26 23:45:51 +00007201 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007202 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007203 }
7204
7205 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007206 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007207 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007208 return 0;
7209}
7210
Chris Lattnera1be5662002-05-02 17:06:02 +00007211
Chris Lattnercfd65102005-10-29 04:36:15 +00007212/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7213/// expression. If so, decompose it, returning some value X, such that Val is
7214/// X*Scale+Offset.
7215///
7216static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007217 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007218 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007219 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007220 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007221 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007222 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007223 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7224 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7225 if (I->getOpcode() == Instruction::Shl) {
7226 // This is a value scaled by '1 << the shift amt'.
7227 Scale = 1U << RHS->getZExtValue();
7228 Offset = 0;
7229 return I->getOperand(0);
7230 } else if (I->getOpcode() == Instruction::Mul) {
7231 // This value is scaled by 'RHS'.
7232 Scale = RHS->getZExtValue();
7233 Offset = 0;
7234 return I->getOperand(0);
7235 } else if (I->getOpcode() == Instruction::Add) {
7236 // We have X+C. Check to see if we really have (X*C2)+C1,
7237 // where C1 is divisible by C2.
7238 unsigned SubScale;
7239 Value *SubVal =
7240 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7241 Offset += RHS->getZExtValue();
7242 Scale = SubScale;
7243 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007244 }
7245 }
7246 }
7247
7248 // Otherwise, we can't look past this.
7249 Scale = 1;
7250 Offset = 0;
7251 return Val;
7252}
7253
7254
Chris Lattnerb3f83972005-10-24 06:03:58 +00007255/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7256/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007257Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007258 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007259 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007260
Chris Lattnerb53c2382005-10-24 06:22:12 +00007261 // Remove any uses of AI that are dead.
7262 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007263
Chris Lattnerb53c2382005-10-24 06:22:12 +00007264 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7265 Instruction *User = cast<Instruction>(*UI++);
7266 if (isInstructionTriviallyDead(User)) {
7267 while (UI != E && *UI == User)
7268 ++UI; // If this instruction uses AI more than once, don't break UI.
7269
Chris Lattnerb53c2382005-10-24 06:22:12 +00007270 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007271 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007272 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007273 }
7274 }
7275
Chris Lattnerb3f83972005-10-24 06:03:58 +00007276 // Get the type really allocated and the type casted to.
7277 const Type *AllocElTy = AI.getAllocatedType();
7278 const Type *CastElTy = PTy->getElementType();
7279 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007280
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007281 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7282 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007283 if (CastElTyAlign < AllocElTyAlign) return 0;
7284
Chris Lattner39387a52005-10-24 06:35:18 +00007285 // If the allocation has multiple uses, only promote it if we are strictly
7286 // increasing the alignment of the resultant allocation. If we keep it the
7287 // same, we open the door to infinite loops of various kinds.
7288 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7289
Duncan Sands514ab342007-11-01 20:53:16 +00007290 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7291 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007292 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007293
Chris Lattner455fcc82005-10-29 03:19:53 +00007294 // See if we can satisfy the modulus by pulling a scale out of the array
7295 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007296 unsigned ArraySizeScale;
7297 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007298 Value *NumElements = // See if the array size is a decomposable linear expr.
7299 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7300
Chris Lattner455fcc82005-10-29 03:19:53 +00007301 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7302 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007303 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7304 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007305
Chris Lattner455fcc82005-10-29 03:19:53 +00007306 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7307 Value *Amt = 0;
7308 if (Scale == 1) {
7309 Amt = NumElements;
7310 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007311 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007312 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7313 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007314 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007315 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007316 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007317 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007318 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007319 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007320 }
7321
Jeff Cohen86796be2007-04-04 16:58:57 +00007322 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7323 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007324 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007325 Amt = InsertNewInstBefore(Tmp, AI);
7326 }
7327
Chris Lattnerb3f83972005-10-24 06:03:58 +00007328 AllocationInst *New;
7329 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007330 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007331 else
Chris Lattner6934a042007-02-11 01:23:03 +00007332 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007333 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007334 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007335
7336 // If the allocation has multiple uses, insert a cast and change all things
7337 // that used it to use the new cast. This will also hack on CI, but it will
7338 // die soon.
7339 if (!AI.hasOneUse()) {
7340 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007341 // New is the allocation instruction, pointer typed. AI is the original
7342 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7343 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007344 InsertNewInstBefore(NewCast, AI);
7345 AI.replaceAllUsesWith(NewCast);
7346 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007347 return ReplaceInstUsesWith(CI, New);
7348}
7349
Chris Lattner70074e02006-05-13 02:06:03 +00007350/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007351/// and return it as type Ty without inserting any new casts and without
7352/// changing the computed value. This is used by code that tries to decide
7353/// whether promoting or shrinking integer operations to wider or smaller types
7354/// will allow us to eliminate a truncate or extend.
7355///
7356/// This is a truncation operation if Ty is smaller than V->getType(), or an
7357/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007358bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7359 unsigned CastOpc,
7360 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007361 // We can always evaluate constants in another type.
7362 if (isa<ConstantInt>(V))
7363 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007364
7365 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007366 if (!I) return false;
7367
7368 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007369
Chris Lattner951626b2007-08-02 06:11:14 +00007370 // If this is an extension or truncate, we can often eliminate it.
7371 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7372 // If this is a cast from the destination type, we can trivially eliminate
7373 // it, and this will remove a cast overall.
7374 if (I->getOperand(0)->getType() == Ty) {
7375 // If the first operand is itself a cast, and is eliminable, do not count
7376 // this as an eliminable cast. We would prefer to eliminate those two
7377 // casts first.
7378 if (!isa<CastInst>(I->getOperand(0)))
7379 ++NumCastsRemoved;
7380 return true;
7381 }
7382 }
7383
7384 // We can't extend or shrink something that has multiple uses: doing so would
7385 // require duplicating the instruction in general, which isn't profitable.
7386 if (!I->hasOneUse()) return false;
7387
Chris Lattner70074e02006-05-13 02:06:03 +00007388 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007389 case Instruction::Add:
7390 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007391 case Instruction::And:
7392 case Instruction::Or:
7393 case Instruction::Xor:
7394 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007395 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7396 NumCastsRemoved) &&
7397 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7398 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007399
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007400 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007401 // A multiply can be truncated by truncating its operands.
7402 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7403 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7404 NumCastsRemoved) &&
7405 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7406 NumCastsRemoved);
7407
Chris Lattner46b96052006-11-29 07:18:39 +00007408 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007409 // If we are truncating the result of this SHL, and if it's a shift of a
7410 // constant amount, we can always perform a SHL in a smaller type.
7411 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007412 uint32_t BitWidth = Ty->getBitWidth();
7413 if (BitWidth < OrigTy->getBitWidth() &&
7414 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007415 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7416 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007417 }
7418 break;
7419 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007420 // If this is a truncate of a logical shr, we can truncate it to a smaller
7421 // lshr iff we know that the bits we would otherwise be shifting in are
7422 // already zeros.
7423 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007424 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7425 uint32_t BitWidth = Ty->getBitWidth();
7426 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007427 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007428 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7429 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007430 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7431 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007432 }
7433 }
Chris Lattner46b96052006-11-29 07:18:39 +00007434 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007435 case Instruction::ZExt:
7436 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007437 case Instruction::Trunc:
7438 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007439 // can safely replace it. Note that replacing it does not reduce the number
7440 // of casts in the input.
7441 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007442 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007443
Reid Spencer3da59db2006-11-27 01:05:10 +00007444 break;
7445 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007446 // TODO: Can handle more cases here.
7447 break;
7448 }
7449
7450 return false;
7451}
7452
7453/// EvaluateInDifferentType - Given an expression that
7454/// CanEvaluateInDifferentType returns true for, actually insert the code to
7455/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007456Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007457 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007458 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007459 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007460
7461 // Otherwise, it must be an instruction.
7462 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007463 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007464 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007465 case Instruction::Add:
7466 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007467 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007468 case Instruction::And:
7469 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007470 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007471 case Instruction::AShr:
7472 case Instruction::LShr:
7473 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007474 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007475 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007476 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007477 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007478 break;
7479 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007480 case Instruction::Trunc:
7481 case Instruction::ZExt:
7482 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007483 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007484 // just return the source. There's no need to insert it because it is not
7485 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007486 if (I->getOperand(0)->getType() == Ty)
7487 return I->getOperand(0);
7488
Chris Lattner951626b2007-08-02 06:11:14 +00007489 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007490 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007491 Ty, I->getName());
7492 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007493 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007494 // TODO: Can handle more cases here.
7495 assert(0 && "Unreachable!");
7496 break;
7497 }
7498
7499 return InsertNewInstBefore(Res, *I);
7500}
7501
Reid Spencer3da59db2006-11-27 01:05:10 +00007502/// @brief Implement the transforms common to all CastInst visitors.
7503Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007504 Value *Src = CI.getOperand(0);
7505
Dan Gohman23d9d272007-05-11 21:10:54 +00007506 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007507 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007508 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007509 if (Instruction::CastOps opc =
7510 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7511 // The first cast (CSrc) is eliminable so we need to fix up or replace
7512 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007513 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007514 }
7515 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007516
Reid Spencer3da59db2006-11-27 01:05:10 +00007517 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007518 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7519 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7520 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007521
7522 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007523 if (isa<PHINode>(Src))
7524 if (Instruction *NV = FoldOpIntoPhi(CI))
7525 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007526
Reid Spencer3da59db2006-11-27 01:05:10 +00007527 return 0;
7528}
7529
Chris Lattnerd3e28342007-04-27 17:44:50 +00007530/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7531Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7532 Value *Src = CI.getOperand(0);
7533
Chris Lattnerd3e28342007-04-27 17:44:50 +00007534 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007535 // If casting the result of a getelementptr instruction with no offset, turn
7536 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007537 if (GEP->hasAllZeroIndices()) {
7538 // Changing the cast operand is usually not a good idea but it is safe
7539 // here because the pointer operand is being replaced with another
7540 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007541 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007542 CI.setOperand(0, GEP->getOperand(0));
7543 return &CI;
7544 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007545
7546 // If the GEP has a single use, and the base pointer is a bitcast, and the
7547 // GEP computes a constant offset, see if we can convert these three
7548 // instructions into fewer. This typically happens with unions and other
7549 // non-type-safe code.
7550 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7551 if (GEP->hasAllConstantIndices()) {
7552 // We are guaranteed to get a constant from EmitGEPOffset.
7553 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7554 int64_t Offset = OffsetV->getSExtValue();
7555
7556 // Get the base pointer input of the bitcast, and the type it points to.
7557 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7558 const Type *GEPIdxTy =
7559 cast<PointerType>(OrigBase->getType())->getElementType();
7560 if (GEPIdxTy->isSized()) {
7561 SmallVector<Value*, 8> NewIndices;
7562
Chris Lattnerc42e2262007-05-05 01:59:31 +00007563 // Start with the index over the outer type. Note that the type size
7564 // might be zero (even if the offset isn't zero) if the indexed type
7565 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007566 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007567 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007568 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007569 FirstIdx = Offset/TySize;
7570 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007571
Chris Lattnerc42e2262007-05-05 01:59:31 +00007572 // Handle silly modulus not returning values values [0..TySize).
7573 if (Offset < 0) {
7574 --FirstIdx;
7575 Offset += TySize;
7576 assert(Offset >= 0);
7577 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007578 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007579 }
7580
7581 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007582
7583 // Index into the types. If we fail, set OrigBase to null.
7584 while (Offset) {
7585 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7586 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007587 if (Offset < (int64_t)SL->getSizeInBytes()) {
7588 unsigned Elt = SL->getElementContainingOffset(Offset);
7589 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007590
Chris Lattner6b6aef82007-05-15 00:16:00 +00007591 Offset -= SL->getElementOffset(Elt);
7592 GEPIdxTy = STy->getElementType(Elt);
7593 } else {
7594 // Otherwise, we can't index into this, bail out.
7595 Offset = 0;
7596 OrigBase = 0;
7597 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007598 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7599 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007600 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007601 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7602 Offset %= EltSize;
7603 } else {
7604 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7605 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007606 GEPIdxTy = STy->getElementType();
7607 } else {
7608 // Otherwise, we can't index into this, bail out.
7609 Offset = 0;
7610 OrigBase = 0;
7611 }
7612 }
7613 if (OrigBase) {
7614 // If we were able to index down into an element, create the GEP
7615 // and bitcast the result. This eliminates one bitcast, potentially
7616 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007617 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7618 NewIndices.begin(),
7619 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007620 InsertNewInstBefore(NGEP, CI);
7621 NGEP->takeName(GEP);
7622
Chris Lattner9bc14642007-04-28 00:57:34 +00007623 if (isa<BitCastInst>(CI))
7624 return new BitCastInst(NGEP, CI.getType());
7625 assert(isa<PtrToIntInst>(CI));
7626 return new PtrToIntInst(NGEP, CI.getType());
7627 }
7628 }
7629 }
7630 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007631 }
7632
7633 return commonCastTransforms(CI);
7634}
7635
7636
7637
Chris Lattnerc739cd62007-03-03 05:27:34 +00007638/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7639/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007640/// cases.
7641/// @brief Implement the transforms common to CastInst with integer operands
7642Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7643 if (Instruction *Result = commonCastTransforms(CI))
7644 return Result;
7645
7646 Value *Src = CI.getOperand(0);
7647 const Type *SrcTy = Src->getType();
7648 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007649 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7650 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007651
Reid Spencer3da59db2006-11-27 01:05:10 +00007652 // See if we can simplify any instructions used by the LHS whose sole
7653 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007654 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7655 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007656 KnownZero, KnownOne))
7657 return &CI;
7658
7659 // If the source isn't an instruction or has more than one use then we
7660 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007661 Instruction *SrcI = dyn_cast<Instruction>(Src);
7662 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007663 return 0;
7664
Chris Lattnerc739cd62007-03-03 05:27:34 +00007665 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007666 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007667 if (!isa<BitCastInst>(CI) &&
7668 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007669 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007670 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007671 // eliminates the cast, so it is always a win. If this is a zero-extension,
7672 // we need to do an AND to maintain the clear top-part of the computation,
7673 // so we require that the input have eliminated at least one cast. If this
7674 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007675 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007676 bool DoXForm;
7677 switch (CI.getOpcode()) {
7678 default:
7679 // All the others use floating point so we shouldn't actually
7680 // get here because of the check above.
7681 assert(0 && "Unknown cast type");
7682 case Instruction::Trunc:
7683 DoXForm = true;
7684 break;
7685 case Instruction::ZExt:
7686 DoXForm = NumCastsRemoved >= 1;
7687 break;
7688 case Instruction::SExt:
7689 DoXForm = NumCastsRemoved >= 2;
7690 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007691 }
7692
7693 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007694 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7695 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007696 assert(Res->getType() == DestTy);
7697 switch (CI.getOpcode()) {
7698 default: assert(0 && "Unknown cast type!");
7699 case Instruction::Trunc:
7700 case Instruction::BitCast:
7701 // Just replace this cast with the result.
7702 return ReplaceInstUsesWith(CI, Res);
7703 case Instruction::ZExt: {
7704 // We need to emit an AND to clear the high bits.
7705 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007706 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7707 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007708 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007709 }
7710 case Instruction::SExt:
7711 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007712 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007713 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7714 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007715 }
7716 }
7717 }
7718
7719 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7720 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7721
7722 switch (SrcI->getOpcode()) {
7723 case Instruction::Add:
7724 case Instruction::Mul:
7725 case Instruction::And:
7726 case Instruction::Or:
7727 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007728 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007729 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7730 // Don't insert two casts if they cannot be eliminated. We allow
7731 // two casts to be inserted if the sizes are the same. This could
7732 // only be converting signedness, which is a noop.
7733 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007734 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7735 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007736 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007737 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7738 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007739 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007740 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007741 }
7742 }
7743
7744 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7745 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7746 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007747 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007748 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007749 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007750 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007751 }
7752 break;
7753 case Instruction::SDiv:
7754 case Instruction::UDiv:
7755 case Instruction::SRem:
7756 case Instruction::URem:
7757 // If we are just changing the sign, rewrite.
7758 if (DestBitSize == SrcBitSize) {
7759 // Don't insert two casts if they cannot be eliminated. We allow
7760 // two casts to be inserted if the sizes are the same. This could
7761 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007762 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7763 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007764 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7765 Op0, DestTy, SrcI);
7766 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7767 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007768 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007769 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7770 }
7771 }
7772 break;
7773
7774 case Instruction::Shl:
7775 // Allow changing the sign of the source operand. Do not allow
7776 // changing the size of the shift, UNLESS the shift amount is a
7777 // constant. We must not change variable sized shifts to a smaller
7778 // size, because it is undefined to shift more bits out than exist
7779 // in the value.
7780 if (DestBitSize == SrcBitSize ||
7781 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007782 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7783 Instruction::BitCast : Instruction::Trunc);
7784 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007785 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007786 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007787 }
7788 break;
7789 case Instruction::AShr:
7790 // If this is a signed shr, and if all bits shifted in are about to be
7791 // truncated off, turn it into an unsigned shr to allow greater
7792 // simplifications.
7793 if (DestBitSize < SrcBitSize &&
7794 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007795 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007796 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7797 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007798 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007799 }
7800 }
7801 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007802 }
7803 return 0;
7804}
7805
Chris Lattner8a9f5712007-04-11 06:57:46 +00007806Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007807 if (Instruction *Result = commonIntCastTransforms(CI))
7808 return Result;
7809
7810 Value *Src = CI.getOperand(0);
7811 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007812 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7813 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007814
7815 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7816 switch (SrcI->getOpcode()) {
7817 default: break;
7818 case Instruction::LShr:
7819 // We can shrink lshr to something smaller if we know the bits shifted in
7820 // are already zeros.
7821 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007822 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007823
7824 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007825 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007826 Value* SrcIOp0 = SrcI->getOperand(0);
7827 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007828 if (ShAmt >= DestBitWidth) // All zeros.
7829 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7830
7831 // Okay, we can shrink this. Truncate the input, then return a new
7832 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007833 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7834 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7835 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007836 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007837 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007838 } else { // This is a variable shr.
7839
7840 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7841 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7842 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007843 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007844 Value *One = ConstantInt::get(SrcI->getType(), 1);
7845
Reid Spencer832254e2007-02-02 02:16:23 +00007846 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007847 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007848 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007849 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007850 SrcI->getOperand(0),
7851 "tmp"), CI);
7852 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007853 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007854 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007855 }
7856 break;
7857 }
7858 }
7859
7860 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007861}
7862
Evan Chengb98a10e2008-03-24 00:21:34 +00007863/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7864/// in order to eliminate the icmp.
7865Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7866 bool DoXform) {
7867 // If we are just checking for a icmp eq of a single bit and zext'ing it
7868 // to an integer, then shift the bit to the appropriate place and then
7869 // cast to integer to avoid the comparison.
7870 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7871 const APInt &Op1CV = Op1C->getValue();
7872
7873 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7874 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7875 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7876 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7877 if (!DoXform) return ICI;
7878
7879 Value *In = ICI->getOperand(0);
7880 Value *Sh = ConstantInt::get(In->getType(),
7881 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007882 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007883 In->getName()+".lobit"),
7884 CI);
7885 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007886 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007887 false/*ZExt*/, "tmp", &CI);
7888
7889 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7890 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007891 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007892 In->getName()+".not"),
7893 CI);
7894 }
7895
7896 return ReplaceInstUsesWith(CI, In);
7897 }
7898
7899
7900
7901 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7902 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7903 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7904 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7905 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7906 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7907 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7908 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7909 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7910 // This only works for EQ and NE
7911 ICI->isEquality()) {
7912 // If Op1C some other power of two, convert:
7913 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7914 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7915 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7916 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7917
7918 APInt KnownZeroMask(~KnownZero);
7919 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7920 if (!DoXform) return ICI;
7921
7922 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7923 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7924 // (X&4) == 2 --> false
7925 // (X&4) != 2 --> true
7926 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7927 Res = ConstantExpr::getZExt(Res, CI.getType());
7928 return ReplaceInstUsesWith(CI, Res);
7929 }
7930
7931 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7932 Value *In = ICI->getOperand(0);
7933 if (ShiftAmt) {
7934 // Perform a logical shr by shiftamt.
7935 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007936 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007937 ConstantInt::get(In->getType(), ShiftAmt),
7938 In->getName()+".lobit"), CI);
7939 }
7940
7941 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7942 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007943 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007944 InsertNewInstBefore(cast<Instruction>(In), CI);
7945 }
7946
7947 if (CI.getType() == In->getType())
7948 return ReplaceInstUsesWith(CI, In);
7949 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007950 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007951 }
7952 }
7953 }
7954
7955 return 0;
7956}
7957
Chris Lattner8a9f5712007-04-11 06:57:46 +00007958Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007959 // If one of the common conversion will work ..
7960 if (Instruction *Result = commonIntCastTransforms(CI))
7961 return Result;
7962
7963 Value *Src = CI.getOperand(0);
7964
7965 // If this is a cast of a cast
7966 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007967 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7968 // types and if the sizes are just right we can convert this into a logical
7969 // 'and' which will be much cheaper than the pair of casts.
7970 if (isa<TruncInst>(CSrc)) {
7971 // Get the sizes of the types involved
7972 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007973 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7974 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7975 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007976 // If we're actually extending zero bits and the trunc is a no-op
7977 if (MidSize < DstSize && SrcSize == DstSize) {
7978 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007979 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007980 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007981 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007982 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007983 // Unfortunately, if the type changed, we need to cast it back.
7984 if (And->getType() != CI.getType()) {
7985 And->setName(CSrc->getName()+".mask");
7986 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007987 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007988 }
7989 return And;
7990 }
7991 }
7992 }
7993
Evan Chengb98a10e2008-03-24 00:21:34 +00007994 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7995 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007996
Evan Chengb98a10e2008-03-24 00:21:34 +00007997 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7998 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7999 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8000 // of the (zext icmp) will be transformed.
8001 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8002 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8003 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8004 (transformZExtICmp(LHS, CI, false) ||
8005 transformZExtICmp(RHS, CI, false))) {
8006 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8007 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008008 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008009 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008010 }
8011
Reid Spencer3da59db2006-11-27 01:05:10 +00008012 return 0;
8013}
8014
Chris Lattner8a9f5712007-04-11 06:57:46 +00008015Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008016 if (Instruction *I = commonIntCastTransforms(CI))
8017 return I;
8018
Chris Lattner8a9f5712007-04-11 06:57:46 +00008019 Value *Src = CI.getOperand(0);
8020
8021 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8022 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8023 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8024 // If we are just checking for a icmp eq of a single bit and zext'ing it
8025 // to an integer, then shift the bit to the appropriate place and then
8026 // cast to integer to avoid the comparison.
8027 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8028 const APInt &Op1CV = Op1C->getValue();
8029
8030 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8031 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8032 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8033 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8034 Value *In = ICI->getOperand(0);
8035 Value *Sh = ConstantInt::get(In->getType(),
8036 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008037 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008038 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008039 CI);
8040 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008041 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008042 true/*SExt*/, "tmp", &CI);
8043
8044 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008045 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008046 In->getName()+".not"), CI);
8047
8048 return ReplaceInstUsesWith(CI, In);
8049 }
8050 }
8051 }
8052
Chris Lattnerba417832007-04-11 06:12:58 +00008053 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008054}
8055
Chris Lattnerb7530652008-01-27 05:29:54 +00008056/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8057/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008058static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008059 APFloat F = CFP->getValueAPF();
8060 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008061 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008062 return 0;
8063}
8064
8065/// LookThroughFPExtensions - If this is an fp extension instruction, look
8066/// through it until we get the source value.
8067static Value *LookThroughFPExtensions(Value *V) {
8068 if (Instruction *I = dyn_cast<Instruction>(V))
8069 if (I->getOpcode() == Instruction::FPExt)
8070 return LookThroughFPExtensions(I->getOperand(0));
8071
8072 // If this value is a constant, return the constant in the smallest FP type
8073 // that can accurately represent it. This allows us to turn
8074 // (float)((double)X+2.0) into x+2.0f.
8075 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8076 if (CFP->getType() == Type::PPC_FP128Ty)
8077 return V; // No constant folding of this.
8078 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008079 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008080 return V;
8081 if (CFP->getType() == Type::DoubleTy)
8082 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008083 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008084 return V;
8085 // Don't try to shrink to various long double types.
8086 }
8087
8088 return V;
8089}
8090
8091Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8092 if (Instruction *I = commonCastTransforms(CI))
8093 return I;
8094
8095 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8096 // smaller than the destination type, we can eliminate the truncate by doing
8097 // the add as the smaller type. This applies to add/sub/mul/div as well as
8098 // many builtins (sqrt, etc).
8099 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8100 if (OpI && OpI->hasOneUse()) {
8101 switch (OpI->getOpcode()) {
8102 default: break;
8103 case Instruction::Add:
8104 case Instruction::Sub:
8105 case Instruction::Mul:
8106 case Instruction::FDiv:
8107 case Instruction::FRem:
8108 const Type *SrcTy = OpI->getType();
8109 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8110 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8111 if (LHSTrunc->getType() != SrcTy &&
8112 RHSTrunc->getType() != SrcTy) {
8113 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8114 // If the source types were both smaller than the destination type of
8115 // the cast, do this xform.
8116 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8117 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8118 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8119 CI.getType(), CI);
8120 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8121 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008122 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008123 }
8124 }
8125 break;
8126 }
8127 }
8128 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008129}
8130
8131Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8132 return commonCastTransforms(CI);
8133}
8134
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008135Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8136 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8137 // mantissa to accurately represent all values of X. For example, do not
8138 // do this with i64->float->i64.
8139 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8140 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8141 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008142 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008143 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8144
8145 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008146}
8147
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008148Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8149 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8150 // mantissa to accurately represent all values of X. For example, do not
8151 // do this with i64->float->i64.
8152 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8153 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8154 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008155 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008156 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8157
8158 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008159}
8160
8161Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8162 return commonCastTransforms(CI);
8163}
8164
8165Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8166 return commonCastTransforms(CI);
8167}
8168
8169Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008170 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008171}
8172
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008173Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8174 if (Instruction *I = commonCastTransforms(CI))
8175 return I;
8176
8177 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8178 if (!DestPointee->isSized()) return 0;
8179
8180 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8181 ConstantInt *Cst;
8182 Value *X;
8183 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8184 m_ConstantInt(Cst)))) {
8185 // If the source and destination operands have the same type, see if this
8186 // is a single-index GEP.
8187 if (X->getType() == CI.getType()) {
8188 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008189 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008190
8191 // Convert the constant to intptr type.
8192 APInt Offset = Cst->getValue();
8193 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8194
8195 // If Offset is evenly divisible by Size, we can do this xform.
8196 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8197 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008198 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008199 }
8200 }
8201 // TODO: Could handle other cases, e.g. where add is indexing into field of
8202 // struct etc.
8203 } else if (CI.getOperand(0)->hasOneUse() &&
8204 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8205 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8206 // "inttoptr+GEP" instead of "add+intptr".
8207
8208 // Get the size of the pointee type.
8209 uint64_t Size = TD->getABITypeSize(DestPointee);
8210
8211 // Convert the constant to intptr type.
8212 APInt Offset = Cst->getValue();
8213 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8214
8215 // If Offset is evenly divisible by Size, we can do this xform.
8216 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8217 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8218
8219 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8220 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008221 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008222 }
8223 }
8224 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008225}
8226
Chris Lattnerd3e28342007-04-27 17:44:50 +00008227Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008228 // If the operands are integer typed then apply the integer transforms,
8229 // otherwise just apply the common ones.
8230 Value *Src = CI.getOperand(0);
8231 const Type *SrcTy = Src->getType();
8232 const Type *DestTy = CI.getType();
8233
Chris Lattner42a75512007-01-15 02:27:26 +00008234 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008235 if (Instruction *Result = commonIntCastTransforms(CI))
8236 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008237 } else if (isa<PointerType>(SrcTy)) {
8238 if (Instruction *I = commonPointerCastTransforms(CI))
8239 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008240 } else {
8241 if (Instruction *Result = commonCastTransforms(CI))
8242 return Result;
8243 }
8244
8245
8246 // Get rid of casts from one type to the same type. These are useless and can
8247 // be replaced by the operand.
8248 if (DestTy == Src->getType())
8249 return ReplaceInstUsesWith(CI, Src);
8250
Reid Spencer3da59db2006-11-27 01:05:10 +00008251 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008252 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8253 const Type *DstElTy = DstPTy->getElementType();
8254 const Type *SrcElTy = SrcPTy->getElementType();
8255
Nate Begeman83ad90a2008-03-31 00:22:16 +00008256 // If the address spaces don't match, don't eliminate the bitcast, which is
8257 // required for changing types.
8258 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8259 return 0;
8260
Chris Lattnerd3e28342007-04-27 17:44:50 +00008261 // If we are casting a malloc or alloca to a pointer to a type of the same
8262 // size, rewrite the allocation instruction to allocate the "right" type.
8263 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8264 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8265 return V;
8266
Chris Lattnerd717c182007-05-05 22:32:24 +00008267 // If the source and destination are pointers, and this cast is equivalent
8268 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008269 // This can enhance SROA and other transforms that want type-safe pointers.
8270 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8271 unsigned NumZeros = 0;
8272 while (SrcElTy != DstElTy &&
8273 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8274 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8275 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8276 ++NumZeros;
8277 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008278
Chris Lattnerd3e28342007-04-27 17:44:50 +00008279 // If we found a path from the src to dest, create the getelementptr now.
8280 if (SrcElTy == DstElTy) {
8281 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008282 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8283 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008284 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008285 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008286
Reid Spencer3da59db2006-11-27 01:05:10 +00008287 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8288 if (SVI->hasOneUse()) {
8289 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8290 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008291 if (isa<VectorType>(DestTy) &&
8292 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008293 SVI->getType()->getNumElements()) {
8294 CastInst *Tmp;
8295 // If either of the operands is a cast from CI.getType(), then
8296 // evaluating the shuffle in the casted destination's type will allow
8297 // us to eliminate at least one cast.
8298 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8299 Tmp->getOperand(0)->getType() == DestTy) ||
8300 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8301 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008302 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8303 SVI->getOperand(0), DestTy, &CI);
8304 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8305 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008306 // Return a new shuffle vector. Use the same element ID's, as we
8307 // know the vector types match #elts.
8308 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008309 }
8310 }
8311 }
8312 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008313 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008314}
8315
Chris Lattnere576b912004-04-09 23:46:01 +00008316/// GetSelectFoldableOperands - We want to turn code that looks like this:
8317/// %C = or %A, %B
8318/// %D = select %cond, %C, %A
8319/// into:
8320/// %C = select %cond, %B, 0
8321/// %D = or %A, %C
8322///
8323/// Assuming that the specified instruction is an operand to the select, return
8324/// a bitmask indicating which operands of this instruction are foldable if they
8325/// equal the other incoming value of the select.
8326///
8327static unsigned GetSelectFoldableOperands(Instruction *I) {
8328 switch (I->getOpcode()) {
8329 case Instruction::Add:
8330 case Instruction::Mul:
8331 case Instruction::And:
8332 case Instruction::Or:
8333 case Instruction::Xor:
8334 return 3; // Can fold through either operand.
8335 case Instruction::Sub: // Can only fold on the amount subtracted.
8336 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008337 case Instruction::LShr:
8338 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008339 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008340 default:
8341 return 0; // Cannot fold
8342 }
8343}
8344
8345/// GetSelectFoldableConstant - For the same transformation as the previous
8346/// function, return the identity constant that goes into the select.
8347static Constant *GetSelectFoldableConstant(Instruction *I) {
8348 switch (I->getOpcode()) {
8349 default: assert(0 && "This cannot happen!"); abort();
8350 case Instruction::Add:
8351 case Instruction::Sub:
8352 case Instruction::Or:
8353 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008354 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008355 case Instruction::LShr:
8356 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008357 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008358 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008359 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008360 case Instruction::Mul:
8361 return ConstantInt::get(I->getType(), 1);
8362 }
8363}
8364
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008365/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8366/// have the same opcode and only one use each. Try to simplify this.
8367Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8368 Instruction *FI) {
8369 if (TI->getNumOperands() == 1) {
8370 // If this is a non-volatile load or a cast from the same type,
8371 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008372 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008373 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8374 return 0;
8375 } else {
8376 return 0; // unknown unary op.
8377 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008378
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008379 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008380 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8381 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008382 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008383 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008384 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008385 }
8386
Reid Spencer832254e2007-02-02 02:16:23 +00008387 // Only handle binary operators here.
8388 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008389 return 0;
8390
8391 // Figure out if the operations have any operands in common.
8392 Value *MatchOp, *OtherOpT, *OtherOpF;
8393 bool MatchIsOpZero;
8394 if (TI->getOperand(0) == FI->getOperand(0)) {
8395 MatchOp = TI->getOperand(0);
8396 OtherOpT = TI->getOperand(1);
8397 OtherOpF = FI->getOperand(1);
8398 MatchIsOpZero = true;
8399 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8400 MatchOp = TI->getOperand(1);
8401 OtherOpT = TI->getOperand(0);
8402 OtherOpF = FI->getOperand(0);
8403 MatchIsOpZero = false;
8404 } else if (!TI->isCommutative()) {
8405 return 0;
8406 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8407 MatchOp = TI->getOperand(0);
8408 OtherOpT = TI->getOperand(1);
8409 OtherOpF = FI->getOperand(0);
8410 MatchIsOpZero = true;
8411 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8412 MatchOp = TI->getOperand(1);
8413 OtherOpT = TI->getOperand(0);
8414 OtherOpF = FI->getOperand(1);
8415 MatchIsOpZero = true;
8416 } else {
8417 return 0;
8418 }
8419
8420 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008421 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8422 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008423 InsertNewInstBefore(NewSI, SI);
8424
8425 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8426 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008427 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008428 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008429 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008430 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008431 assert(0 && "Shouldn't get here");
8432 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008433}
8434
Chris Lattner3d69f462004-03-12 05:52:32 +00008435Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008436 Value *CondVal = SI.getCondition();
8437 Value *TrueVal = SI.getTrueValue();
8438 Value *FalseVal = SI.getFalseValue();
8439
8440 // select true, X, Y -> X
8441 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008442 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008443 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008444
8445 // select C, X, X -> X
8446 if (TrueVal == FalseVal)
8447 return ReplaceInstUsesWith(SI, TrueVal);
8448
Chris Lattnere87597f2004-10-16 18:11:37 +00008449 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8450 return ReplaceInstUsesWith(SI, FalseVal);
8451 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8452 return ReplaceInstUsesWith(SI, TrueVal);
8453 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8454 if (isa<Constant>(TrueVal))
8455 return ReplaceInstUsesWith(SI, TrueVal);
8456 else
8457 return ReplaceInstUsesWith(SI, FalseVal);
8458 }
8459
Reid Spencer4fe16d62007-01-11 18:21:29 +00008460 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008461 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008462 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008463 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008464 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008465 } else {
8466 // Change: A = select B, false, C --> A = and !B, C
8467 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008468 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008469 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008470 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008471 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008472 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008473 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008474 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008475 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008476 } else {
8477 // Change: A = select B, C, true --> A = or !B, C
8478 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008479 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008480 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008481 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008482 }
8483 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008484
8485 // select a, b, a -> a&b
8486 // select a, a, b -> a|b
8487 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008488 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008489 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008490 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008491 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008492
Chris Lattner2eefe512004-04-09 19:05:30 +00008493 // Selecting between two integer constants?
8494 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8495 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008496 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008497 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008498 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008499 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008500 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008501 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008502 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008503 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008504 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008505 }
Chris Lattnerba417832007-04-11 06:12:58 +00008506
8507 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008508
Reid Spencere4d87aa2006-12-23 06:05:41 +00008509 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008510
Reid Spencere4d87aa2006-12-23 06:05:41 +00008511 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008512 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008513 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008514 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008515 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008516 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008517 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008518 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008519 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008520 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008521 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008522 InsertNewInstBefore(SRA, SI);
8523
Reid Spencer3da59db2006-11-27 01:05:10 +00008524 // Finally, convert to the type of the select RHS. We figure out
8525 // if this requires a SExt, Trunc or BitCast based on the sizes.
8526 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008527 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8528 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008529 if (SRASize < SISize)
8530 opc = Instruction::SExt;
8531 else if (SRASize > SISize)
8532 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008533 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008534 }
8535 }
8536
8537
8538 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008539 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008540 // non-constant value, eliminate this whole mess. This corresponds to
8541 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008542 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008543 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008544 cast<Constant>(IC->getOperand(1))->isNullValue())
8545 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8546 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008547 isa<ConstantInt>(ICA->getOperand(1)) &&
8548 (ICA->getOperand(1) == TrueValC ||
8549 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008550 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8551 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008552 // know whether we have a icmp_ne or icmp_eq and whether the
8553 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008554 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008555 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008556 Value *V = ICA;
8557 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008558 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008559 Instruction::Xor, V, ICA->getOperand(1)), SI);
8560 return ReplaceInstUsesWith(SI, V);
8561 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008562 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008563 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008564
8565 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008566 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8567 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008568 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008569 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8570 // This is not safe in general for floating point:
8571 // consider X== -0, Y== +0.
8572 // It becomes safe if either operand is a nonzero constant.
8573 ConstantFP *CFPt, *CFPf;
8574 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8575 !CFPt->getValueAPF().isZero()) ||
8576 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8577 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008578 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008579 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008580 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008581 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008582 return ReplaceInstUsesWith(SI, TrueVal);
8583 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8584
Reid Spencere4d87aa2006-12-23 06:05:41 +00008585 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008586 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008587 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8588 // This is not safe in general for floating point:
8589 // consider X== -0, Y== +0.
8590 // It becomes safe if either operand is a nonzero constant.
8591 ConstantFP *CFPt, *CFPf;
8592 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8593 !CFPt->getValueAPF().isZero()) ||
8594 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8595 !CFPf->getValueAPF().isZero()))
8596 return ReplaceInstUsesWith(SI, FalseVal);
8597 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008598 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008599 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8600 return ReplaceInstUsesWith(SI, TrueVal);
8601 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8602 }
8603 }
8604
8605 // See if we are selecting two values based on a comparison of the two values.
8606 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8607 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8608 // Transform (X == Y) ? X : Y -> Y
8609 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8610 return ReplaceInstUsesWith(SI, FalseVal);
8611 // Transform (X != Y) ? X : Y -> X
8612 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8613 return ReplaceInstUsesWith(SI, TrueVal);
8614 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8615
8616 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8617 // Transform (X == Y) ? Y : X -> X
8618 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8619 return ReplaceInstUsesWith(SI, FalseVal);
8620 // Transform (X != Y) ? Y : X -> Y
8621 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008622 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008623 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8624 }
8625 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008626
Chris Lattner87875da2005-01-13 22:52:24 +00008627 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8628 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8629 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008630 Instruction *AddOp = 0, *SubOp = 0;
8631
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008632 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8633 if (TI->getOpcode() == FI->getOpcode())
8634 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8635 return IV;
8636
8637 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8638 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008639 if (TI->getOpcode() == Instruction::Sub &&
8640 FI->getOpcode() == Instruction::Add) {
8641 AddOp = FI; SubOp = TI;
8642 } else if (FI->getOpcode() == Instruction::Sub &&
8643 TI->getOpcode() == Instruction::Add) {
8644 AddOp = TI; SubOp = FI;
8645 }
8646
8647 if (AddOp) {
8648 Value *OtherAddOp = 0;
8649 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8650 OtherAddOp = AddOp->getOperand(1);
8651 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8652 OtherAddOp = AddOp->getOperand(0);
8653 }
8654
8655 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008656 // So at this point we know we have (Y -> OtherAddOp):
8657 // select C, (add X, Y), (sub X, Z)
8658 Value *NegVal; // Compute -Z
8659 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8660 NegVal = ConstantExpr::getNeg(C);
8661 } else {
8662 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008663 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008664 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008665
8666 Value *NewTrueOp = OtherAddOp;
8667 Value *NewFalseOp = NegVal;
8668 if (AddOp != TI)
8669 std::swap(NewTrueOp, NewFalseOp);
8670 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008671 SelectInst::Create(CondVal, NewTrueOp,
8672 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008673
8674 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008675 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008676 }
8677 }
8678 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008679
Chris Lattnere576b912004-04-09 23:46:01 +00008680 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008681 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008682 // See the comment above GetSelectFoldableOperands for a description of the
8683 // transformation we are doing here.
8684 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8685 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8686 !isa<Constant>(FalseVal))
8687 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8688 unsigned OpToFold = 0;
8689 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8690 OpToFold = 1;
8691 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8692 OpToFold = 2;
8693 }
8694
8695 if (OpToFold) {
8696 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008697 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008698 SelectInst::Create(SI.getCondition(),
8699 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008700 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008701 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008702 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008703 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008704 else {
8705 assert(0 && "Unknown instruction!!");
8706 }
8707 }
8708 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008709
Chris Lattnere576b912004-04-09 23:46:01 +00008710 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8711 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8712 !isa<Constant>(TrueVal))
8713 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8714 unsigned OpToFold = 0;
8715 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8716 OpToFold = 1;
8717 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8718 OpToFold = 2;
8719 }
8720
8721 if (OpToFold) {
8722 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008723 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008724 SelectInst::Create(SI.getCondition(), C,
8725 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008726 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008727 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008728 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008729 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008730 else
Chris Lattnere576b912004-04-09 23:46:01 +00008731 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008732 }
8733 }
8734 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008735
8736 if (BinaryOperator::isNot(CondVal)) {
8737 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8738 SI.setOperand(1, FalseVal);
8739 SI.setOperand(2, TrueVal);
8740 return &SI;
8741 }
8742
Chris Lattner3d69f462004-03-12 05:52:32 +00008743 return 0;
8744}
8745
Dan Gohmaneee962e2008-04-10 18:43:06 +00008746/// EnforceKnownAlignment - If the specified pointer points to an object that
8747/// we control, modify the object's alignment to PrefAlign. This isn't
8748/// often possible though. If alignment is important, a more reliable approach
8749/// is to simply align all global variables and allocation instructions to
8750/// their preferred alignment from the beginning.
8751///
8752static unsigned EnforceKnownAlignment(Value *V,
8753 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008754
Dan Gohmaneee962e2008-04-10 18:43:06 +00008755 User *U = dyn_cast<User>(V);
8756 if (!U) return Align;
8757
8758 switch (getOpcode(U)) {
8759 default: break;
8760 case Instruction::BitCast:
8761 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8762 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008763 // If all indexes are zero, it is just the alignment of the base pointer.
8764 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008765 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8766 if (!isa<Constant>(U->getOperand(i)) ||
8767 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008768 AllZeroOperands = false;
8769 break;
8770 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008771
8772 if (AllZeroOperands) {
8773 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008774 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008775 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008776 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008777 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008778 }
8779
8780 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8781 // If there is a large requested alignment and we can, bump up the alignment
8782 // of the global.
8783 if (!GV->isDeclaration()) {
8784 GV->setAlignment(PrefAlign);
8785 Align = PrefAlign;
8786 }
8787 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8788 // If there is a requested alignment and if this is an alloca, round up. We
8789 // don't do this for malloc, because some systems can't respect the request.
8790 if (isa<AllocaInst>(AI)) {
8791 AI->setAlignment(PrefAlign);
8792 Align = PrefAlign;
8793 }
8794 }
8795
8796 return Align;
8797}
8798
8799/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8800/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8801/// and it is more than the alignment of the ultimate object, see if we can
8802/// increase the alignment of the ultimate object, making this check succeed.
8803unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8804 unsigned PrefAlign) {
8805 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8806 sizeof(PrefAlign) * CHAR_BIT;
8807 APInt Mask = APInt::getAllOnesValue(BitWidth);
8808 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8809 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8810 unsigned TrailZ = KnownZero.countTrailingOnes();
8811 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8812
8813 if (PrefAlign > Align)
8814 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8815
8816 // We don't need to make any adjustment.
8817 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008818}
8819
Chris Lattnerf497b022008-01-13 23:50:23 +00008820Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008821 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8822 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008823 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8824 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8825
8826 if (CopyAlign < MinAlign) {
8827 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8828 return MI;
8829 }
8830
8831 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8832 // load/store.
8833 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8834 if (MemOpLength == 0) return 0;
8835
Chris Lattner37ac6082008-01-14 00:28:35 +00008836 // Source and destination pointer types are always "i8*" for intrinsic. See
8837 // if the size is something we can handle with a single primitive load/store.
8838 // A single load+store correctly handles overlapping memory in the memmove
8839 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008840 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008841 if (Size == 0) return MI; // Delete this mem transfer.
8842
8843 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008844 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008845
Chris Lattner37ac6082008-01-14 00:28:35 +00008846 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008847 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008848
8849 // Memcpy forces the use of i8* for the source and destination. That means
8850 // that if you're using memcpy to move one double around, you'll get a cast
8851 // from double* to i8*. We'd much rather use a double load+store rather than
8852 // an i64 load+store, here because this improves the odds that the source or
8853 // dest address will be promotable. See if we can find a better type than the
8854 // integer datatype.
8855 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8856 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8857 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8858 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8859 // down through these levels if so.
8860 while (!SrcETy->isFirstClassType()) {
8861 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8862 if (STy->getNumElements() == 1)
8863 SrcETy = STy->getElementType(0);
8864 else
8865 break;
8866 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8867 if (ATy->getNumElements() == 1)
8868 SrcETy = ATy->getElementType();
8869 else
8870 break;
8871 } else
8872 break;
8873 }
8874
8875 if (SrcETy->isFirstClassType())
8876 NewPtrTy = PointerType::getUnqual(SrcETy);
8877 }
8878 }
8879
8880
Chris Lattnerf497b022008-01-13 23:50:23 +00008881 // If the memcpy/memmove provides better alignment info than we can
8882 // infer, use it.
8883 SrcAlign = std::max(SrcAlign, CopyAlign);
8884 DstAlign = std::max(DstAlign, CopyAlign);
8885
8886 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8887 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008888 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8889 InsertNewInstBefore(L, *MI);
8890 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8891
8892 // Set the size of the copy to 0, it will be deleted on the next iteration.
8893 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8894 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008895}
Chris Lattner3d69f462004-03-12 05:52:32 +00008896
Chris Lattner69ea9d22008-04-30 06:39:11 +00008897Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8898 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8899 if (MI->getAlignment()->getZExtValue() < Alignment) {
8900 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8901 return MI;
8902 }
8903
8904 // Extract the length and alignment and fill if they are constant.
8905 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8906 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8907 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8908 return 0;
8909 uint64_t Len = LenC->getZExtValue();
8910 Alignment = MI->getAlignment()->getZExtValue();
8911
8912 // If the length is zero, this is a no-op
8913 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8914
8915 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8916 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8917 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8918
8919 Value *Dest = MI->getDest();
8920 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8921
8922 // Alignment 0 is identity for alignment 1 for memset, but not store.
8923 if (Alignment == 0) Alignment = 1;
8924
8925 // Extract the fill value and store.
8926 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8927 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8928 Alignment), *MI);
8929
8930 // Set the size of the copy to 0, it will be deleted on the next iteration.
8931 MI->setLength(Constant::getNullValue(LenC->getType()));
8932 return MI;
8933 }
8934
8935 return 0;
8936}
8937
8938
Chris Lattner8b0ea312006-01-13 20:11:04 +00008939/// visitCallInst - CallInst simplification. This mostly only handles folding
8940/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8941/// the heavy lifting.
8942///
Chris Lattner9fe38862003-06-19 17:00:31 +00008943Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008944 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8945 if (!II) return visitCallSite(&CI);
8946
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008947 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8948 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008949 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008950 bool Changed = false;
8951
8952 // memmove/cpy/set of zero bytes is a noop.
8953 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8954 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8955
Chris Lattner35b9e482004-10-12 04:52:52 +00008956 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008957 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008958 // Replace the instruction with just byte operations. We would
8959 // transform other cases to loads/stores, but we don't know if
8960 // alignment is sufficient.
8961 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008962 }
8963
Chris Lattner35b9e482004-10-12 04:52:52 +00008964 // If we have a memmove and the source operation is a constant global,
8965 // then the source and dest pointers can't alias, so we can change this
8966 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008967 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008968 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8969 if (GVSrc->isConstant()) {
8970 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008971 Intrinsic::ID MemCpyID;
8972 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8973 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008974 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008975 MemCpyID = Intrinsic::memcpy_i64;
8976 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008977 Changed = true;
8978 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008979 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008980
Chris Lattner95a959d2006-03-06 20:18:44 +00008981 // If we can determine a pointer alignment that is bigger than currently
8982 // set, update the alignment.
8983 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008984 if (Instruction *I = SimplifyMemTransfer(MI))
8985 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008986 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8987 if (Instruction *I = SimplifyMemSet(MSI))
8988 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008989 }
8990
Chris Lattner8b0ea312006-01-13 20:11:04 +00008991 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008992 } else {
8993 switch (II->getIntrinsicID()) {
8994 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008995 case Intrinsic::ppc_altivec_lvx:
8996 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008997 case Intrinsic::x86_sse_loadu_ps:
8998 case Intrinsic::x86_sse2_loadu_pd:
8999 case Intrinsic::x86_sse2_loadu_dq:
9000 // Turn PPC lvx -> load if the pointer is known aligned.
9001 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009002 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009003 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9004 PointerType::getUnqual(II->getType()),
9005 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009006 return new LoadInst(Ptr);
9007 }
9008 break;
9009 case Intrinsic::ppc_altivec_stvx:
9010 case Intrinsic::ppc_altivec_stvxl:
9011 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009012 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009013 const Type *OpPtrTy =
9014 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009015 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009016 return new StoreInst(II->getOperand(1), Ptr);
9017 }
9018 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009019 case Intrinsic::x86_sse_storeu_ps:
9020 case Intrinsic::x86_sse2_storeu_pd:
9021 case Intrinsic::x86_sse2_storeu_dq:
9022 case Intrinsic::x86_sse2_storel_dq:
9023 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009024 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009025 const Type *OpPtrTy =
9026 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009027 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009028 return new StoreInst(II->getOperand(2), Ptr);
9029 }
9030 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009031
9032 case Intrinsic::x86_sse_cvttss2si: {
9033 // These intrinsics only demands the 0th element of its input vector. If
9034 // we can simplify the input based on that, do so now.
9035 uint64_t UndefElts;
9036 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9037 UndefElts)) {
9038 II->setOperand(1, V);
9039 return II;
9040 }
9041 break;
9042 }
9043
Chris Lattnere2ed0572006-04-06 19:19:17 +00009044 case Intrinsic::ppc_altivec_vperm:
9045 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009046 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009047 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9048
9049 // Check that all of the elements are integer constants or undefs.
9050 bool AllEltsOk = true;
9051 for (unsigned i = 0; i != 16; ++i) {
9052 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9053 !isa<UndefValue>(Mask->getOperand(i))) {
9054 AllEltsOk = false;
9055 break;
9056 }
9057 }
9058
9059 if (AllEltsOk) {
9060 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009061 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9062 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009063 Value *Result = UndefValue::get(Op0->getType());
9064
9065 // Only extract each element once.
9066 Value *ExtractedElts[32];
9067 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9068
9069 for (unsigned i = 0; i != 16; ++i) {
9070 if (isa<UndefValue>(Mask->getOperand(i)))
9071 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009072 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009073 Idx &= 31; // Match the hardware behavior.
9074
9075 if (ExtractedElts[Idx] == 0) {
9076 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009077 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009078 InsertNewInstBefore(Elt, CI);
9079 ExtractedElts[Idx] = Elt;
9080 }
9081
9082 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009083 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9084 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009085 InsertNewInstBefore(cast<Instruction>(Result), CI);
9086 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009087 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009088 }
9089 }
9090 break;
9091
Chris Lattnera728ddc2006-01-13 21:28:09 +00009092 case Intrinsic::stackrestore: {
9093 // If the save is right next to the restore, remove the restore. This can
9094 // happen when variable allocas are DCE'd.
9095 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9096 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9097 BasicBlock::iterator BI = SS;
9098 if (&*++BI == II)
9099 return EraseInstFromFunction(CI);
9100 }
9101 }
9102
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009103 // Scan down this block to see if there is another stack restore in the
9104 // same block without an intervening call/alloca.
9105 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009106 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009107 bool CannotRemove = false;
9108 for (++BI; &*BI != TI; ++BI) {
9109 if (isa<AllocaInst>(BI)) {
9110 CannotRemove = true;
9111 break;
9112 }
9113 if (isa<CallInst>(BI)) {
9114 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009115 CannotRemove = true;
9116 break;
9117 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009118 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009119 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009120 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009121 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009122
9123 // If the stack restore is in a return/unwind block and if there are no
9124 // allocas or calls between the restore and the return, nuke the restore.
9125 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9126 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009127 break;
9128 }
9129 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009130 }
9131
Chris Lattner8b0ea312006-01-13 20:11:04 +00009132 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009133}
9134
9135// InvokeInst simplification
9136//
9137Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009138 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009139}
9140
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009141/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9142/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009143static bool isSafeToEliminateVarargsCast(const CallSite CS,
9144 const CastInst * const CI,
9145 const TargetData * const TD,
9146 const int ix) {
9147 if (!CI->isLosslessCast())
9148 return false;
9149
9150 // The size of ByVal arguments is derived from the type, so we
9151 // can't change to a type with a different size. If the size were
9152 // passed explicitly we could avoid this check.
9153 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9154 return true;
9155
9156 const Type* SrcTy =
9157 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9158 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9159 if (!SrcTy->isSized() || !DstTy->isSized())
9160 return false;
9161 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9162 return false;
9163 return true;
9164}
9165
Chris Lattnera44d8a22003-10-07 22:32:43 +00009166// visitCallSite - Improvements for call and invoke instructions.
9167//
9168Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009169 bool Changed = false;
9170
9171 // If the callee is a constexpr cast of a function, attempt to move the cast
9172 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009173 if (transformConstExprCastCall(CS)) return 0;
9174
Chris Lattner6c266db2003-10-07 22:54:13 +00009175 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009176
Chris Lattner08b22ec2005-05-13 07:09:09 +00009177 if (Function *CalleeF = dyn_cast<Function>(Callee))
9178 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9179 Instruction *OldCall = CS.getInstruction();
9180 // If the call and callee calling conventions don't match, this call must
9181 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009182 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009183 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9184 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009185 if (!OldCall->use_empty())
9186 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9187 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9188 return EraseInstFromFunction(*OldCall);
9189 return 0;
9190 }
9191
Chris Lattner17be6352004-10-18 02:59:09 +00009192 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9193 // This instruction is not reachable, just remove it. We insert a store to
9194 // undef so that we know that this code is not reachable, despite the fact
9195 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009196 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009197 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009198 CS.getInstruction());
9199
9200 if (!CS.getInstruction()->use_empty())
9201 CS.getInstruction()->
9202 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9203
9204 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9205 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009206 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9207 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009208 }
Chris Lattner17be6352004-10-18 02:59:09 +00009209 return EraseInstFromFunction(*CS.getInstruction());
9210 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009211
Duncan Sandscdb6d922007-09-17 10:26:40 +00009212 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9213 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9214 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9215 return transformCallThroughTrampoline(CS);
9216
Chris Lattner6c266db2003-10-07 22:54:13 +00009217 const PointerType *PTy = cast<PointerType>(Callee->getType());
9218 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9219 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009220 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009221 // See if we can optimize any arguments passed through the varargs area of
9222 // the call.
9223 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009224 E = CS.arg_end(); I != E; ++I, ++ix) {
9225 CastInst *CI = dyn_cast<CastInst>(*I);
9226 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9227 *I = CI->getOperand(0);
9228 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009229 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009230 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009231 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009232
Duncan Sandsf0c33542007-12-19 21:13:37 +00009233 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009234 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009235 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009236 Changed = true;
9237 }
9238
Chris Lattner6c266db2003-10-07 22:54:13 +00009239 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009240}
9241
Chris Lattner9fe38862003-06-19 17:00:31 +00009242// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9243// attempt to move the cast to the arguments of the call/invoke.
9244//
9245bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9246 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9247 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009248 if (CE->getOpcode() != Instruction::BitCast ||
9249 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009250 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009251 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009252 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009253 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009254
9255 // Okay, this is a cast from a function to a different type. Unless doing so
9256 // would cause a type conversion of one of our arguments, change this call to
9257 // be a direct call with arguments casted to the appropriate types.
9258 //
9259 const FunctionType *FT = Callee->getFunctionType();
9260 const Type *OldRetTy = Caller->getType();
9261
Devang Patel75e6f022008-03-11 18:04:06 +00009262 if (isa<StructType>(FT->getReturnType()))
9263 return false; // TODO: Handle multiple return values.
9264
Chris Lattnerf78616b2004-01-14 06:06:08 +00009265 // Check to see if we are changing the return type...
9266 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009267 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009268 // Conversion is ok if changing from pointer to int of same size.
9269 !(isa<PointerType>(FT->getReturnType()) &&
9270 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009271 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009272
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009273 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009274 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009275 FT->getReturnType() != Type::VoidTy &&
9276 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009277 return false; // Cannot transform this return value.
9278
Chris Lattner58d74912008-03-12 17:45:29 +00009279 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9280 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009281 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9282 return false; // Attribute not compatible with transformed value.
9283 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009284
Chris Lattnerf78616b2004-01-14 06:06:08 +00009285 // If the callsite is an invoke instruction, and the return value is used by
9286 // a PHI node in a successor, we cannot change the return type of the call
9287 // because there is no place to put the cast instruction (without breaking
9288 // the critical edge). Bail out in this case.
9289 if (!Caller->use_empty())
9290 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9291 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9292 UI != E; ++UI)
9293 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9294 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009295 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009296 return false;
9297 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009298
9299 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9300 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009301
Chris Lattner9fe38862003-06-19 17:00:31 +00009302 CallSite::arg_iterator AI = CS.arg_begin();
9303 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9304 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009305 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009306
9307 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009308 return false; // Cannot transform this parameter value.
9309
Chris Lattner58d74912008-03-12 17:45:29 +00009310 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9311 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009312
Reid Spencer3da59db2006-11-27 01:05:10 +00009313 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009314 // Some conversions are safe even if we do not have a body.
9315 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009316 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009317 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009318 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009319 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9320 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009321 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009322 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009323 }
9324
9325 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009326 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009327 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009328
Chris Lattner58d74912008-03-12 17:45:29 +00009329 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9330 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009331 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009332 // won't be dropping them. Check that these extra arguments have attributes
9333 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009334 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9335 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009336 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009337 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009338 if (PAttrs & ParamAttr::VarArgsIncompatible)
9339 return false;
9340 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009341
Chris Lattner9fe38862003-06-19 17:00:31 +00009342 // Okay, we decided that this is a safe thing to do: go ahead and start
9343 // inserting cast instructions as necessary...
9344 std::vector<Value*> Args;
9345 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009346 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009347 attrVec.reserve(NumCommonArgs);
9348
9349 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009350 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009351
9352 // If the return value is not being used, the type may not be compatible
9353 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009354 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009355
9356 // Add the new return attributes.
9357 if (RAttrs)
9358 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009359
9360 AI = CS.arg_begin();
9361 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9362 const Type *ParamTy = FT->getParamType(i);
9363 if ((*AI)->getType() == ParamTy) {
9364 Args.push_back(*AI);
9365 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009366 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009367 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009368 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009369 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009370 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009371
9372 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009373 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009374 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009375 }
9376
9377 // If the function takes more arguments than the call was taking, add them
9378 // now...
9379 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9380 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9381
9382 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009383 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009384 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009385 cerr << "WARNING: While resolving call to function '"
9386 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009387 } else {
9388 // Add all of the arguments in their promoted form to the arg list...
9389 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9390 const Type *PTy = getPromotedType((*AI)->getType());
9391 if (PTy != (*AI)->getType()) {
9392 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009393 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9394 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009395 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009396 InsertNewInstBefore(Cast, *Caller);
9397 Args.push_back(Cast);
9398 } else {
9399 Args.push_back(*AI);
9400 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009401
Duncan Sandse1e520f2008-01-13 08:02:44 +00009402 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009403 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009404 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9405 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009406 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009407 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009408
9409 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009410 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009411
Chris Lattner58d74912008-03-12 17:45:29 +00009412 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009413
Chris Lattner9fe38862003-06-19 17:00:31 +00009414 Instruction *NC;
9415 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009416 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009417 Args.begin(), Args.end(),
9418 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009419 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009420 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009421 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009422 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9423 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009424 CallInst *CI = cast<CallInst>(Caller);
9425 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009426 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009427 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009428 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009429 }
9430
Chris Lattner6934a042007-02-11 01:23:03 +00009431 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009432 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009433 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009434 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009435 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009436 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009437 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009438
9439 // If this is an invoke instruction, we should insert it after the first
9440 // non-phi, instruction in the normal successor block.
9441 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9442 BasicBlock::iterator I = II->getNormalDest()->begin();
9443 while (isa<PHINode>(I)) ++I;
9444 InsertNewInstBefore(NC, *I);
9445 } else {
9446 // Otherwise, it's a call, just insert cast right after the call instr
9447 InsertNewInstBefore(NC, *Caller);
9448 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009449 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009450 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009451 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009452 }
9453 }
9454
9455 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9456 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009457 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009458 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009459 return true;
9460}
9461
Duncan Sandscdb6d922007-09-17 10:26:40 +00009462// transformCallThroughTrampoline - Turn a call to a function created by the
9463// init_trampoline intrinsic into a direct call to the underlying function.
9464//
9465Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9466 Value *Callee = CS.getCalledValue();
9467 const PointerType *PTy = cast<PointerType>(Callee->getType());
9468 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009469 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009470
9471 // If the call already has the 'nest' attribute somewhere then give up -
9472 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009473 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009474 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009475
9476 IntrinsicInst *Tramp =
9477 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9478
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009479 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009480 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9481 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9482
Chris Lattner58d74912008-03-12 17:45:29 +00009483 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9484 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009485 unsigned NestIdx = 1;
9486 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009487 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009488
9489 // Look for a parameter marked with the 'nest' attribute.
9490 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9491 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009492 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009493 // Record the parameter type and any other attributes.
9494 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009495 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009496 break;
9497 }
9498
9499 if (NestTy) {
9500 Instruction *Caller = CS.getInstruction();
9501 std::vector<Value*> NewArgs;
9502 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9503
Chris Lattner58d74912008-03-12 17:45:29 +00009504 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9505 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009506
Duncan Sandscdb6d922007-09-17 10:26:40 +00009507 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009508 // mean appending it. Likewise for attributes.
9509
9510 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009511 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9512 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009513
Duncan Sandscdb6d922007-09-17 10:26:40 +00009514 {
9515 unsigned Idx = 1;
9516 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9517 do {
9518 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009519 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009520 Value *NestVal = Tramp->getOperand(3);
9521 if (NestVal->getType() != NestTy)
9522 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9523 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009524 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009525 }
9526
9527 if (I == E)
9528 break;
9529
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009530 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009531 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009532 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009533 NewAttrs.push_back
9534 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009535
9536 ++Idx, ++I;
9537 } while (1);
9538 }
9539
9540 // The trampoline may have been bitcast to a bogus type (FTy).
9541 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009542 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009543
Duncan Sandscdb6d922007-09-17 10:26:40 +00009544 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009545 NewTypes.reserve(FTy->getNumParams()+1);
9546
Duncan Sandscdb6d922007-09-17 10:26:40 +00009547 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009548 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009549 {
9550 unsigned Idx = 1;
9551 FunctionType::param_iterator I = FTy->param_begin(),
9552 E = FTy->param_end();
9553
9554 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009555 if (Idx == NestIdx)
9556 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009557 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009558
9559 if (I == E)
9560 break;
9561
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009562 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009563 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009564
9565 ++Idx, ++I;
9566 } while (1);
9567 }
9568
9569 // Replace the trampoline call with a direct call. Let the generic
9570 // code sort out any function type mismatches.
9571 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009572 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009573 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9574 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009575 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009576
9577 Instruction *NewCaller;
9578 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009579 NewCaller = InvokeInst::Create(NewCallee,
9580 II->getNormalDest(), II->getUnwindDest(),
9581 NewArgs.begin(), NewArgs.end(),
9582 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009583 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009584 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009585 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009586 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9587 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009588 if (cast<CallInst>(Caller)->isTailCall())
9589 cast<CallInst>(NewCaller)->setTailCall();
9590 cast<CallInst>(NewCaller)->
9591 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009592 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009593 }
9594 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9595 Caller->replaceAllUsesWith(NewCaller);
9596 Caller->eraseFromParent();
9597 RemoveFromWorkList(Caller);
9598 return 0;
9599 }
9600 }
9601
9602 // Replace the trampoline call with a direct call. Since there is no 'nest'
9603 // parameter, there is no need to adjust the argument list. Let the generic
9604 // code sort out any function type mismatches.
9605 Constant *NewCallee =
9606 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9607 CS.setCalledFunction(NewCallee);
9608 return CS.getInstruction();
9609}
9610
Chris Lattner7da52b22006-11-01 04:51:18 +00009611/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9612/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9613/// and a single binop.
9614Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9615 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009616 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9617 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009618 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009619 Value *LHSVal = FirstInst->getOperand(0);
9620 Value *RHSVal = FirstInst->getOperand(1);
9621
9622 const Type *LHSType = LHSVal->getType();
9623 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009624
9625 // Scan to see if all operands are the same opcode, all have one use, and all
9626 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009627 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009628 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009629 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009630 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009631 // types or GEP's with different index types.
9632 I->getOperand(0)->getType() != LHSType ||
9633 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009634 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009635
9636 // If they are CmpInst instructions, check their predicates
9637 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9638 if (cast<CmpInst>(I)->getPredicate() !=
9639 cast<CmpInst>(FirstInst)->getPredicate())
9640 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009641
9642 // Keep track of which operand needs a phi node.
9643 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9644 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009645 }
9646
Chris Lattner53738a42006-11-08 19:42:28 +00009647 // Otherwise, this is safe to transform, determine if it is profitable.
9648
9649 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9650 // Indexes are often folded into load/store instructions, so we don't want to
9651 // hide them behind a phi.
9652 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9653 return 0;
9654
Chris Lattner7da52b22006-11-01 04:51:18 +00009655 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009656 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009657 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009658 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009659 NewLHS = PHINode::Create(LHSType,
9660 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009661 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9662 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009663 InsertNewInstBefore(NewLHS, PN);
9664 LHSVal = NewLHS;
9665 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009666
9667 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009668 NewRHS = PHINode::Create(RHSType,
9669 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009670 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9671 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009672 InsertNewInstBefore(NewRHS, PN);
9673 RHSVal = NewRHS;
9674 }
9675
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009676 // Add all operands to the new PHIs.
9677 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9678 if (NewLHS) {
9679 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9680 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9681 }
9682 if (NewRHS) {
9683 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9684 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9685 }
9686 }
9687
Chris Lattner7da52b22006-11-01 04:51:18 +00009688 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009689 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009690 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009691 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009692 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009693 else {
9694 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009695 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009696 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009697}
9698
Chris Lattner76c73142006-11-01 07:13:54 +00009699/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9700/// of the block that defines it. This means that it must be obvious the value
9701/// of the load is not changed from the point of the load to the end of the
9702/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009703///
9704/// Finally, it is safe, but not profitable, to sink a load targetting a
9705/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9706/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009707static bool isSafeToSinkLoad(LoadInst *L) {
9708 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9709
9710 for (++BBI; BBI != E; ++BBI)
9711 if (BBI->mayWriteToMemory())
9712 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009713
9714 // Check for non-address taken alloca. If not address-taken already, it isn't
9715 // profitable to do this xform.
9716 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9717 bool isAddressTaken = false;
9718 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9719 UI != E; ++UI) {
9720 if (isa<LoadInst>(UI)) continue;
9721 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9722 // If storing TO the alloca, then the address isn't taken.
9723 if (SI->getOperand(1) == AI) continue;
9724 }
9725 isAddressTaken = true;
9726 break;
9727 }
9728
9729 if (!isAddressTaken)
9730 return false;
9731 }
9732
Chris Lattner76c73142006-11-01 07:13:54 +00009733 return true;
9734}
9735
Chris Lattner9fe38862003-06-19 17:00:31 +00009736
Chris Lattnerbac32862004-11-14 19:13:23 +00009737// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9738// operator and they all are only used by the PHI, PHI together their
9739// inputs, and do the operation once, to the result of the PHI.
9740Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9741 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9742
9743 // Scan the instruction, looking for input operations that can be folded away.
9744 // If all input operands to the phi are the same instruction (e.g. a cast from
9745 // the same type or "+42") we can pull the operation through the PHI, reducing
9746 // code size and simplifying code.
9747 Constant *ConstantOp = 0;
9748 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009749 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009750 if (isa<CastInst>(FirstInst)) {
9751 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009752 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009753 // Can fold binop, compare or shift here if the RHS is a constant,
9754 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009755 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009756 if (ConstantOp == 0)
9757 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009758 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9759 isVolatile = LI->isVolatile();
9760 // We can't sink the load if the loaded value could be modified between the
9761 // load and the PHI.
9762 if (LI->getParent() != PN.getIncomingBlock(0) ||
9763 !isSafeToSinkLoad(LI))
9764 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009765 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009766 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009767 return FoldPHIArgBinOpIntoPHI(PN);
9768 // Can't handle general GEPs yet.
9769 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009770 } else {
9771 return 0; // Cannot fold this operation.
9772 }
9773
9774 // Check to see if all arguments are the same operation.
9775 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9776 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9777 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009778 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009779 return 0;
9780 if (CastSrcTy) {
9781 if (I->getOperand(0)->getType() != CastSrcTy)
9782 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009783 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009784 // We can't sink the load if the loaded value could be modified between
9785 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009786 if (LI->isVolatile() != isVolatile ||
9787 LI->getParent() != PN.getIncomingBlock(i) ||
9788 !isSafeToSinkLoad(LI))
9789 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009790
9791 // If the PHI is volatile and its block has multiple successors, sinking
9792 // it would remove a load of the volatile value from the path through the
9793 // other successor.
9794 if (isVolatile &&
9795 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9796 return 0;
9797
9798
Chris Lattnerbac32862004-11-14 19:13:23 +00009799 } else if (I->getOperand(1) != ConstantOp) {
9800 return 0;
9801 }
9802 }
9803
9804 // Okay, they are all the same operation. Create a new PHI node of the
9805 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009806 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9807 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009808 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009809
9810 Value *InVal = FirstInst->getOperand(0);
9811 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009812
9813 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009814 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9815 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9816 if (NewInVal != InVal)
9817 InVal = 0;
9818 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9819 }
9820
9821 Value *PhiVal;
9822 if (InVal) {
9823 // The new PHI unions all of the same values together. This is really
9824 // common, so we handle it intelligently here for compile-time speed.
9825 PhiVal = InVal;
9826 delete NewPN;
9827 } else {
9828 InsertNewInstBefore(NewPN, PN);
9829 PhiVal = NewPN;
9830 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009831
Chris Lattnerbac32862004-11-14 19:13:23 +00009832 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009833 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009834 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009835 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009836 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009837 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009838 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009839 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009840 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9841
9842 // If this was a volatile load that we are merging, make sure to loop through
9843 // and mark all the input loads as non-volatile. If we don't do this, we will
9844 // insert a new volatile load and the old ones will not be deletable.
9845 if (isVolatile)
9846 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9847 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9848
9849 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009850}
Chris Lattnera1be5662002-05-02 17:06:02 +00009851
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009852/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9853/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009854static bool DeadPHICycle(PHINode *PN,
9855 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009856 if (PN->use_empty()) return true;
9857 if (!PN->hasOneUse()) return false;
9858
9859 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009860 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009861 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009862
9863 // Don't scan crazily complex things.
9864 if (PotentiallyDeadPHIs.size() == 16)
9865 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009866
9867 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9868 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009869
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009870 return false;
9871}
9872
Chris Lattnercf5008a2007-11-06 21:52:06 +00009873/// PHIsEqualValue - Return true if this phi node is always equal to
9874/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9875/// z = some value; x = phi (y, z); y = phi (x, z)
9876static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9877 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9878 // See if we already saw this PHI node.
9879 if (!ValueEqualPHIs.insert(PN))
9880 return true;
9881
9882 // Don't scan crazily complex things.
9883 if (ValueEqualPHIs.size() == 16)
9884 return false;
9885
9886 // Scan the operands to see if they are either phi nodes or are equal to
9887 // the value.
9888 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9889 Value *Op = PN->getIncomingValue(i);
9890 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9891 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9892 return false;
9893 } else if (Op != NonPhiInVal)
9894 return false;
9895 }
9896
9897 return true;
9898}
9899
9900
Chris Lattner473945d2002-05-06 18:06:38 +00009901// PHINode simplification
9902//
Chris Lattner7e708292002-06-25 16:13:24 +00009903Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009904 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009905 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009906
Owen Anderson7e057142006-07-10 22:03:18 +00009907 if (Value *V = PN.hasConstantValue())
9908 return ReplaceInstUsesWith(PN, V);
9909
Owen Anderson7e057142006-07-10 22:03:18 +00009910 // If all PHI operands are the same operation, pull them through the PHI,
9911 // reducing code size.
9912 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9913 PN.getIncomingValue(0)->hasOneUse())
9914 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9915 return Result;
9916
9917 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9918 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9919 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009920 if (PN.hasOneUse()) {
9921 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9922 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009923 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009924 PotentiallyDeadPHIs.insert(&PN);
9925 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9926 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9927 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009928
9929 // If this phi has a single use, and if that use just computes a value for
9930 // the next iteration of a loop, delete the phi. This occurs with unused
9931 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9932 // common case here is good because the only other things that catch this
9933 // are induction variable analysis (sometimes) and ADCE, which is only run
9934 // late.
9935 if (PHIUser->hasOneUse() &&
9936 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9937 PHIUser->use_back() == &PN) {
9938 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9939 }
9940 }
Owen Anderson7e057142006-07-10 22:03:18 +00009941
Chris Lattnercf5008a2007-11-06 21:52:06 +00009942 // We sometimes end up with phi cycles that non-obviously end up being the
9943 // same value, for example:
9944 // z = some value; x = phi (y, z); y = phi (x, z)
9945 // where the phi nodes don't necessarily need to be in the same block. Do a
9946 // quick check to see if the PHI node only contains a single non-phi value, if
9947 // so, scan to see if the phi cycle is actually equal to that value.
9948 {
9949 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9950 // Scan for the first non-phi operand.
9951 while (InValNo != NumOperandVals &&
9952 isa<PHINode>(PN.getIncomingValue(InValNo)))
9953 ++InValNo;
9954
9955 if (InValNo != NumOperandVals) {
9956 Value *NonPhiInVal = PN.getOperand(InValNo);
9957
9958 // Scan the rest of the operands to see if there are any conflicts, if so
9959 // there is no need to recursively scan other phis.
9960 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9961 Value *OpVal = PN.getIncomingValue(InValNo);
9962 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9963 break;
9964 }
9965
9966 // If we scanned over all operands, then we have one unique value plus
9967 // phi values. Scan PHI nodes to see if they all merge in each other or
9968 // the value.
9969 if (InValNo == NumOperandVals) {
9970 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9971 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9972 return ReplaceInstUsesWith(PN, NonPhiInVal);
9973 }
9974 }
9975 }
Chris Lattner60921c92003-12-19 05:58:40 +00009976 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009977}
9978
Reid Spencer17212df2006-12-12 09:18:51 +00009979static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9980 Instruction *InsertPoint,
9981 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009982 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9983 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009984 // We must cast correctly to the pointer type. Ensure that we
9985 // sign extend the integer value if it is smaller as this is
9986 // used for address computation.
9987 Instruction::CastOps opcode =
9988 (VTySize < PtrSize ? Instruction::SExt :
9989 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9990 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009991}
9992
Chris Lattnera1be5662002-05-02 17:06:02 +00009993
Chris Lattner7e708292002-06-25 16:13:24 +00009994Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009995 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009996 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009997 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009998 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009999 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010000
Chris Lattnere87597f2004-10-16 18:11:37 +000010001 if (isa<UndefValue>(GEP.getOperand(0)))
10002 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10003
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010004 bool HasZeroPointerIndex = false;
10005 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10006 HasZeroPointerIndex = C->isNullValue();
10007
10008 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010009 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010010
Chris Lattner28977af2004-04-05 01:30:19 +000010011 // Eliminate unneeded casts for indices.
10012 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010013
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010014 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010015 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010016 if (isa<SequentialType>(*GTI)) {
10017 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010018 if (CI->getOpcode() == Instruction::ZExt ||
10019 CI->getOpcode() == Instruction::SExt) {
10020 const Type *SrcTy = CI->getOperand(0)->getType();
10021 // We can eliminate a cast from i32 to i64 iff the target
10022 // is a 32-bit pointer target.
10023 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10024 MadeChange = true;
10025 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010026 }
10027 }
10028 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010029 // If we are using a wider index than needed for this platform, shrink it
10030 // to what we need. If the incoming value needs a cast instruction,
10031 // insert it. This explicit cast can make subsequent optimizations more
10032 // obvious.
10033 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010034 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010035 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010036 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010037 MadeChange = true;
10038 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010039 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10040 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010041 GEP.setOperand(i, Op);
10042 MadeChange = true;
10043 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010044 }
Chris Lattner28977af2004-04-05 01:30:19 +000010045 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010046 }
Chris Lattner28977af2004-04-05 01:30:19 +000010047 if (MadeChange) return &GEP;
10048
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010049 // If this GEP instruction doesn't move the pointer, and if the input operand
10050 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10051 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010052 if (GEP.hasAllZeroIndices()) {
10053 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10054 // If the bitcast is of an allocation, and the allocation will be
10055 // converted to match the type of the cast, don't touch this.
10056 if (isa<AllocationInst>(BCI->getOperand(0))) {
10057 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010058 if (Instruction *I = visitBitCast(*BCI)) {
10059 if (I != BCI) {
10060 I->takeName(BCI);
10061 BCI->getParent()->getInstList().insert(BCI, I);
10062 ReplaceInstUsesWith(*BCI, I);
10063 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010064 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010065 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010066 }
10067 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10068 }
10069 }
10070
Chris Lattner90ac28c2002-08-02 19:29:35 +000010071 // Combine Indices - If the source pointer to this getelementptr instruction
10072 // is a getelementptr instruction, combine the indices of the two
10073 // getelementptr instructions into a single instruction.
10074 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010075 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010076 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010077 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010078
10079 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010080 // Note that if our source is a gep chain itself that we wait for that
10081 // chain to be resolved before we perform this transformation. This
10082 // avoids us creating a TON of code in some cases.
10083 //
10084 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10085 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10086 return 0; // Wait until our source is folded to completion.
10087
Chris Lattner72588fc2007-02-15 22:48:32 +000010088 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010089
10090 // Find out whether the last index in the source GEP is a sequential idx.
10091 bool EndsWithSequential = false;
10092 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10093 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010094 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010095
Chris Lattner90ac28c2002-08-02 19:29:35 +000010096 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010097 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010098 // Replace: gep (gep %P, long B), long A, ...
10099 // With: T = long A+B; gep %P, T, ...
10100 //
Chris Lattner620ce142004-05-07 22:09:22 +000010101 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010102 if (SO1 == Constant::getNullValue(SO1->getType())) {
10103 Sum = GO1;
10104 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10105 Sum = SO1;
10106 } else {
10107 // If they aren't the same type, convert both to an integer of the
10108 // target's pointer size.
10109 if (SO1->getType() != GO1->getType()) {
10110 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010111 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010112 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010113 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010114 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010115 unsigned PS = TD->getPointerSizeInBits();
10116 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010117 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010118 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010119
Duncan Sands514ab342007-11-01 20:53:16 +000010120 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010121 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010122 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010123 } else {
10124 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010125 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10126 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010127 }
10128 }
10129 }
Chris Lattner620ce142004-05-07 22:09:22 +000010130 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10131 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10132 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010133 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010134 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010135 }
Chris Lattner28977af2004-04-05 01:30:19 +000010136 }
Chris Lattner620ce142004-05-07 22:09:22 +000010137
10138 // Recycle the GEP we already have if possible.
10139 if (SrcGEPOperands.size() == 2) {
10140 GEP.setOperand(0, SrcGEPOperands[0]);
10141 GEP.setOperand(1, Sum);
10142 return &GEP;
10143 } else {
10144 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10145 SrcGEPOperands.end()-1);
10146 Indices.push_back(Sum);
10147 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10148 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010149 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010150 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010151 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010152 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010153 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10154 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010155 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10156 }
10157
10158 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010159 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10160 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010161
Chris Lattner620ce142004-05-07 22:09:22 +000010162 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010163 // GEP of global variable. If all of the indices for this GEP are
10164 // constants, we can promote this to a constexpr instead of an instruction.
10165
10166 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010167 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010168 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10169 for (; I != E && isa<Constant>(*I); ++I)
10170 Indices.push_back(cast<Constant>(*I));
10171
10172 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010173 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10174 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010175
10176 // Replace all uses of the GEP with the new constexpr...
10177 return ReplaceInstUsesWith(GEP, CE);
10178 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010179 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010180 if (!isa<PointerType>(X->getType())) {
10181 // Not interesting. Source pointer must be a cast from pointer.
10182 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010183 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10184 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010185 //
10186 // This occurs when the program declares an array extern like "int X[];"
10187 //
10188 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10189 const PointerType *XTy = cast<PointerType>(X->getType());
10190 if (const ArrayType *XATy =
10191 dyn_cast<ArrayType>(XTy->getElementType()))
10192 if (const ArrayType *CATy =
10193 dyn_cast<ArrayType>(CPTy->getElementType()))
10194 if (CATy->getElementType() == XATy->getElementType()) {
10195 // At this point, we know that the cast source type is a pointer
10196 // to an array of the same type as the destination pointer
10197 // array. Because the array type is never stepped over (there
10198 // is a leading zero) we can fold the cast into this GEP.
10199 GEP.setOperand(0, X);
10200 return &GEP;
10201 }
10202 } else if (GEP.getNumOperands() == 2) {
10203 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010204 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10205 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010206 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10207 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10208 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010209 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10210 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010211 Value *Idx[2];
10212 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10213 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010214 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010215 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010216 // V and GEP are both pointer types --> BitCast
10217 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010218 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010219
10220 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010221 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010222 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010223 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010224
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010225 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010226 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010227 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010228
10229 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10230 // allow either a mul, shift, or constant here.
10231 Value *NewIdx = 0;
10232 ConstantInt *Scale = 0;
10233 if (ArrayEltSize == 1) {
10234 NewIdx = GEP.getOperand(1);
10235 Scale = ConstantInt::get(NewIdx->getType(), 1);
10236 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010237 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010238 Scale = CI;
10239 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10240 if (Inst->getOpcode() == Instruction::Shl &&
10241 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010242 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10243 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10244 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010245 NewIdx = Inst->getOperand(0);
10246 } else if (Inst->getOpcode() == Instruction::Mul &&
10247 isa<ConstantInt>(Inst->getOperand(1))) {
10248 Scale = cast<ConstantInt>(Inst->getOperand(1));
10249 NewIdx = Inst->getOperand(0);
10250 }
10251 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010252
Chris Lattner7835cdd2005-09-13 18:36:04 +000010253 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010254 // out, perform the transformation. Note, we don't know whether Scale is
10255 // signed or not. We'll use unsigned version of division/modulo
10256 // operation after making sure Scale doesn't have the sign bit set.
10257 if (Scale && Scale->getSExtValue() >= 0LL &&
10258 Scale->getZExtValue() % ArrayEltSize == 0) {
10259 Scale = ConstantInt::get(Scale->getType(),
10260 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010261 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010262 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010263 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010264 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010265 NewIdx = InsertNewInstBefore(Sc, GEP);
10266 }
10267
10268 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010269 Value *Idx[2];
10270 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10271 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010272 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010273 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010274 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10275 // The NewGEP must be pointer typed, so must the old one -> BitCast
10276 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010277 }
10278 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010279 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010280 }
10281
Chris Lattner8a2a3112001-12-14 16:52:21 +000010282 return 0;
10283}
10284
Chris Lattner0864acf2002-11-04 16:18:53 +000010285Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10286 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010287 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010288 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10289 const Type *NewTy =
10290 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010291 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010292
10293 // Create and insert the replacement instruction...
10294 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010295 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010296 else {
10297 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010298 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010299 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010300
10301 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010302
Chris Lattner0864acf2002-11-04 16:18:53 +000010303 // Scan to the end of the allocation instructions, to skip over a block of
10304 // allocas if possible...
10305 //
10306 BasicBlock::iterator It = New;
10307 while (isa<AllocationInst>(*It)) ++It;
10308
10309 // Now that I is pointing to the first non-allocation-inst in the block,
10310 // insert our getelementptr instruction...
10311 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010312 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010313 Value *Idx[2];
10314 Idx[0] = NullIdx;
10315 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010316 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10317 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010318
10319 // Now make everything use the getelementptr instead of the original
10320 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010321 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010322 } else if (isa<UndefValue>(AI.getArraySize())) {
10323 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010324 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010325 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010326
10327 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10328 // Note that we only do this for alloca's, because malloc should allocate and
10329 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010330 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010331 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010332 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10333
Chris Lattner0864acf2002-11-04 16:18:53 +000010334 return 0;
10335}
10336
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010337Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10338 Value *Op = FI.getOperand(0);
10339
Chris Lattner17be6352004-10-18 02:59:09 +000010340 // free undef -> unreachable.
10341 if (isa<UndefValue>(Op)) {
10342 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010343 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010344 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010345 return EraseInstFromFunction(FI);
10346 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010347
Chris Lattner6160e852004-02-28 04:57:37 +000010348 // If we have 'free null' delete the instruction. This can happen in stl code
10349 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010350 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010351 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010352
10353 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10354 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10355 FI.setOperand(0, CI->getOperand(0));
10356 return &FI;
10357 }
10358
10359 // Change free (gep X, 0,0,0,0) into free(X)
10360 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10361 if (GEPI->hasAllZeroIndices()) {
10362 AddToWorkList(GEPI);
10363 FI.setOperand(0, GEPI->getOperand(0));
10364 return &FI;
10365 }
10366 }
10367
10368 // Change free(malloc) into nothing, if the malloc has a single use.
10369 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10370 if (MI->hasOneUse()) {
10371 EraseInstFromFunction(FI);
10372 return EraseInstFromFunction(*MI);
10373 }
Chris Lattner6160e852004-02-28 04:57:37 +000010374
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010375 return 0;
10376}
10377
10378
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010379/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010380static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010381 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010382 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010383 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010384
Devang Patel99db6ad2007-10-18 19:52:32 +000010385 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10386 // Instead of loading constant c string, use corresponding integer value
10387 // directly if string length is small enough.
10388 const std::string &Str = CE->getOperand(0)->getStringValue();
10389 if (!Str.empty()) {
10390 unsigned len = Str.length();
10391 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10392 unsigned numBits = Ty->getPrimitiveSizeInBits();
10393 // Replace LI with immediate integer store.
10394 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010395 APInt StrVal(numBits, 0);
10396 APInt SingleChar(numBits, 0);
10397 if (TD->isLittleEndian()) {
10398 for (signed i = len-1; i >= 0; i--) {
10399 SingleChar = (uint64_t) Str[i];
10400 StrVal = (StrVal << 8) | SingleChar;
10401 }
10402 } else {
10403 for (unsigned i = 0; i < len; i++) {
10404 SingleChar = (uint64_t) Str[i];
10405 StrVal = (StrVal << 8) | SingleChar;
10406 }
10407 // Append NULL at the end.
10408 SingleChar = 0;
10409 StrVal = (StrVal << 8) | SingleChar;
10410 }
10411 Value *NL = ConstantInt::get(StrVal);
10412 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010413 }
10414 }
10415 }
10416
Chris Lattnerb89e0712004-07-13 01:49:43 +000010417 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010418 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010419 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010420
Reid Spencer42230162007-01-22 05:51:25 +000010421 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010422 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010423 // If the source is an array, the code below will not succeed. Check to
10424 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10425 // constants.
10426 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10427 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10428 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010429 Value *Idxs[2];
10430 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10431 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010432 SrcTy = cast<PointerType>(CastOp->getType());
10433 SrcPTy = SrcTy->getElementType();
10434 }
10435
Reid Spencer42230162007-01-22 05:51:25 +000010436 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010437 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010438 // Do not allow turning this into a load of an integer, which is then
10439 // casted to a pointer, this pessimizes pointer analysis a lot.
10440 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010441 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10442 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010443
Chris Lattnerf9527852005-01-31 04:50:46 +000010444 // Okay, we are casting from one integer or pointer type to another of
10445 // the same size. Instead of casting the pointer before the load, cast
10446 // the result of the loaded value.
10447 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10448 CI->getName(),
10449 LI.isVolatile()),LI);
10450 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010451 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010452 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010453 }
10454 }
10455 return 0;
10456}
10457
Chris Lattnerc10aced2004-09-19 18:43:46 +000010458/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010459/// from this value cannot trap. If it is not obviously safe to load from the
10460/// specified pointer, we do a quick local scan of the basic block containing
10461/// ScanFrom, to determine if the address is already accessed.
10462static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010463 // If it is an alloca it is always safe to load from.
10464 if (isa<AllocaInst>(V)) return true;
10465
Duncan Sands46318cd2007-09-19 10:25:38 +000010466 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010467 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010468 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010469 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010470
10471 // Otherwise, be a little bit agressive by scanning the local block where we
10472 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010473 // from/to. If so, the previous load or store would have already trapped,
10474 // so there is no harm doing an extra load (also, CSE will later eliminate
10475 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010476 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10477
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010478 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010479 --BBI;
10480
10481 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10482 if (LI->getOperand(0) == V) return true;
10483 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10484 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010485
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010486 }
Chris Lattner8a375202004-09-19 19:18:10 +000010487 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010488}
10489
Chris Lattner8d2e8882007-08-11 18:48:48 +000010490/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10491/// until we find the underlying object a pointer is referring to or something
10492/// we don't understand. Note that the returned pointer may be offset from the
10493/// input, because we ignore GEP indices.
10494static Value *GetUnderlyingObject(Value *Ptr) {
10495 while (1) {
10496 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10497 if (CE->getOpcode() == Instruction::BitCast ||
10498 CE->getOpcode() == Instruction::GetElementPtr)
10499 Ptr = CE->getOperand(0);
10500 else
10501 return Ptr;
10502 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10503 Ptr = BCI->getOperand(0);
10504 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10505 Ptr = GEP->getOperand(0);
10506 } else {
10507 return Ptr;
10508 }
10509 }
10510}
10511
Chris Lattner833b8a42003-06-26 05:06:25 +000010512Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10513 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010514
Dan Gohman9941f742007-07-20 16:34:21 +000010515 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010516 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10517 if (KnownAlign >
10518 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10519 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010520 LI.setAlignment(KnownAlign);
10521
Chris Lattner37366c12005-05-01 04:24:53 +000010522 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010523 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010524 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010525 return Res;
10526
10527 // None of the following transforms are legal for volatile loads.
10528 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010529
Chris Lattner62f254d2005-09-12 22:00:15 +000010530 if (&LI.getParent()->front() != &LI) {
10531 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010532 // If the instruction immediately before this is a store to the same
10533 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010534 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10535 if (SI->getOperand(1) == LI.getOperand(0))
10536 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010537 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10538 if (LIB->getOperand(0) == LI.getOperand(0))
10539 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010540 }
Chris Lattner37366c12005-05-01 04:24:53 +000010541
Christopher Lambb15147e2007-12-29 07:56:53 +000010542 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10543 const Value *GEPI0 = GEPI->getOperand(0);
10544 // TODO: Consider a target hook for valid address spaces for this xform.
10545 if (isa<ConstantPointerNull>(GEPI0) &&
10546 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010547 // Insert a new store to null instruction before the load to indicate
10548 // that this code is not reachable. We do this instead of inserting
10549 // an unreachable instruction directly because we cannot modify the
10550 // CFG.
10551 new StoreInst(UndefValue::get(LI.getType()),
10552 Constant::getNullValue(Op->getType()), &LI);
10553 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10554 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010555 }
Chris Lattner37366c12005-05-01 04:24:53 +000010556
Chris Lattnere87597f2004-10-16 18:11:37 +000010557 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010558 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010559 // TODO: Consider a target hook for valid address spaces for this xform.
10560 if (isa<UndefValue>(C) || (C->isNullValue() &&
10561 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010562 // Insert a new store to null instruction before the load to indicate that
10563 // this code is not reachable. We do this instead of inserting an
10564 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010565 new StoreInst(UndefValue::get(LI.getType()),
10566 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010567 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010568 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010569
Chris Lattnere87597f2004-10-16 18:11:37 +000010570 // Instcombine load (constant global) into the value loaded.
10571 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010572 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010573 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010574
Chris Lattnere87597f2004-10-16 18:11:37 +000010575 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010576 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010577 if (CE->getOpcode() == Instruction::GetElementPtr) {
10578 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010579 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010580 if (Constant *V =
10581 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010582 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010583 if (CE->getOperand(0)->isNullValue()) {
10584 // Insert a new store to null instruction before the load to indicate
10585 // that this code is not reachable. We do this instead of inserting
10586 // an unreachable instruction directly because we cannot modify the
10587 // CFG.
10588 new StoreInst(UndefValue::get(LI.getType()),
10589 Constant::getNullValue(Op->getType()), &LI);
10590 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10591 }
10592
Reid Spencer3da59db2006-11-27 01:05:10 +000010593 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010594 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010595 return Res;
10596 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010597 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010598 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010599
10600 // If this load comes from anywhere in a constant global, and if the global
10601 // is all undef or zero, we know what it loads.
10602 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10603 if (GV->isConstant() && GV->hasInitializer()) {
10604 if (GV->getInitializer()->isNullValue())
10605 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10606 else if (isa<UndefValue>(GV->getInitializer()))
10607 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10608 }
10609 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010610
Chris Lattner37366c12005-05-01 04:24:53 +000010611 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010612 // Change select and PHI nodes to select values instead of addresses: this
10613 // helps alias analysis out a lot, allows many others simplifications, and
10614 // exposes redundancy in the code.
10615 //
10616 // Note that we cannot do the transformation unless we know that the
10617 // introduced loads cannot trap! Something like this is valid as long as
10618 // the condition is always false: load (select bool %C, int* null, int* %G),
10619 // but it would not be valid if we transformed it to load from null
10620 // unconditionally.
10621 //
10622 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10623 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010624 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10625 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010626 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010627 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010628 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010629 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010630 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010631 }
10632
Chris Lattner684fe212004-09-23 15:46:00 +000010633 // load (select (cond, null, P)) -> load P
10634 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10635 if (C->isNullValue()) {
10636 LI.setOperand(0, SI->getOperand(2));
10637 return &LI;
10638 }
10639
10640 // load (select (cond, P, null)) -> load P
10641 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10642 if (C->isNullValue()) {
10643 LI.setOperand(0, SI->getOperand(1));
10644 return &LI;
10645 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010646 }
10647 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010648 return 0;
10649}
10650
Reid Spencer55af2b52007-01-19 21:20:31 +000010651/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010652/// when possible.
10653static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10654 User *CI = cast<User>(SI.getOperand(1));
10655 Value *CastOp = CI->getOperand(0);
10656
10657 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10658 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10659 const Type *SrcPTy = SrcTy->getElementType();
10660
Reid Spencer42230162007-01-22 05:51:25 +000010661 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010662 // If the source is an array, the code below will not succeed. Check to
10663 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10664 // constants.
10665 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10666 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10667 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010668 Value* Idxs[2];
10669 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10670 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010671 SrcTy = cast<PointerType>(CastOp->getType());
10672 SrcPTy = SrcTy->getElementType();
10673 }
10674
Reid Spencer67f827c2007-01-20 23:35:48 +000010675 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10676 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10677 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010678
10679 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010680 // the same size. Instead of casting the pointer before
10681 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010682 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010683 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010684 Instruction::CastOps opcode = Instruction::BitCast;
10685 const Type* CastSrcTy = SIOp0->getType();
10686 const Type* CastDstTy = SrcPTy;
10687 if (isa<PointerType>(CastDstTy)) {
10688 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010689 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010690 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010691 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010692 opcode = Instruction::PtrToInt;
10693 }
10694 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010695 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010696 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010697 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010698 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010699 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010700 return new StoreInst(NewCast, CastOp);
10701 }
10702 }
10703 }
10704 return 0;
10705}
10706
Chris Lattner2f503e62005-01-31 05:36:43 +000010707Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10708 Value *Val = SI.getOperand(0);
10709 Value *Ptr = SI.getOperand(1);
10710
10711 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010712 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010713 ++NumCombined;
10714 return 0;
10715 }
Chris Lattner836692d2007-01-15 06:51:56 +000010716
10717 // If the RHS is an alloca with a single use, zapify the store, making the
10718 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010719 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010720 if (isa<AllocaInst>(Ptr)) {
10721 EraseInstFromFunction(SI);
10722 ++NumCombined;
10723 return 0;
10724 }
10725
10726 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10727 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10728 GEP->getOperand(0)->hasOneUse()) {
10729 EraseInstFromFunction(SI);
10730 ++NumCombined;
10731 return 0;
10732 }
10733 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010734
Dan Gohman9941f742007-07-20 16:34:21 +000010735 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010736 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10737 if (KnownAlign >
10738 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10739 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010740 SI.setAlignment(KnownAlign);
10741
Chris Lattner9ca96412006-02-08 03:25:32 +000010742 // Do really simple DSE, to catch cases where there are several consequtive
10743 // stores to the same location, separated by a few arithmetic operations. This
10744 // situation often occurs with bitfield accesses.
10745 BasicBlock::iterator BBI = &SI;
10746 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10747 --ScanInsts) {
10748 --BBI;
10749
10750 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10751 // Prev store isn't volatile, and stores to the same location?
10752 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10753 ++NumDeadStore;
10754 ++BBI;
10755 EraseInstFromFunction(*PrevSI);
10756 continue;
10757 }
10758 break;
10759 }
10760
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010761 // If this is a load, we have to stop. However, if the loaded value is from
10762 // the pointer we're loading and is producing the pointer we're storing,
10763 // then *this* store is dead (X = load P; store X -> P).
10764 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010765 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010766 EraseInstFromFunction(SI);
10767 ++NumCombined;
10768 return 0;
10769 }
10770 // Otherwise, this is a load from some other location. Stores before it
10771 // may not be dead.
10772 break;
10773 }
10774
Chris Lattner9ca96412006-02-08 03:25:32 +000010775 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010776 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010777 break;
10778 }
10779
10780
10781 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010782
10783 // store X, null -> turns into 'unreachable' in SimplifyCFG
10784 if (isa<ConstantPointerNull>(Ptr)) {
10785 if (!isa<UndefValue>(Val)) {
10786 SI.setOperand(0, UndefValue::get(Val->getType()));
10787 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010788 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010789 ++NumCombined;
10790 }
10791 return 0; // Do not modify these!
10792 }
10793
10794 // store undef, Ptr -> noop
10795 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010796 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010797 ++NumCombined;
10798 return 0;
10799 }
10800
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010801 // If the pointer destination is a cast, see if we can fold the cast into the
10802 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010803 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010804 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10805 return Res;
10806 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010807 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010808 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10809 return Res;
10810
Chris Lattner408902b2005-09-12 23:23:25 +000010811
10812 // If this store is the last instruction in the basic block, and if the block
10813 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010814 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010815 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010816 if (BI->isUnconditional())
10817 if (SimplifyStoreAtEndOfBlock(SI))
10818 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010819
Chris Lattner2f503e62005-01-31 05:36:43 +000010820 return 0;
10821}
10822
Chris Lattner3284d1f2007-04-15 00:07:55 +000010823/// SimplifyStoreAtEndOfBlock - Turn things like:
10824/// if () { *P = v1; } else { *P = v2 }
10825/// into a phi node with a store in the successor.
10826///
Chris Lattner31755a02007-04-15 01:02:18 +000010827/// Simplify things like:
10828/// *P = v1; if () { *P = v2; }
10829/// into a phi node with a store in the successor.
10830///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010831bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10832 BasicBlock *StoreBB = SI.getParent();
10833
10834 // Check to see if the successor block has exactly two incoming edges. If
10835 // so, see if the other predecessor contains a store to the same location.
10836 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010837 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010838
10839 // Determine whether Dest has exactly two predecessors and, if so, compute
10840 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010841 pred_iterator PI = pred_begin(DestBB);
10842 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010843 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010844 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010845 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010846 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010847 return false;
10848
10849 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010850 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010851 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010852 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010853 }
Chris Lattner31755a02007-04-15 01:02:18 +000010854 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010855 return false;
10856
10857
Chris Lattner31755a02007-04-15 01:02:18 +000010858 // Verify that the other block ends in a branch and is not otherwise empty.
10859 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010860 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010861 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010862 return false;
10863
Chris Lattner31755a02007-04-15 01:02:18 +000010864 // If the other block ends in an unconditional branch, check for the 'if then
10865 // else' case. there is an instruction before the branch.
10866 StoreInst *OtherStore = 0;
10867 if (OtherBr->isUnconditional()) {
10868 // If this isn't a store, or isn't a store to the same location, bail out.
10869 --BBI;
10870 OtherStore = dyn_cast<StoreInst>(BBI);
10871 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10872 return false;
10873 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010874 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010875 // destinations is StoreBB, then we have the if/then case.
10876 if (OtherBr->getSuccessor(0) != StoreBB &&
10877 OtherBr->getSuccessor(1) != StoreBB)
10878 return false;
10879
10880 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010881 // if/then triangle. See if there is a store to the same ptr as SI that
10882 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010883 for (;; --BBI) {
10884 // Check to see if we find the matching store.
10885 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10886 if (OtherStore->getOperand(1) != SI.getOperand(1))
10887 return false;
10888 break;
10889 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010890 // If we find something that may be using the stored value, or if we run
10891 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010892 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10893 BBI == OtherBB->begin())
10894 return false;
10895 }
10896
10897 // In order to eliminate the store in OtherBr, we have to
10898 // make sure nothing reads the stored value in StoreBB.
10899 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10900 // FIXME: This should really be AA driven.
10901 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10902 return false;
10903 }
10904 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010905
Chris Lattner31755a02007-04-15 01:02:18 +000010906 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010907 Value *MergedVal = OtherStore->getOperand(0);
10908 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010909 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010910 PN->reserveOperandSpace(2);
10911 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010912 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10913 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010914 }
10915
10916 // Advance to a place where it is safe to insert the new store and
10917 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010918 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010919 while (isa<PHINode>(BBI)) ++BBI;
10920 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10921 OtherStore->isVolatile()), *BBI);
10922
10923 // Nuke the old stores.
10924 EraseInstFromFunction(SI);
10925 EraseInstFromFunction(*OtherStore);
10926 ++NumCombined;
10927 return true;
10928}
10929
Chris Lattner2f503e62005-01-31 05:36:43 +000010930
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010931Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10932 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010933 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010934 BasicBlock *TrueDest;
10935 BasicBlock *FalseDest;
10936 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10937 !isa<Constant>(X)) {
10938 // Swap Destinations and condition...
10939 BI.setCondition(X);
10940 BI.setSuccessor(0, FalseDest);
10941 BI.setSuccessor(1, TrueDest);
10942 return &BI;
10943 }
10944
Reid Spencere4d87aa2006-12-23 06:05:41 +000010945 // Cannonicalize fcmp_one -> fcmp_oeq
10946 FCmpInst::Predicate FPred; Value *Y;
10947 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10948 TrueDest, FalseDest)))
10949 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10950 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10951 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010952 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010953 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10954 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010955 // Swap Destinations and condition...
10956 BI.setCondition(NewSCC);
10957 BI.setSuccessor(0, FalseDest);
10958 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010959 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010960 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010961 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010962 return &BI;
10963 }
10964
10965 // Cannonicalize icmp_ne -> icmp_eq
10966 ICmpInst::Predicate IPred;
10967 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10968 TrueDest, FalseDest)))
10969 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10970 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10971 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10972 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010973 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010974 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10975 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010976 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010977 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010978 BI.setSuccessor(0, FalseDest);
10979 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010980 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010981 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010982 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010983 return &BI;
10984 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010985
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010986 return 0;
10987}
Chris Lattner0864acf2002-11-04 16:18:53 +000010988
Chris Lattner46238a62004-07-03 00:26:11 +000010989Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10990 Value *Cond = SI.getCondition();
10991 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10992 if (I->getOpcode() == Instruction::Add)
10993 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10994 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10995 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010996 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010997 AddRHS));
10998 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010999 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011000 return &SI;
11001 }
11002 }
11003 return 0;
11004}
11005
Chris Lattner220b0cf2006-03-05 00:22:33 +000011006/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11007/// is to leave as a vector operation.
11008static bool CheapToScalarize(Value *V, bool isConstant) {
11009 if (isa<ConstantAggregateZero>(V))
11010 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011011 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011012 if (isConstant) return true;
11013 // If all elts are the same, we can extract.
11014 Constant *Op0 = C->getOperand(0);
11015 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11016 if (C->getOperand(i) != Op0)
11017 return false;
11018 return true;
11019 }
11020 Instruction *I = dyn_cast<Instruction>(V);
11021 if (!I) return false;
11022
11023 // Insert element gets simplified to the inserted element or is deleted if
11024 // this is constant idx extract element and its a constant idx insertelt.
11025 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11026 isa<ConstantInt>(I->getOperand(2)))
11027 return true;
11028 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11029 return true;
11030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11031 if (BO->hasOneUse() &&
11032 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11033 CheapToScalarize(BO->getOperand(1), isConstant)))
11034 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011035 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11036 if (CI->hasOneUse() &&
11037 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11038 CheapToScalarize(CI->getOperand(1), isConstant)))
11039 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011040
11041 return false;
11042}
11043
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011044/// Read and decode a shufflevector mask.
11045///
11046/// It turns undef elements into values that are larger than the number of
11047/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011048static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11049 unsigned NElts = SVI->getType()->getNumElements();
11050 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11051 return std::vector<unsigned>(NElts, 0);
11052 if (isa<UndefValue>(SVI->getOperand(2)))
11053 return std::vector<unsigned>(NElts, 2*NElts);
11054
11055 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011056 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000011057 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11058 if (isa<UndefValue>(CP->getOperand(i)))
11059 Result.push_back(NElts*2); // undef -> 8
11060 else
Reid Spencerb83eb642006-10-20 07:07:24 +000011061 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011062 return Result;
11063}
11064
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011065/// FindScalarElement - Given a vector and an element number, see if the scalar
11066/// value is already around as a register, for example if it were inserted then
11067/// extracted from the vector.
11068static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011069 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11070 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011071 unsigned Width = PTy->getNumElements();
11072 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011073 return UndefValue::get(PTy->getElementType());
11074
11075 if (isa<UndefValue>(V))
11076 return UndefValue::get(PTy->getElementType());
11077 else if (isa<ConstantAggregateZero>(V))
11078 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011079 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011080 return CP->getOperand(EltNo);
11081 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11082 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011083 if (!isa<ConstantInt>(III->getOperand(2)))
11084 return 0;
11085 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011086
11087 // If this is an insert to the element we are looking for, return the
11088 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011089 if (EltNo == IIElt)
11090 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011091
11092 // Otherwise, the insertelement doesn't modify the value, recurse on its
11093 // vector input.
11094 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011095 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011096 unsigned InEl = getShuffleMask(SVI)[EltNo];
11097 if (InEl < Width)
11098 return FindScalarElement(SVI->getOperand(0), InEl);
11099 else if (InEl < Width*2)
11100 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11101 else
11102 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011103 }
11104
11105 // Otherwise, we don't know.
11106 return 0;
11107}
11108
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011109Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011110
Dan Gohman07a96762007-07-16 14:29:03 +000011111 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011112 if (isa<UndefValue>(EI.getOperand(0)))
11113 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11114
Dan Gohman07a96762007-07-16 14:29:03 +000011115 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011116 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11117 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11118
Reid Spencer9d6565a2007-02-15 02:26:10 +000011119 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000011120 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011121 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000011122 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011123 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011124 if (C->getOperand(i) != op0) {
11125 op0 = 0;
11126 break;
11127 }
11128 if (op0)
11129 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011130 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011131
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011132 // If extracting a specified index from the vector, see if we can recursively
11133 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011134 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011135 unsigned IndexVal = IdxC->getZExtValue();
11136 unsigned VectorWidth =
11137 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11138
11139 // If this is extracting an invalid index, turn this into undef, to avoid
11140 // crashing the code below.
11141 if (IndexVal >= VectorWidth)
11142 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11143
Chris Lattner867b99f2006-10-05 06:55:50 +000011144 // This instruction only demands the single element from the input vector.
11145 // If the input vector has a single use, simplify it based on this use
11146 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011147 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011148 uint64_t UndefElts;
11149 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011150 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011151 UndefElts)) {
11152 EI.setOperand(0, V);
11153 return &EI;
11154 }
11155 }
11156
Reid Spencerb83eb642006-10-20 07:07:24 +000011157 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011158 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011159
11160 // If the this extractelement is directly using a bitcast from a vector of
11161 // the same number of elements, see if we can find the source element from
11162 // it. In this case, we will end up needing to bitcast the scalars.
11163 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11164 if (const VectorType *VT =
11165 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11166 if (VT->getNumElements() == VectorWidth)
11167 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11168 return new BitCastInst(Elt, EI.getType());
11169 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011170 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011171
Chris Lattner73fa49d2006-05-25 22:53:38 +000011172 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011173 if (I->hasOneUse()) {
11174 // Push extractelement into predecessor operation if legal and
11175 // profitable to do so
11176 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011177 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11178 if (CheapToScalarize(BO, isConstantElt)) {
11179 ExtractElementInst *newEI0 =
11180 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11181 EI.getName()+".lhs");
11182 ExtractElementInst *newEI1 =
11183 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11184 EI.getName()+".rhs");
11185 InsertNewInstBefore(newEI0, EI);
11186 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011187 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011188 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011189 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011190 unsigned AS =
11191 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011192 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11193 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011194 GetElementPtrInst *GEP =
11195 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011196 InsertNewInstBefore(GEP, EI);
11197 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011198 }
11199 }
11200 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11201 // Extracting the inserted element?
11202 if (IE->getOperand(2) == EI.getOperand(1))
11203 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11204 // If the inserted and extracted elements are constants, they must not
11205 // be the same value, extract from the pre-inserted value instead.
11206 if (isa<Constant>(IE->getOperand(2)) &&
11207 isa<Constant>(EI.getOperand(1))) {
11208 AddUsesToWorkList(EI);
11209 EI.setOperand(0, IE->getOperand(0));
11210 return &EI;
11211 }
11212 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11213 // If this is extracting an element from a shufflevector, figure out where
11214 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011215 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11216 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011217 Value *Src;
11218 if (SrcIdx < SVI->getType()->getNumElements())
11219 Src = SVI->getOperand(0);
11220 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11221 SrcIdx -= SVI->getType()->getNumElements();
11222 Src = SVI->getOperand(1);
11223 } else {
11224 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011225 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011226 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011227 }
11228 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011229 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011230 return 0;
11231}
11232
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011233/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11234/// elements from either LHS or RHS, return the shuffle mask and true.
11235/// Otherwise, return false.
11236static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11237 std::vector<Constant*> &Mask) {
11238 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11239 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011240 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011241
11242 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011243 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011244 return true;
11245 } else if (V == LHS) {
11246 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011247 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011248 return true;
11249 } else if (V == RHS) {
11250 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011251 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011252 return true;
11253 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11254 // If this is an insert of an extract from some other vector, include it.
11255 Value *VecOp = IEI->getOperand(0);
11256 Value *ScalarOp = IEI->getOperand(1);
11257 Value *IdxOp = IEI->getOperand(2);
11258
Chris Lattnerd929f062006-04-27 21:14:21 +000011259 if (!isa<ConstantInt>(IdxOp))
11260 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011261 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011262
11263 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11264 // Okay, we can handle this if the vector we are insertinting into is
11265 // transitively ok.
11266 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11267 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011268 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011269 return true;
11270 }
11271 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11272 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011273 EI->getOperand(0)->getType() == V->getType()) {
11274 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011275 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011276
11277 // This must be extracting from either LHS or RHS.
11278 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11279 // Okay, we can handle this if the vector we are insertinting into is
11280 // transitively ok.
11281 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11282 // If so, update the mask to reflect the inserted value.
11283 if (EI->getOperand(0) == LHS) {
11284 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011285 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011286 } else {
11287 assert(EI->getOperand(0) == RHS);
11288 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011289 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011290
11291 }
11292 return true;
11293 }
11294 }
11295 }
11296 }
11297 }
11298 // TODO: Handle shufflevector here!
11299
11300 return false;
11301}
11302
11303/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11304/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11305/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011306static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011307 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011308 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011309 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011310 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011311 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011312
11313 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011314 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011315 return V;
11316 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011317 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011318 return V;
11319 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11320 // If this is an insert of an extract from some other vector, include it.
11321 Value *VecOp = IEI->getOperand(0);
11322 Value *ScalarOp = IEI->getOperand(1);
11323 Value *IdxOp = IEI->getOperand(2);
11324
11325 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11326 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11327 EI->getOperand(0)->getType() == V->getType()) {
11328 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011329 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11330 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011331
11332 // Either the extracted from or inserted into vector must be RHSVec,
11333 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011334 if (EI->getOperand(0) == RHS || RHS == 0) {
11335 RHS = EI->getOperand(0);
11336 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011337 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011338 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011339 return V;
11340 }
11341
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011342 if (VecOp == RHS) {
11343 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011344 // Everything but the extracted element is replaced with the RHS.
11345 for (unsigned i = 0; i != NumElts; ++i) {
11346 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011347 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011348 }
11349 return V;
11350 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011351
11352 // If this insertelement is a chain that comes from exactly these two
11353 // vectors, return the vector and the effective shuffle.
11354 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11355 return EI->getOperand(0);
11356
Chris Lattnerefb47352006-04-15 01:39:45 +000011357 }
11358 }
11359 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011360 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011361
11362 // Otherwise, can't do anything fancy. Return an identity vector.
11363 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011364 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011365 return V;
11366}
11367
11368Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11369 Value *VecOp = IE.getOperand(0);
11370 Value *ScalarOp = IE.getOperand(1);
11371 Value *IdxOp = IE.getOperand(2);
11372
Chris Lattner599ded12007-04-09 01:11:16 +000011373 // Inserting an undef or into an undefined place, remove this.
11374 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11375 ReplaceInstUsesWith(IE, VecOp);
11376
Chris Lattnerefb47352006-04-15 01:39:45 +000011377 // If the inserted element was extracted from some other vector, and if the
11378 // indexes are constant, try to turn this into a shufflevector operation.
11379 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11380 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11381 EI->getOperand(0)->getType() == IE.getType()) {
11382 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011383 unsigned ExtractedIdx =
11384 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011385 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011386
11387 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11388 return ReplaceInstUsesWith(IE, VecOp);
11389
11390 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11391 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11392
11393 // If we are extracting a value from a vector, then inserting it right
11394 // back into the same place, just use the input vector.
11395 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11396 return ReplaceInstUsesWith(IE, VecOp);
11397
11398 // We could theoretically do this for ANY input. However, doing so could
11399 // turn chains of insertelement instructions into a chain of shufflevector
11400 // instructions, and right now we do not merge shufflevectors. As such,
11401 // only do this in a situation where it is clear that there is benefit.
11402 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11403 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11404 // the values of VecOp, except then one read from EIOp0.
11405 // Build a new shuffle mask.
11406 std::vector<Constant*> Mask;
11407 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011408 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011409 else {
11410 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011411 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011412 NumVectorElts));
11413 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011414 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011415 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011416 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011417 }
11418
11419 // If this insertelement isn't used by some other insertelement, turn it
11420 // (and any insertelements it points to), into one big shuffle.
11421 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11422 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011423 Value *RHS = 0;
11424 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11425 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11426 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011427 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011428 }
11429 }
11430 }
11431
11432 return 0;
11433}
11434
11435
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011436Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11437 Value *LHS = SVI.getOperand(0);
11438 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011439 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011440
11441 bool MadeChange = false;
11442
Chris Lattner867b99f2006-10-05 06:55:50 +000011443 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011444 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011445 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11446
Chris Lattnere4929dd2007-01-05 07:36:08 +000011447 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011448 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011449 if (isa<UndefValue>(SVI.getOperand(1))) {
11450 // Scan to see if there are any references to the RHS. If so, replace them
11451 // with undef element refs and set MadeChange to true.
11452 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11453 if (Mask[i] >= e && Mask[i] != 2*e) {
11454 Mask[i] = 2*e;
11455 MadeChange = true;
11456 }
11457 }
11458
11459 if (MadeChange) {
11460 // Remap any references to RHS to use LHS.
11461 std::vector<Constant*> Elts;
11462 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11463 if (Mask[i] == 2*e)
11464 Elts.push_back(UndefValue::get(Type::Int32Ty));
11465 else
11466 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11467 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011468 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011469 }
11470 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011471
Chris Lattner863bcff2006-05-25 23:48:38 +000011472 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11473 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11474 if (LHS == RHS || isa<UndefValue>(LHS)) {
11475 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011476 // shuffle(undef,undef,mask) -> undef.
11477 return ReplaceInstUsesWith(SVI, LHS);
11478 }
11479
Chris Lattner863bcff2006-05-25 23:48:38 +000011480 // Remap any references to RHS to use LHS.
11481 std::vector<Constant*> Elts;
11482 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011483 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011484 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011485 else {
11486 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11487 (Mask[i] < e && isa<UndefValue>(LHS)))
11488 Mask[i] = 2*e; // Turn into undef.
11489 else
11490 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011491 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011492 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011493 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011494 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011495 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011496 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011497 LHS = SVI.getOperand(0);
11498 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011499 MadeChange = true;
11500 }
11501
Chris Lattner7b2e27922006-05-26 00:29:06 +000011502 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011503 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011504
Chris Lattner863bcff2006-05-25 23:48:38 +000011505 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11506 if (Mask[i] >= e*2) continue; // Ignore undef values.
11507 // Is this an identity shuffle of the LHS value?
11508 isLHSID &= (Mask[i] == i);
11509
11510 // Is this an identity shuffle of the RHS value?
11511 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011512 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011513
Chris Lattner863bcff2006-05-25 23:48:38 +000011514 // Eliminate identity shuffles.
11515 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11516 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011517
Chris Lattner7b2e27922006-05-26 00:29:06 +000011518 // If the LHS is a shufflevector itself, see if we can combine it with this
11519 // one without producing an unusual shuffle. Here we are really conservative:
11520 // we are absolutely afraid of producing a shuffle mask not in the input
11521 // program, because the code gen may not be smart enough to turn a merged
11522 // shuffle into two specific shuffles: it may produce worse code. As such,
11523 // we only merge two shuffles if the result is one of the two input shuffle
11524 // masks. In this case, merging the shuffles just removes one instruction,
11525 // which we know is safe. This is good for things like turning:
11526 // (splat(splat)) -> splat.
11527 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11528 if (isa<UndefValue>(RHS)) {
11529 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11530
11531 std::vector<unsigned> NewMask;
11532 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11533 if (Mask[i] >= 2*e)
11534 NewMask.push_back(2*e);
11535 else
11536 NewMask.push_back(LHSMask[Mask[i]]);
11537
11538 // If the result mask is equal to the src shuffle or this shuffle mask, do
11539 // the replacement.
11540 if (NewMask == LHSMask || NewMask == Mask) {
11541 std::vector<Constant*> Elts;
11542 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11543 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011544 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011545 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011546 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011547 }
11548 }
11549 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11550 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011551 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011552 }
11553 }
11554 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011555
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011556 return MadeChange ? &SVI : 0;
11557}
11558
11559
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011560
Chris Lattnerea1c4542004-12-08 23:43:58 +000011561
11562/// TryToSinkInstruction - Try to move the specified instruction from its
11563/// current block into the beginning of DestBlock, which can only happen if it's
11564/// safe to move the instruction past all of the instructions between it and the
11565/// end of its block.
11566static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11567 assert(I->hasOneUse() && "Invariants didn't hold!");
11568
Chris Lattner108e9022005-10-27 17:13:11 +000011569 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011570 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11571 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011572
Chris Lattnerea1c4542004-12-08 23:43:58 +000011573 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011574 if (isa<AllocaInst>(I) && I->getParent() ==
11575 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011576 return false;
11577
Chris Lattner96a52a62004-12-09 07:14:34 +000011578 // We can only sink load instructions if there is nothing between the load and
11579 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011580 if (I->mayReadFromMemory()) {
11581 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011582 Scan != E; ++Scan)
11583 if (Scan->mayWriteToMemory())
11584 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011585 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011586
11587 BasicBlock::iterator InsertPos = DestBlock->begin();
11588 while (isa<PHINode>(InsertPos)) ++InsertPos;
11589
Chris Lattner4bc5f802005-08-08 19:11:57 +000011590 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011591 ++NumSunkInst;
11592 return true;
11593}
11594
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011595
11596/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11597/// all reachable code to the worklist.
11598///
11599/// This has a couple of tricks to make the code faster and more powerful. In
11600/// particular, we constant fold and DCE instructions as we go, to avoid adding
11601/// them to the worklist (this significantly speeds up instcombine on code where
11602/// many instructions are dead or constant). Additionally, if we find a branch
11603/// whose condition is a known constant, we only visit the reachable successors.
11604///
11605static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011606 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011607 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011608 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011609 std::vector<BasicBlock*> Worklist;
11610 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011611
Chris Lattner2c7718a2007-03-23 19:17:18 +000011612 while (!Worklist.empty()) {
11613 BB = Worklist.back();
11614 Worklist.pop_back();
11615
11616 // We have now visited this block! If we've already been here, ignore it.
11617 if (!Visited.insert(BB)) continue;
11618
11619 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11620 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011621
Chris Lattner2c7718a2007-03-23 19:17:18 +000011622 // DCE instruction if trivially dead.
11623 if (isInstructionTriviallyDead(Inst)) {
11624 ++NumDeadInst;
11625 DOUT << "IC: DCE: " << *Inst;
11626 Inst->eraseFromParent();
11627 continue;
11628 }
11629
11630 // ConstantProp instruction if trivially constant.
11631 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11632 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11633 Inst->replaceAllUsesWith(C);
11634 ++NumConstProp;
11635 Inst->eraseFromParent();
11636 continue;
11637 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011638
Chris Lattner2c7718a2007-03-23 19:17:18 +000011639 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011640 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011641
11642 // Recursively visit successors. If this is a branch or switch on a
11643 // constant, only visit the reachable successor.
11644 TerminatorInst *TI = BB->getTerminator();
11645 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11646 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11647 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011648 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011649 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011650 continue;
11651 }
11652 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11653 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11654 // See if this is an explicit destination.
11655 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11656 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011657 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011658 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011659 continue;
11660 }
11661
11662 // Otherwise it is the default destination.
11663 Worklist.push_back(SI->getSuccessor(0));
11664 continue;
11665 }
11666 }
11667
11668 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11669 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011670 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011671}
11672
Chris Lattnerec9c3582007-03-03 02:04:50 +000011673bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011674 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011675 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011676
11677 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11678 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011679
Chris Lattnerb3d59702005-07-07 20:40:38 +000011680 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011681 // Do a depth-first traversal of the function, populate the worklist with
11682 // the reachable instructions. Ignore blocks that are not reachable. Keep
11683 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011684 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011685 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011686
Chris Lattnerb3d59702005-07-07 20:40:38 +000011687 // Do a quick scan over the function. If we find any blocks that are
11688 // unreachable, remove any instructions inside of them. This prevents
11689 // the instcombine code from having to deal with some bad special cases.
11690 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11691 if (!Visited.count(BB)) {
11692 Instruction *Term = BB->getTerminator();
11693 while (Term != BB->begin()) { // Remove instrs bottom-up
11694 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011695
Bill Wendlingb7427032006-11-26 09:46:52 +000011696 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011697 ++NumDeadInst;
11698
11699 if (!I->use_empty())
11700 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11701 I->eraseFromParent();
11702 }
11703 }
11704 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011705
Chris Lattnerdbab3862007-03-02 21:28:56 +000011706 while (!Worklist.empty()) {
11707 Instruction *I = RemoveOneFromWorkList();
11708 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011709
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011710 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011711 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011712 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011713 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011714 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011715 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011716
Bill Wendlingb7427032006-11-26 09:46:52 +000011717 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011718
11719 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011720 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011721 continue;
11722 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011723
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011724 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011725 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011726 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011727
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011728 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011729 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011730 ReplaceInstUsesWith(*I, C);
11731
Chris Lattner62b14df2002-09-02 04:59:56 +000011732 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011733 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011734 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011735 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011736 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011737
Chris Lattnerea1c4542004-12-08 23:43:58 +000011738 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011739 // FIXME: Remove GetResultInst test when first class support for aggregates
11740 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011741 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011742 BasicBlock *BB = I->getParent();
11743 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11744 if (UserParent != BB) {
11745 bool UserIsSuccessor = false;
11746 // See if the user is one of our successors.
11747 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11748 if (*SI == UserParent) {
11749 UserIsSuccessor = true;
11750 break;
11751 }
11752
11753 // If the user is one of our immediate successors, and if that successor
11754 // only has us as a predecessors (we'd have to split the critical edge
11755 // otherwise), we can keep going.
11756 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11757 next(pred_begin(UserParent)) == pred_end(UserParent))
11758 // Okay, the CFG is simple enough, try to sink this instruction.
11759 Changed |= TryToSinkInstruction(I, UserParent);
11760 }
11761 }
11762
Chris Lattner8a2a3112001-12-14 16:52:21 +000011763 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011764#ifndef NDEBUG
11765 std::string OrigI;
11766#endif
11767 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011768 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011769 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011770 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011771 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011772 DOUT << "IC: Old = " << *I
11773 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011774
Chris Lattnerf523d062004-06-09 05:08:07 +000011775 // Everything uses the new instruction now.
11776 I->replaceAllUsesWith(Result);
11777
11778 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011779 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011780 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011781
Chris Lattner6934a042007-02-11 01:23:03 +000011782 // Move the name to the new instruction first.
11783 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011784
11785 // Insert the new instruction into the basic block...
11786 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011787 BasicBlock::iterator InsertPos = I;
11788
11789 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11790 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11791 ++InsertPos;
11792
11793 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011794
Chris Lattner00d51312004-05-01 23:27:23 +000011795 // Make sure that we reprocess all operands now that we reduced their
11796 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011797 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011798
Chris Lattnerf523d062004-06-09 05:08:07 +000011799 // Instructions can end up on the worklist more than once. Make sure
11800 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011801 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011802
11803 // Erase the old instruction.
11804 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011805 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011806#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011807 DOUT << "IC: Mod = " << OrigI
11808 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011809#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011810
Chris Lattner90ac28c2002-08-02 19:29:35 +000011811 // If the instruction was modified, it's possible that it is now dead.
11812 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011813 if (isInstructionTriviallyDead(I)) {
11814 // Make sure we process all operands now that we are reducing their
11815 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011816 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011817
Chris Lattner00d51312004-05-01 23:27:23 +000011818 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011819 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011820 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011821 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011822 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011823 AddToWorkList(I);
11824 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011825 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011826 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011827 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011828 }
11829 }
11830
Chris Lattnerec9c3582007-03-03 02:04:50 +000011831 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011832
11833 // Do an explicit clear, this shrinks the map if needed.
11834 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011835 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011836}
11837
Chris Lattnerec9c3582007-03-03 02:04:50 +000011838
11839bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011840 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11841
Chris Lattnerec9c3582007-03-03 02:04:50 +000011842 bool EverMadeChange = false;
11843
11844 // Iterate while there is work to do.
11845 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011846 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011847 EverMadeChange = true;
11848 return EverMadeChange;
11849}
11850
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011851FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011852 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011853}
Brian Gaeked0fde302003-11-11 22:41:34 +000011854