blob: 4f4296f83a7f3e2303338940c13a683073af9fc6 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000051#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000058#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000059#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000062#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000063#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000064#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000066#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000067#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000068#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000069using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000070using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000077
Chris Lattner0e5f4992006-12-19 21:40:18 +000078namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000079 /// InstCombineWorklist - This is the worklist management logic for
80 /// InstCombine.
81 class InstCombineWorklist {
82 SmallVector<Instruction*, 256> Worklist;
83 DenseMap<Instruction*, unsigned> WorklistMap;
84
85 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
86 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
87 public:
88 InstCombineWorklist() {}
89
90 bool isEmpty() const { return Worklist.empty(); }
91
92 /// Add - Add the specified instruction to the worklist if it isn't already
93 /// in it.
94 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000097 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000098 }
Chris Lattner873ff012009-08-30 05:55:36 +000099 }
100
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000101 void AddValue(Value *V) {
102 if (Instruction *I = dyn_cast<Instruction>(V))
103 Add(I);
104 }
105
Chris Lattner67f7d542009-10-12 03:58:40 +0000106 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
107 /// which should only be done when the worklist is empty and when the group
108 /// has no duplicates.
109 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
110 assert(Worklist.empty() && "Worklist must be empty to add initial group");
111 Worklist.reserve(NumEntries+16);
112 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
113 for (; NumEntries; --NumEntries) {
114 Instruction *I = List[NumEntries-1];
115 WorklistMap.insert(std::make_pair(I, Worklist.size()));
116 Worklist.push_back(I);
117 }
118 }
119
Chris Lattner7a1e9242009-08-30 06:13:40 +0000120 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000121 void Remove(Instruction *I) {
122 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
123 if (It == WorklistMap.end()) return; // Not in worklist.
124
125 // Don't bother moving everything down, just null out the slot.
126 Worklist[It->second] = 0;
127
128 WorklistMap.erase(It);
129 }
130
131 Instruction *RemoveOne() {
132 Instruction *I = Worklist.back();
133 Worklist.pop_back();
134 WorklistMap.erase(I);
135 return I;
136 }
137
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000138 /// AddUsersToWorkList - When an instruction is simplified, add all users of
139 /// the instruction to the work lists because they might get more simplified
140 /// now.
141 ///
142 void AddUsersToWorkList(Instruction &I) {
143 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
144 UI != UE; ++UI)
145 Add(cast<Instruction>(*UI));
146 }
147
Chris Lattner873ff012009-08-30 05:55:36 +0000148
149 /// Zap - check that the worklist is empty and nuke the backing store for
150 /// the map if it is large.
151 void Zap() {
152 assert(WorklistMap.empty() && "Worklist empty, but map not?");
153
154 // Do an explicit clear, this shrinks the map if needed.
155 WorklistMap.clear();
156 }
157 };
158} // end anonymous namespace.
159
160
161namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000162 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
163 /// just like the normal insertion helper, but also adds any new instructions
164 /// to the instcombine worklist.
165 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
166 InstCombineWorklist &Worklist;
167 public:
168 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
169
170 void InsertHelper(Instruction *I, const Twine &Name,
171 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
172 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
173 Worklist.Add(I);
174 }
175 };
176} // end anonymous namespace
177
178
179namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000180 class InstCombiner : public FunctionPass,
181 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000182 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000183 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000184 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000185 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000186 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000187 InstCombineWorklist Worklist;
188
Chris Lattner74381062009-08-30 07:44:24 +0000189 /// Builder - This is an IRBuilder that automatically inserts new
190 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000191 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000192 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000193
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000194 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000195 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000196
Owen Andersone922c022009-07-22 00:24:57 +0000197 LLVMContext *Context;
198 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000199
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000200 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000201 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000202
203 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000204
Chris Lattner97e52e42002-04-28 21:27:06 +0000205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000206 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000207 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000208 }
209
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000210 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000211
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000212 // Visitation implementation - Implement instruction combining for different
213 // instruction types. The semantics are as follows:
214 // Return Value:
215 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000216 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000217 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000218 //
Chris Lattner7e708292002-06-25 16:13:24 +0000219 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000220 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000221 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000223 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000225 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000226 Instruction *visitURem(BinaryOperator &I);
227 Instruction *visitSRem(BinaryOperator &I);
228 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000229 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000230 Instruction *commonRemTransforms(BinaryOperator &I);
231 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000232 Instruction *commonDivTransforms(BinaryOperator &I);
233 Instruction *commonIDivTransforms(BinaryOperator &I);
234 Instruction *visitUDiv(BinaryOperator &I);
235 Instruction *visitSDiv(BinaryOperator &I);
236 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000237 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000238 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000240 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000241 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000242 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000243 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitOr (BinaryOperator &I);
245 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000246 Instruction *visitShl(BinaryOperator &I);
247 Instruction *visitAShr(BinaryOperator &I);
248 Instruction *visitLShr(BinaryOperator &I);
249 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000250 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
251 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000252 Instruction *visitFCmpInst(FCmpInst &I);
253 Instruction *visitICmpInst(ICmpInst &I);
254 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000255 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256 Instruction *LHS,
257 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000258 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000260
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000261 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000262 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000263 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000264 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000265 Instruction *commonCastTransforms(CastInst &CI);
266 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000267 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000268 Instruction *visitTrunc(TruncInst &CI);
269 Instruction *visitZExt(ZExtInst &CI);
270 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000271 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000272 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000273 Instruction *visitFPToUI(FPToUIInst &FI);
274 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000275 Instruction *visitUIToFP(CastInst &CI);
276 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000277 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000278 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000279 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000280 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
281 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000282 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000283 Instruction *visitSelectInst(SelectInst &SI);
284 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000285 Instruction *visitCallInst(CallInst &CI);
286 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000287
288 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000289 Instruction *visitPHINode(PHINode &PN);
290 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000291 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000292 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000293 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000294 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000295 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000296 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000297 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000298 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000299 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000300 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000301
302 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000303 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000304
Chris Lattner9fe38862003-06-19 17:00:31 +0000305 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000306 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000307 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000308 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000309 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
310 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000311 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000312 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
313
Chris Lattner9fe38862003-06-19 17:00:31 +0000314
Chris Lattner28977af2004-04-05 01:30:19 +0000315 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000316 // InsertNewInstBefore - insert an instruction New before instruction Old
317 // in the program. Add the new instruction to the worklist.
318 //
Chris Lattner955f3312004-09-28 21:48:02 +0000319 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000320 assert(New && New->getParent() == 0 &&
321 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000322 BasicBlock *BB = Old.getParent();
323 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000324 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000325 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000326 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000327
Chris Lattner8b170942002-08-09 23:47:40 +0000328 // ReplaceInstUsesWith - This method is to be used when an instruction is
329 // found to be dead, replacable with another preexisting expression. Here
330 // we add all uses of I to the worklist, replace all uses of I with the new
331 // value, then return I, so that the inst combiner will know that I was
332 // modified.
333 //
334 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000335 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000336
337 // If we are replacing the instruction with itself, this must be in a
338 // segment of unreachable code, so just clobber the instruction.
339 if (&I == V)
340 V = UndefValue::get(I.getType());
341
342 I.replaceAllUsesWith(V);
343 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000344 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000345
346 // EraseInstFromFunction - When dealing with an instruction that has side
347 // effects or produces a void value, we can't rely on DCE to delete the
348 // instruction. Instead, visit methods should return the value returned by
349 // this function.
350 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000351 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000352
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000353 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000354 // Make sure that we reprocess all operands now that we reduced their
355 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000356 if (I.getNumOperands() < 8) {
357 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
358 if (Instruction *Op = dyn_cast<Instruction>(*i))
359 Worklist.Add(Op);
360 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000361 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000362 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000363 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000364 return 0; // Don't do anything with FI
365 }
Chris Lattner173234a2008-06-02 01:18:21 +0000366
367 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368 APInt &KnownOne, unsigned Depth = 0) const {
369 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
370 }
371
372 bool MaskedValueIsZero(Value *V, const APInt &Mask,
373 unsigned Depth = 0) const {
374 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
375 }
376 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377 return llvm::ComputeNumSignBits(Op, TD, Depth);
378 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000379
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000380 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000381
Reid Spencere4d87aa2006-12-23 06:05:41 +0000382 /// SimplifyCommutative - This performs a few simplifications for
383 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000384 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000385
Chris Lattner886ab6c2009-01-31 08:15:18 +0000386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
390 unsigned Depth);
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000392 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000393 unsigned Depth=0);
394
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
Evan Cheng388df622009-02-03 10:05:09 +0000400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000402
Chris Lattner5d1704d2009-09-27 19:57:57 +0000403 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404 // which has a PHI node as operand #0, see if we can fold the instruction
405 // into the PHI (which is only possible if all operands to the PHI are
406 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000407 //
408 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409 // that would normally be unprofitable because they strongly encourage jump
410 // threading.
411 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000412
Chris Lattnerbac32862004-11-14 19:13:23 +0000413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414 // operator and they all are only used by the PHI, PHI together their
415 // inputs, and do the operation once, to the result of the PHI.
416 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000417 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000418 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000419 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000420
Chris Lattner7da52b22006-11-01 04:51:18 +0000421
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000424
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000426 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000428 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000430 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000433 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000434
Chris Lattnerafe91a52006-06-15 19:07:26 +0000435
Reid Spencerc55b2432006-12-13 18:21:21 +0000436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000437
Dan Gohman6de29f82009-06-15 22:12:54 +0000438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000439 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000442
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000443 };
Chris Lattner873ff012009-08-30 05:55:36 +0000444} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000445
Dan Gohman844731a2008-05-13 00:00:25 +0000446char InstCombiner::ID = 0;
447static RegisterPass<InstCombiner>
448X("instcombine", "Combine redundant instructions");
449
Chris Lattner4f98c562003-03-10 21:43:22 +0000450// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000451// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000452static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000453 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000456 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000457 return 3;
458 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000459 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000462}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000463
Chris Lattnerc8802d22003-03-11 00:12:48 +0000464// isOnlyUse - Return true if this instruction will be deleted if we stop using
465// it.
466static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000467 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000468}
469
Chris Lattner4cb170c2004-02-23 06:38:22 +0000470// getPromotedType - Return the specified type promoted as it would be to pass
471// though a va_arg area...
472static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000475 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000476 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000477 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000478}
479
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000480/// ShouldChangeType - Return true if it is desirable to convert a computation
481/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
482/// type for example, or from a smaller to a larger illegal type.
483static bool ShouldChangeType(const Type *From, const Type *To,
484 const TargetData *TD) {
485 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
486
487 // If we don't have TD, we don't know if the source/dest are legal.
488 if (!TD) return false;
489
490 unsigned FromWidth = From->getPrimitiveSizeInBits();
491 unsigned ToWidth = To->getPrimitiveSizeInBits();
492 bool FromLegal = TD->isLegalInteger(FromWidth);
493 bool ToLegal = TD->isLegalInteger(ToWidth);
494
495 // If this is a legal integer from type, and the result would be an illegal
496 // type, don't do the transformation.
497 if (FromLegal && !ToLegal)
498 return false;
499
500 // Otherwise, if both are illegal, do not increase the size of the result. We
501 // do allow things like i160 -> i64, but not i64 -> i160.
502 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
503 return false;
504
505 return true;
506}
507
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000508/// getBitCastOperand - If the specified operand is a CastInst, a constant
509/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
510/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000511static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000512 if (Operator *O = dyn_cast<Operator>(V)) {
513 if (O->getOpcode() == Instruction::BitCast)
514 return O->getOperand(0);
515 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
516 if (GEP->hasAllZeroIndices())
517 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000518 }
Chris Lattnereed48272005-09-13 00:40:14 +0000519 return 0;
520}
521
Reid Spencer3da59db2006-11-27 01:05:10 +0000522/// This function is a wrapper around CastInst::isEliminableCastPair. It
523/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000524static Instruction::CastOps
525isEliminableCastPair(
526 const CastInst *CI, ///< The first cast instruction
527 unsigned opcode, ///< The opcode of the second cast instruction
528 const Type *DstTy, ///< The target type for the second cast instruction
529 TargetData *TD ///< The target data for pointer size
530) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000531
Reid Spencer3da59db2006-11-27 01:05:10 +0000532 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
533 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000534
Reid Spencer3da59db2006-11-27 01:05:10 +0000535 // Get the opcodes of the two Cast instructions
536 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
537 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000538
Chris Lattnera0e69692009-03-24 18:35:40 +0000539 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000540 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000541 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000542
543 // We don't want to form an inttoptr or ptrtoint that converts to an integer
544 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000545 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000546 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000547 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000548 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000549 Res = 0;
550
551 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000552}
553
554/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
555/// in any code being generated. It does not require codegen if V is simple
556/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000557static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
558 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000559 if (V->getType() == Ty || isa<Constant>(V)) return false;
560
Chris Lattner01575b72006-05-25 23:24:33 +0000561 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000562 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000563 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000564 return false;
565 return true;
566}
567
Chris Lattner4f98c562003-03-10 21:43:22 +0000568// SimplifyCommutative - This performs a few simplifications for commutative
569// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000570//
Chris Lattner4f98c562003-03-10 21:43:22 +0000571// 1. Order operands such that they are listed from right (least complex) to
572// left (most complex). This puts constants before unary operators before
573// binary operators.
574//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
576// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000577//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000578bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000579 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000580 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000581 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000582
Chris Lattner4f98c562003-03-10 21:43:22 +0000583 if (!I.isAssociative()) return Changed;
584 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000585 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
586 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
587 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000588 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000589 cast<Constant>(I.getOperand(1)),
590 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 I.setOperand(0, Op->getOperand(0));
592 I.setOperand(1, Folded);
593 return true;
594 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
595 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
596 isOnlyUse(Op) && isOnlyUse(Op1)) {
597 Constant *C1 = cast<Constant>(Op->getOperand(1));
598 Constant *C2 = cast<Constant>(Op1->getOperand(1));
599
600 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000601 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000602 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000603 Op1->getOperand(0),
604 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000605 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000606 I.setOperand(0, New);
607 I.setOperand(1, Folded);
608 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000609 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000610 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000611 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000612}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000613
Chris Lattner8d969642003-03-10 23:06:50 +0000614// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
615// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000616//
Dan Gohman186a6362009-08-12 16:04:34 +0000617static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000618 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000619 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000620
Chris Lattner0ce85802004-12-14 20:08:06 +0000621 // Constants can be considered to be negated values if they can be folded.
622 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000623 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000624
625 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000627 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000628
Chris Lattner8d969642003-03-10 23:06:50 +0000629 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000630}
631
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000632// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
633// instruction if the LHS is a constant negative zero (which is the 'negate'
634// form).
635//
Dan Gohman186a6362009-08-12 16:04:34 +0000636static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000637 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000638 return BinaryOperator::getFNegArgument(V);
639
640 // Constants can be considered to be negated values if they can be folded.
641 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000642 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000643
644 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
645 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000646 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000647
648 return 0;
649}
650
Chris Lattner48b59ec2009-10-26 15:40:07 +0000651/// isFreeToInvert - Return true if the specified value is free to invert (apply
652/// ~ to). This happens in cases where the ~ can be eliminated.
653static inline bool isFreeToInvert(Value *V) {
654 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000655 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000656 return true;
657
658 // Constants can be considered to be not'ed values.
659 if (isa<ConstantInt>(V))
660 return true;
661
662 // Compares can be inverted if they have a single use.
663 if (CmpInst *CI = dyn_cast<CmpInst>(V))
664 return CI->hasOneUse();
665
666 return false;
667}
668
669static inline Value *dyn_castNotVal(Value *V) {
670 // If this is not(not(x)) don't return that this is a not: we want the two
671 // not's to be folded first.
672 if (BinaryOperator::isNot(V)) {
673 Value *Operand = BinaryOperator::getNotArgument(V);
674 if (!isFreeToInvert(Operand))
675 return Operand;
676 }
Chris Lattner8d969642003-03-10 23:06:50 +0000677
678 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000679 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000680 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000681 return 0;
682}
683
Chris Lattner48b59ec2009-10-26 15:40:07 +0000684
685
Chris Lattnerc8802d22003-03-11 00:12:48 +0000686// dyn_castFoldableMul - If this value is a multiply that can be folded into
687// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000688// non-constant operand of the multiply, and set CST to point to the multiplier.
689// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000690//
Dan Gohman186a6362009-08-12 16:04:34 +0000691static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000692 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000693 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000694 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000695 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000696 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000697 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000698 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000699 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000700 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000701 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000702 CST = ConstantInt::get(V->getType()->getContext(),
703 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000704 return I->getOperand(0);
705 }
706 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000707 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000708}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000709
Reid Spencer7177c3a2007-03-25 05:33:51 +0000710/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000711static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000712 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000713 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000714}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000715/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000716static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000717 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000718 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000719}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000720/// MultiplyOverflows - True if the multiply can not be expressed in an int
721/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000722static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000723 uint32_t W = C1->getBitWidth();
724 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
725 if (sign) {
726 LHSExt.sext(W * 2);
727 RHSExt.sext(W * 2);
728 } else {
729 LHSExt.zext(W * 2);
730 RHSExt.zext(W * 2);
731 }
732
733 APInt MulExt = LHSExt * RHSExt;
734
735 if (sign) {
736 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
737 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
738 return MulExt.slt(Min) || MulExt.sgt(Max);
739 } else
740 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
741}
Chris Lattner955f3312004-09-28 21:48:02 +0000742
Reid Spencere7816b52007-03-08 01:52:58 +0000743
Chris Lattner255d8912006-02-11 09:31:47 +0000744/// ShrinkDemandedConstant - Check to see if the specified operand of the
745/// specified instruction is a constant integer. If so, check to see if there
746/// are any bits set in the constant that are not demanded. If so, shrink the
747/// constant and return true.
748static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000749 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000750 assert(I && "No instruction?");
751 assert(OpNo < I->getNumOperands() && "Operand index too large");
752
753 // If the operand is not a constant integer, nothing to do.
754 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
755 if (!OpC) return false;
756
757 // If there are no bits set that aren't demanded, nothing to do.
758 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
759 if ((~Demanded & OpC->getValue()) == 0)
760 return false;
761
762 // This instruction is producing bits that are not demanded. Shrink the RHS.
763 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000764 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000765 return true;
766}
767
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000768// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
769// set of known zero and one bits, compute the maximum and minimum values that
770// could have the specified known zero and known one bits, returning them in
771// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000772static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000773 const APInt& KnownOne,
774 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000775 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
776 KnownZero.getBitWidth() == Min.getBitWidth() &&
777 KnownZero.getBitWidth() == Max.getBitWidth() &&
778 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000779 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000780
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000781 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
782 // bit if it is unknown.
783 Min = KnownOne;
784 Max = KnownOne|UnknownBits;
785
Dan Gohman1c8491e2009-04-25 17:12:48 +0000786 if (UnknownBits.isNegative()) { // Sign bit is unknown
787 Min.set(Min.getBitWidth()-1);
788 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000789 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000790}
791
792// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793// a set of known zero and one bits, compute the maximum and minimum values that
794// could have the specified known zero and known one bits, returning them in
795// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000796static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000797 const APInt &KnownOne,
798 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000799 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
800 KnownZero.getBitWidth() == Min.getBitWidth() &&
801 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000802 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000803 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000804
805 // The minimum value is when the unknown bits are all zeros.
806 Min = KnownOne;
807 // The maximum value is when the unknown bits are all ones.
808 Max = KnownOne|UnknownBits;
809}
Chris Lattner255d8912006-02-11 09:31:47 +0000810
Chris Lattner886ab6c2009-01-31 08:15:18 +0000811/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
812/// SimplifyDemandedBits knows about. See if the instruction has any
813/// properties that allow us to simplify its operands.
814bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000815 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000816 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
817 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
818
819 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
820 KnownZero, KnownOne, 0);
821 if (V == 0) return false;
822 if (V == &Inst) return true;
823 ReplaceInstUsesWith(Inst, V);
824 return true;
825}
826
827/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
828/// specified instruction operand if possible, updating it in place. It returns
829/// true if it made any change and false otherwise.
830bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
831 APInt &KnownZero, APInt &KnownOne,
832 unsigned Depth) {
833 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
834 KnownZero, KnownOne, Depth);
835 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000836 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000837 return true;
838}
839
840
841/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
842/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000843/// that only the bits set in DemandedMask of the result of V are ever used
844/// downstream. Consequently, depending on the mask and V, it may be possible
845/// to replace V with a constant or one of its operands. In such cases, this
846/// function does the replacement and returns true. In all other cases, it
847/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000848/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000849/// to be zero in the expression. These are provided to potentially allow the
850/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
851/// the expression. KnownOne and KnownZero always follow the invariant that
852/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
853/// the bits in KnownOne and KnownZero may only be accurate for those bits set
854/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
855/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000856///
857/// This returns null if it did not change anything and it permits no
858/// simplification. This returns V itself if it did some simplification of V's
859/// operands based on the information about what bits are demanded. This returns
860/// some other non-null value if it found out that V is equal to another value
861/// in the context where the specified bits are demanded, but not for all users.
862Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
863 APInt &KnownZero, APInt &KnownOne,
864 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000865 assert(V != 0 && "Null pointer of Value???");
866 assert(Depth <= 6 && "Limit Search Depth");
867 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000868 const Type *VTy = V->getType();
869 assert((TD || !isa<PointerType>(VTy)) &&
870 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000871 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
872 (!VTy->isIntOrIntVector() ||
873 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000874 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000875 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000876 "Value *V, DemandedMask, KnownZero and KnownOne "
877 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000878 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
879 // We know all of the bits for a constant!
880 KnownOne = CI->getValue() & DemandedMask;
881 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000882 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000883 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000884 if (isa<ConstantPointerNull>(V)) {
885 // We know all of the bits for a constant!
886 KnownOne.clear();
887 KnownZero = DemandedMask;
888 return 0;
889 }
890
Chris Lattner08d2cc72009-01-31 07:26:06 +0000891 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000892 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000893 if (DemandedMask == 0) { // Not demanding any bits from V.
894 if (isa<UndefValue>(V))
895 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000896 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000897 }
898
Chris Lattner4598c942009-01-31 08:24:16 +0000899 if (Depth == 6) // Limit search depth.
900 return 0;
901
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000902 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
903 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
904
Dan Gohman1c8491e2009-04-25 17:12:48 +0000905 Instruction *I = dyn_cast<Instruction>(V);
906 if (!I) {
907 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
908 return 0; // Only analyze instructions.
909 }
910
Chris Lattner4598c942009-01-31 08:24:16 +0000911 // If there are multiple uses of this value and we aren't at the root, then
912 // we can't do any simplifications of the operands, because DemandedMask
913 // only reflects the bits demanded by *one* of the users.
914 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000915 // Despite the fact that we can't simplify this instruction in all User's
916 // context, we can at least compute the knownzero/knownone bits, and we can
917 // do simplifications that apply to *just* the one user if we know that
918 // this instruction has a simpler value in that context.
919 if (I->getOpcode() == Instruction::And) {
920 // If either the LHS or the RHS are Zero, the result is zero.
921 ComputeMaskedBits(I->getOperand(1), DemandedMask,
922 RHSKnownZero, RHSKnownOne, Depth+1);
923 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
924 LHSKnownZero, LHSKnownOne, Depth+1);
925
926 // If all of the demanded bits are known 1 on one side, return the other.
927 // These bits cannot contribute to the result of the 'and' in this
928 // context.
929 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
930 (DemandedMask & ~LHSKnownZero))
931 return I->getOperand(0);
932 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
933 (DemandedMask & ~RHSKnownZero))
934 return I->getOperand(1);
935
936 // If all of the demanded bits in the inputs are known zeros, return zero.
937 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000938 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000939
940 } else if (I->getOpcode() == Instruction::Or) {
941 // We can simplify (X|Y) -> X or Y in the user's context if we know that
942 // only bits from X or Y are demanded.
943
944 // If either the LHS or the RHS are One, the result is One.
945 ComputeMaskedBits(I->getOperand(1), DemandedMask,
946 RHSKnownZero, RHSKnownOne, Depth+1);
947 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
948 LHSKnownZero, LHSKnownOne, Depth+1);
949
950 // If all of the demanded bits are known zero on one side, return the
951 // other. These bits cannot contribute to the result of the 'or' in this
952 // context.
953 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
954 (DemandedMask & ~LHSKnownOne))
955 return I->getOperand(0);
956 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
957 (DemandedMask & ~RHSKnownOne))
958 return I->getOperand(1);
959
960 // If all of the potentially set bits on one side are known to be set on
961 // the other side, just use the 'other' side.
962 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
963 (DemandedMask & (~RHSKnownZero)))
964 return I->getOperand(0);
965 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
966 (DemandedMask & (~LHSKnownZero)))
967 return I->getOperand(1);
968 }
969
Chris Lattner4598c942009-01-31 08:24:16 +0000970 // Compute the KnownZero/KnownOne bits to simplify things downstream.
971 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
972 return 0;
973 }
974
975 // If this is the root being simplified, allow it to have multiple uses,
976 // just set the DemandedMask to all bits so that we can try to simplify the
977 // operands. This allows visitTruncInst (for example) to simplify the
978 // operand of a trunc without duplicating all the logic below.
979 if (Depth == 0 && !V->hasOneUse())
980 DemandedMask = APInt::getAllOnesValue(BitWidth);
981
Reid Spencer8cb68342007-03-12 17:25:59 +0000982 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000983 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000985 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000986 case Instruction::And:
987 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000991 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I;
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000995
996 // If all of the demanded bits are known 1 on one side, return the other.
997 // These bits cannot contribute to the result of the 'and'.
998 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
999 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001001 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1002 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001003 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001004
1005 // If all of the demanded bits in the inputs are known zeros, return zero.
1006 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001007 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +00001008
1009 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001010 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001012
1013 // Output known-1 bits are only known if set in both the LHS & RHS.
1014 RHSKnownOne &= LHSKnownOne;
1015 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1016 RHSKnownZero |= LHSKnownZero;
1017 break;
1018 case Instruction::Or:
1019 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1021 RHSKnownZero, RHSKnownOne, Depth+1) ||
1022 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001023 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001024 return I;
1025 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1026 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001027
1028 // If all of the demanded bits are known zero on one side, return the other.
1029 // These bits cannot contribute to the result of the 'or'.
1030 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1031 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001032 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001033 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1034 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001035 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001036
1037 // If all of the potentially set bits on one side are known to be set on
1038 // the other side, just use the 'other' side.
1039 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1040 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001042 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1043 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001044 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001045
1046 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001047 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001048 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001049
1050 // Output known-0 bits are only known if clear in both the LHS & RHS.
1051 RHSKnownZero &= LHSKnownZero;
1052 // Output known-1 are known to be set if set in either the LHS | RHS.
1053 RHSKnownOne |= LHSKnownOne;
1054 break;
1055 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001056 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1057 RHSKnownZero, RHSKnownOne, Depth+1) ||
1058 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001059 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 return I;
1061 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1062 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001063
1064 // If all of the demanded bits are known zero on one side, return the other.
1065 // These bits cannot contribute to the result of the 'xor'.
1066 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001068 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001070
1071 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1072 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1073 (RHSKnownOne & LHSKnownOne);
1074 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1075 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1076 (RHSKnownOne & LHSKnownZero);
1077
1078 // If all of the demanded bits are known to be zero on one side or the
1079 // other, turn this into an *inclusive* or.
1080 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001081 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1082 Instruction *Or =
1083 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1084 I->getName());
1085 return InsertNewInstBefore(Or, *I);
1086 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001087
1088 // If all of the demanded bits on one side are known, and all of the set
1089 // bits on that side are also known to be set on the other side, turn this
1090 // into an AND, as we know the bits will be cleared.
1091 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1092 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1093 // all known
1094 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001095 Constant *AndC = Constant::getIntegerValue(VTy,
1096 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001097 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001098 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001099 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001100 }
1101 }
1102
1103 // If the RHS is a constant, see if we can simplify it.
1104 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001105 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001106 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001107
Chris Lattnerd0883142009-10-11 22:22:13 +00001108 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1109 // are flipping are known to be set, then the xor is just resetting those
1110 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1111 // simplifying both of them.
1112 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1113 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1114 isa<ConstantInt>(I->getOperand(1)) &&
1115 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1116 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1117 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1118 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1119 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1120
1121 Constant *AndC =
1122 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1123 Instruction *NewAnd =
1124 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1125 InsertNewInstBefore(NewAnd, *I);
1126
1127 Constant *XorC =
1128 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1129 Instruction *NewXor =
1130 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1131 return InsertNewInstBefore(NewXor, *I);
1132 }
1133
1134
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 RHSKnownZero = KnownZeroOut;
1136 RHSKnownOne = KnownOneOut;
1137 break;
1138 }
1139 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001140 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1141 RHSKnownZero, RHSKnownOne, Depth+1) ||
1142 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001143 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001144 return I;
1145 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1146 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001147
1148 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001149 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1150 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001151 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001152
1153 // Only known if known in both the LHS and RHS.
1154 RHSKnownOne &= LHSKnownOne;
1155 RHSKnownZero &= LHSKnownZero;
1156 break;
1157 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001158 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001159 DemandedMask.zext(truncBf);
1160 RHSKnownZero.zext(truncBf);
1161 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001163 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001164 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 DemandedMask.trunc(BitWidth);
1166 RHSKnownZero.trunc(BitWidth);
1167 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001168 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001169 break;
1170 }
1171 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001172 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001174
1175 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1176 if (const VectorType *SrcVTy =
1177 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1178 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1179 // Don't touch a bitcast between vectors of different element counts.
1180 return false;
1181 } else
1182 // Don't touch a scalar-to-vector bitcast.
1183 return false;
1184 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1185 // Don't touch a vector-to-scalar bitcast.
1186 return false;
1187
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 return I;
1191 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001192 break;
1193 case Instruction::ZExt: {
1194 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001195 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001196
Zhou Shengd48653a2007-03-29 04:45:55 +00001197 DemandedMask.trunc(SrcBitWidth);
1198 RHSKnownZero.trunc(SrcBitWidth);
1199 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001201 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001202 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001203 DemandedMask.zext(BitWidth);
1204 RHSKnownZero.zext(BitWidth);
1205 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001206 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001207 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001208 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 break;
1210 }
1211 case Instruction::SExt: {
1212 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001213 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
Reid Spencer8cb68342007-03-12 17:25:59 +00001215 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001216 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001217
Zhou Sheng01542f32007-03-29 02:26:30 +00001218 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001219 // If any of the sign extended bits are demanded, we know that the sign
1220 // bit is demanded.
1221 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001222 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001223
Zhou Shengd48653a2007-03-29 04:45:55 +00001224 InputDemandedBits.trunc(SrcBitWidth);
1225 RHSKnownZero.trunc(SrcBitWidth);
1226 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001227 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001230 InputDemandedBits.zext(BitWidth);
1231 RHSKnownZero.zext(BitWidth);
1232 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001233 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001234
1235 // If the sign bit of the input is known set or clear, then we know the
1236 // top bits of the result.
1237
1238 // If the input sign bit is known zero, or if the NewBits are not demanded
1239 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1243 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001246 }
1247 break;
1248 }
1249 case Instruction::Add: {
1250 // Figure out what the input bits are. If the top bits of the and result
1251 // are not demanded, then the add doesn't demand them from its input
1252 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001253 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001254
1255 // If there is a constant on the RHS, there are a variety of xformations
1256 // we can do.
1257 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258 // If null, this should be simplified elsewhere. Some of the xforms here
1259 // won't work if the RHS is zero.
1260 if (RHS->isZero())
1261 break;
1262
1263 // If the top bit of the output is demanded, demand everything from the
1264 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001265 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001266
1267 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001271
1272 // If the RHS of the add has bits set that can't affect the input, reduce
1273 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001274 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001275 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001276
1277 // Avoid excess work.
1278 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1279 break;
1280
1281 // Turn it into OR if input bits are zero.
1282 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1283 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001284 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001286 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 }
1288
1289 // We can say something about the output known-zero and known-one bits,
1290 // depending on potential carries from the input constant and the
1291 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1292 // bits set and the RHS constant is 0x01001, then we know we have a known
1293 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1294
1295 // To compute this, we first compute the potential carry bits. These are
1296 // the bits which may be modified. I'm not aware of a better way to do
1297 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001298 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001299 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001300
1301 // Now that we know which bits have carries, compute the known-1/0 sets.
1302
1303 // Bits are known one if they are known zero in one operand and one in the
1304 // other, and there is no input carry.
1305 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1306 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1307
1308 // Bits are known zero if they are known zero in both operands and there
1309 // is no input carry.
1310 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1311 } else {
1312 // If the high-bits of this ADD are not demanded, then it does not demand
1313 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001314 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Right fill the mask of bits for this ADD to demand the most
1316 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001317 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001318 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319 LHSKnownZero, LHSKnownOne, Depth+1) ||
1320 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001323 }
1324 }
1325 break;
1326 }
1327 case Instruction::Sub:
1328 // If the high-bits of this SUB are not demanded, then it does not demand
1329 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001330 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001331 // Right fill the mask of bits for this SUB to demand the most
1332 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001333 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001334 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1336 LHSKnownZero, LHSKnownOne, Depth+1) ||
1337 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001338 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001341 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1342 // the known zeros and ones.
1343 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 break;
1345 case Instruction::Shl:
1346 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001347 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001348 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001349 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001351 return I;
1352 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001353 RHSKnownZero <<= ShiftAmt;
1354 RHSKnownOne <<= ShiftAmt;
1355 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001356 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001357 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001358 }
1359 break;
1360 case Instruction::LShr:
1361 // For a logical shift right
1362 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001363 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001364
Reid Spencer8cb68342007-03-12 17:25:59 +00001365 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001366 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001368 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001369 return I;
1370 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001371 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1372 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001373 if (ShiftAmt) {
1374 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001375 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001376 RHSKnownZero |= HighBits; // high bits known zero.
1377 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001378 }
1379 break;
1380 case Instruction::AShr:
1381 // If this is an arithmetic shift right and only the low-bit is set, we can
1382 // always convert this into a logical shr, even if the shift amount is
1383 // variable. The low bit of the shift cannot be an input sign bit unless
1384 // the shift amount is >= the size of the datatype, which is undefined.
1385 if (DemandedMask == 1) {
1386 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001387 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001388 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001389 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001391
1392 // If the sign bit is the only bit demanded by this ashr, then there is no
1393 // need to do it, the shift doesn't change the high bit.
1394 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001395 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001396
1397 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001398 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001399
Reid Spencer8cb68342007-03-12 17:25:59 +00001400 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001401 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001402 // If any of the "high bits" are demanded, we should set the sign bit as
1403 // demanded.
1404 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1405 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001406 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001407 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001408 return I;
1409 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001411 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001412 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1413 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1414
1415 // Handle the sign bits.
1416 APInt SignBit(APInt::getSignBit(BitWidth));
1417 // Adjust to where it is now in the mask.
1418 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1419
1420 // If the input sign bit is known to be zero, or if none of the top bits
1421 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001422 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001423 (HighBits & ~DemandedMask) == HighBits) {
1424 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001425 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001426 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001427 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001428 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1429 RHSKnownOne |= HighBits;
1430 }
1431 }
1432 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001433 case Instruction::SRem:
1434 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001435 APInt RA = Rem->getValue().abs();
1436 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001437 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001438 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001439
Nick Lewycky8e394322008-11-02 02:41:50 +00001440 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001441 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001442 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001443 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001444 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001445
1446 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1447 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001448
1449 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001450
Chris Lattner886ab6c2009-01-31 08:15:18 +00001451 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001452 }
1453 }
1454 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001455 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001456 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1457 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001458 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1459 KnownZero2, KnownOne2, Depth+1) ||
1460 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001461 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001462 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001463
Chris Lattner455e9ab2009-01-21 18:09:24 +00001464 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001465 Leaders = std::max(Leaders,
1466 KnownZero2.countLeadingOnes());
1467 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001468 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001469 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001470 case Instruction::Call:
1471 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1472 switch (II->getIntrinsicID()) {
1473 default: break;
1474 case Intrinsic::bswap: {
1475 // If the only bits demanded come from one byte of the bswap result,
1476 // just shift the input byte into position to eliminate the bswap.
1477 unsigned NLZ = DemandedMask.countLeadingZeros();
1478 unsigned NTZ = DemandedMask.countTrailingZeros();
1479
1480 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1481 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1482 // have 14 leading zeros, round to 8.
1483 NLZ &= ~7;
1484 NTZ &= ~7;
1485 // If we need exactly one byte, we can do this transformation.
1486 if (BitWidth-NLZ-NTZ == 8) {
1487 unsigned ResultBit = NTZ;
1488 unsigned InputBit = BitWidth-NTZ-8;
1489
1490 // Replace this with either a left or right shift to get the byte into
1491 // the right place.
1492 Instruction *NewVal;
1493 if (InputBit > ResultBit)
1494 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001495 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001496 else
1497 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001498 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001499 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001500 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001501 }
1502
1503 // TODO: Could compute known zero/one bits based on the input.
1504 break;
1505 }
1506 }
1507 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001508 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001509 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001510 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001511
1512 // If the client is only demanding bits that we know, return the known
1513 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001514 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1515 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001516 return false;
1517}
1518
Chris Lattner867b99f2006-10-05 06:55:50 +00001519
Mon P Wangaeb06d22008-11-10 04:46:22 +00001520/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001521/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001522/// actually used by the caller. This method analyzes which elements of the
1523/// operand are undef and returns that information in UndefElts.
1524///
1525/// If the information about demanded elements can be used to simplify the
1526/// operation, the operation is simplified, then the resultant value is
1527/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001528Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1529 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001530 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001531 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001532 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001533 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001534
1535 if (isa<UndefValue>(V)) {
1536 // If the entire vector is undefined, just return this info.
1537 UndefElts = EltMask;
1538 return 0;
1539 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1540 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001541 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001542 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001543
Chris Lattner867b99f2006-10-05 06:55:50 +00001544 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001545 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1546 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001547 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001548
1549 std::vector<Constant*> Elts;
1550 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001551 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001552 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001553 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001554 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1555 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001556 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001557 } else { // Otherwise, defined.
1558 Elts.push_back(CP->getOperand(i));
1559 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001560
Chris Lattner867b99f2006-10-05 06:55:50 +00001561 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001562 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001563 return NewCP != CP ? NewCP : 0;
1564 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001565 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001566 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001567
1568 // Check if this is identity. If so, return 0 since we are not simplifying
1569 // anything.
1570 if (DemandedElts == ((1ULL << VWidth) -1))
1571 return 0;
1572
Reid Spencer9d6565a2007-02-15 02:26:10 +00001573 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001574 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001575 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001576 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001577 for (unsigned i = 0; i != VWidth; ++i) {
1578 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1579 Elts.push_back(Elt);
1580 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001581 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001582 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001583 }
1584
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585 // Limit search depth.
1586 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001587 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588
1589 // If multiple users are using the root value, procede with
1590 // simplification conservatively assuming that all elements
1591 // are needed.
1592 if (!V->hasOneUse()) {
1593 // Quit if we find multiple users of a non-root value though.
1594 // They'll be handled when it's their turn to be visited by
1595 // the main instcombine process.
1596 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001598 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001599
1600 // Conservatively assume that all elements are needed.
1601 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001602 }
1603
1604 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001605 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001606
1607 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001608 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001609 Value *TmpV;
1610 switch (I->getOpcode()) {
1611 default: break;
1612
1613 case Instruction::InsertElement: {
1614 // If this is a variable index, we don't know which element it overwrites.
1615 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001616 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001617 if (Idx == 0) {
1618 // Note that we can't propagate undef elt info, because we don't know
1619 // which elt is getting updated.
1620 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1621 UndefElts2, Depth+1);
1622 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1623 break;
1624 }
1625
1626 // If this is inserting an element that isn't demanded, remove this
1627 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001628 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001629 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1630 Worklist.Add(I);
1631 return I->getOperand(0);
1632 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001633
1634 // Otherwise, the element inserted overwrites whatever was there, so the
1635 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001636 APInt DemandedElts2 = DemandedElts;
1637 DemandedElts2.clear(IdxNo);
1638 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001639 UndefElts, Depth+1);
1640 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1641
1642 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001643 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001644 break;
1645 }
1646 case Instruction::ShuffleVector: {
1647 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001648 uint64_t LHSVWidth =
1649 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001650 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001651 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001652 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001653 unsigned MaskVal = Shuffle->getMaskValue(i);
1654 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001655 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001656 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001657 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001658 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001659 else
Evan Cheng388df622009-02-03 10:05:09 +00001660 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001661 }
1662 }
1663 }
1664
Nate Begeman7b254672009-02-11 22:36:25 +00001665 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001666 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001667 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001668 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1669
Nate Begeman7b254672009-02-11 22:36:25 +00001670 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001671 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1672 UndefElts3, Depth+1);
1673 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1674
1675 bool NewUndefElts = false;
1676 for (unsigned i = 0; i < VWidth; i++) {
1677 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001678 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001679 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001680 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001681 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001682 NewUndefElts = true;
1683 UndefElts.set(i);
1684 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001685 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001686 if (UndefElts3[MaskVal - LHSVWidth]) {
1687 NewUndefElts = true;
1688 UndefElts.set(i);
1689 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001690 }
1691 }
1692
1693 if (NewUndefElts) {
1694 // Add additional discovered undefs.
1695 std::vector<Constant*> Elts;
1696 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001697 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001698 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001699 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001700 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001701 Shuffle->getMaskValue(i)));
1702 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001703 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001704 MadeChange = true;
1705 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001706 break;
1707 }
Chris Lattner69878332007-04-14 22:29:23 +00001708 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001709 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001710 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1711 if (!VTy) break;
1712 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001713 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001714 unsigned Ratio;
1715
1716 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001717 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001718 // elements as are demanded of us.
1719 Ratio = 1;
1720 InputDemandedElts = DemandedElts;
1721 } else if (VWidth > InVWidth) {
1722 // Untested so far.
1723 break;
1724
1725 // If there are more elements in the result than there are in the source,
1726 // then an input element is live if any of the corresponding output
1727 // elements are live.
1728 Ratio = VWidth/InVWidth;
1729 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001730 if (DemandedElts[OutIdx])
1731 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001732 }
1733 } else {
1734 // Untested so far.
1735 break;
1736
1737 // If there are more elements in the source than there are in the result,
1738 // then an input element is live if the corresponding output element is
1739 // live.
1740 Ratio = InVWidth/VWidth;
1741 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001742 if (DemandedElts[InIdx/Ratio])
1743 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001744 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001745
Chris Lattner69878332007-04-14 22:29:23 +00001746 // div/rem demand all inputs, because they don't want divide by zero.
1747 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1748 UndefElts2, Depth+1);
1749 if (TmpV) {
1750 I->setOperand(0, TmpV);
1751 MadeChange = true;
1752 }
1753
1754 UndefElts = UndefElts2;
1755 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001756 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001757 // If there are more elements in the result than there are in the source,
1758 // then an output element is undef if the corresponding input element is
1759 // undef.
1760 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001761 if (UndefElts2[OutIdx/Ratio])
1762 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001763 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001764 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001765 // If there are more elements in the source than there are in the result,
1766 // then a result element is undef if all of the corresponding input
1767 // elements are undef.
1768 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1769 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001770 if (!UndefElts2[InIdx]) // Not undef?
1771 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001772 }
1773 break;
1774 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001775 case Instruction::And:
1776 case Instruction::Or:
1777 case Instruction::Xor:
1778 case Instruction::Add:
1779 case Instruction::Sub:
1780 case Instruction::Mul:
1781 // div/rem demand all inputs, because they don't want divide by zero.
1782 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1783 UndefElts, Depth+1);
1784 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1785 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1786 UndefElts2, Depth+1);
1787 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1788
1789 // Output elements are undefined if both are undefined. Consider things
1790 // like undef&0. The result is known zero, not undef.
1791 UndefElts &= UndefElts2;
1792 break;
1793
1794 case Instruction::Call: {
1795 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1796 if (!II) break;
1797 switch (II->getIntrinsicID()) {
1798 default: break;
1799
1800 // Binary vector operations that work column-wise. A dest element is a
1801 // function of the corresponding input elements from the two inputs.
1802 case Intrinsic::x86_sse_sub_ss:
1803 case Intrinsic::x86_sse_mul_ss:
1804 case Intrinsic::x86_sse_min_ss:
1805 case Intrinsic::x86_sse_max_ss:
1806 case Intrinsic::x86_sse2_sub_sd:
1807 case Intrinsic::x86_sse2_mul_sd:
1808 case Intrinsic::x86_sse2_min_sd:
1809 case Intrinsic::x86_sse2_max_sd:
1810 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1811 UndefElts, Depth+1);
1812 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1813 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1814 UndefElts2, Depth+1);
1815 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1816
1817 // If only the low elt is demanded and this is a scalarizable intrinsic,
1818 // scalarize it now.
1819 if (DemandedElts == 1) {
1820 switch (II->getIntrinsicID()) {
1821 default: break;
1822 case Intrinsic::x86_sse_sub_ss:
1823 case Intrinsic::x86_sse_mul_ss:
1824 case Intrinsic::x86_sse2_sub_sd:
1825 case Intrinsic::x86_sse2_mul_sd:
1826 // TODO: Lower MIN/MAX/ABS/etc
1827 Value *LHS = II->getOperand(1);
1828 Value *RHS = II->getOperand(2);
1829 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001830 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001831 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001832 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001833 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001834
1835 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001836 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001837 case Intrinsic::x86_sse_sub_ss:
1838 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001839 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001840 II->getName()), *II);
1841 break;
1842 case Intrinsic::x86_sse_mul_ss:
1843 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001844 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001845 II->getName()), *II);
1846 break;
1847 }
1848
1849 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001850 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001851 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001852 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001853 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001854 return New;
1855 }
1856 }
1857
1858 // Output elements are undefined if both are undefined. Consider things
1859 // like undef&0. The result is known zero, not undef.
1860 UndefElts &= UndefElts2;
1861 break;
1862 }
1863 break;
1864 }
1865 }
1866 return MadeChange ? I : 0;
1867}
1868
Dan Gohman45b4e482008-05-19 22:14:15 +00001869
Chris Lattner564a7272003-08-13 19:01:45 +00001870/// AssociativeOpt - Perform an optimization on an associative operator. This
1871/// function is designed to check a chain of associative operators for a
1872/// potential to apply a certain optimization. Since the optimization may be
1873/// applicable if the expression was reassociated, this checks the chain, then
1874/// reassociates the expression as necessary to expose the optimization
1875/// opportunity. This makes use of a special Functor, which must define
1876/// 'shouldApply' and 'apply' methods.
1877///
1878template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001879static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001880 unsigned Opcode = Root.getOpcode();
1881 Value *LHS = Root.getOperand(0);
1882
1883 // Quick check, see if the immediate LHS matches...
1884 if (F.shouldApply(LHS))
1885 return F.apply(Root);
1886
1887 // Otherwise, if the LHS is not of the same opcode as the root, return.
1888 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001889 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001890 // Should we apply this transform to the RHS?
1891 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1892
1893 // If not to the RHS, check to see if we should apply to the LHS...
1894 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1895 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1896 ShouldApply = true;
1897 }
1898
1899 // If the functor wants to apply the optimization to the RHS of LHSI,
1900 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1901 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001902 // Now all of the instructions are in the current basic block, go ahead
1903 // and perform the reassociation.
1904 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1905
1906 // First move the selected RHS to the LHS of the root...
1907 Root.setOperand(0, LHSI->getOperand(1));
1908
1909 // Make what used to be the LHS of the root be the user of the root...
1910 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001911 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001912 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001913 return 0;
1914 }
Chris Lattner65725312004-04-16 18:08:07 +00001915 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001916 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001917 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001918 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001919 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001920
1921 // Now propagate the ExtraOperand down the chain of instructions until we
1922 // get to LHSI.
1923 while (TmpLHSI != LHSI) {
1924 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001925 // Move the instruction to immediately before the chain we are
1926 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001927 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001928 ARI = NextLHSI;
1929
Chris Lattner564a7272003-08-13 19:01:45 +00001930 Value *NextOp = NextLHSI->getOperand(1);
1931 NextLHSI->setOperand(1, ExtraOperand);
1932 TmpLHSI = NextLHSI;
1933 ExtraOperand = NextOp;
1934 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001935
Chris Lattner564a7272003-08-13 19:01:45 +00001936 // Now that the instructions are reassociated, have the functor perform
1937 // the transformation...
1938 return F.apply(Root);
1939 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001940
Chris Lattner564a7272003-08-13 19:01:45 +00001941 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1942 }
1943 return 0;
1944}
1945
Dan Gohman844731a2008-05-13 00:00:25 +00001946namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001947
Nick Lewycky02d639f2008-05-23 04:34:58 +00001948// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001949struct AddRHS {
1950 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001951 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001952 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1953 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001954 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001955 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001956 }
1957};
1958
1959// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1960// iff C1&C2 == 0
1961struct AddMaskingAnd {
1962 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001963 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001964 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001965 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001966 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001967 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001968 }
1969 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001970 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001971 }
1972};
1973
Dan Gohman844731a2008-05-13 00:00:25 +00001974}
1975
Chris Lattner6e7ba452005-01-01 16:22:27 +00001976static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001977 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001978 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001979 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001980
Chris Lattner2eefe512004-04-09 19:05:30 +00001981 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001982 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1983 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001984
Chris Lattner2eefe512004-04-09 19:05:30 +00001985 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1986 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001987 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1988 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001989 }
1990
1991 Value *Op0 = SO, *Op1 = ConstOperand;
1992 if (!ConstIsRHS)
1993 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001994
Chris Lattner6e7ba452005-01-01 16:22:27 +00001995 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001996 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1997 SO->getName()+".op");
1998 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1999 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2000 SO->getName()+".cmp");
2001 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2002 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2003 SO->getName()+".cmp");
2004 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00002005}
2006
2007// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2008// constant as the other operand, try to fold the binary operator into the
2009// select arguments. This also works for Cast instructions, which obviously do
2010// not have a second operand.
2011static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2012 InstCombiner *IC) {
2013 // Don't modify shared select instructions
2014 if (!SI->hasOneUse()) return 0;
2015 Value *TV = SI->getOperand(1);
2016 Value *FV = SI->getOperand(2);
2017
2018 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002019 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002020 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002021
Chris Lattner6e7ba452005-01-01 16:22:27 +00002022 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2023 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2024
Gabor Greif051a9502008-04-06 20:25:17 +00002025 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2026 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002027 }
2028 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002029}
2030
Chris Lattner4e998b22004-09-29 05:07:12 +00002031
Chris Lattner5d1704d2009-09-27 19:57:57 +00002032/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2033/// has a PHI node as operand #0, see if we can fold the instruction into the
2034/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002035///
2036/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2037/// that would normally be unprofitable because they strongly encourage jump
2038/// threading.
2039Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2040 bool AllowAggressive) {
2041 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002042 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002043 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002044 if (NumPHIValues == 0 ||
2045 // We normally only transform phis with a single use, unless we're trying
2046 // hard to make jump threading happen.
2047 (!PN->hasOneUse() && !AllowAggressive))
2048 return 0;
2049
2050
Chris Lattner5d1704d2009-09-27 19:57:57 +00002051 // Check to see if all of the operands of the PHI are simple constants
2052 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002053 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2054 // bail out. We don't do arbitrary constant expressions here because moving
2055 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002056 BasicBlock *NonConstBB = 0;
2057 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002058 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2059 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002060 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002061 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002062 NonConstBB = PN->getIncomingBlock(i);
2063
2064 // If the incoming non-constant value is in I's block, we have an infinite
2065 // loop.
2066 if (NonConstBB == I.getParent())
2067 return 0;
2068 }
2069
2070 // If there is exactly one non-constant value, we can insert a copy of the
2071 // operation in that block. However, if this is a critical edge, we would be
2072 // inserting the computation one some other paths (e.g. inside a loop). Only
2073 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002074 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002075 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2076 if (!BI || !BI->isUnconditional()) return 0;
2077 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002078
2079 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002080 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002081 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002082 InsertNewInstBefore(NewPN, *PN);
2083 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002084
2085 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002086 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2087 // We only currently try to fold the condition of a select when it is a phi,
2088 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002089 Value *TrueV = SI->getTrueValue();
2090 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002091 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002092 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002093 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002094 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2095 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002096 Value *InV = 0;
2097 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002098 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002099 } else {
2100 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002101 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2102 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002103 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002104 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002105 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002106 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002107 }
2108 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002109 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002110 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002111 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002112 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002113 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002114 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002115 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002116 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002117 } else {
2118 assert(PN->getIncomingBlock(i) == NonConstBB);
2119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002120 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002121 PN->getIncomingValue(i), C, "phitmp",
2122 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002123 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002124 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002125 CI->getPredicate(),
2126 PN->getIncomingValue(i), C, "phitmp",
2127 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002128 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002129 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002130
2131 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002132 }
2133 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002134 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002135 } else {
2136 CastInst *CI = cast<CastInst>(&I);
2137 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002138 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002139 Value *InV;
2140 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002141 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002142 } else {
2143 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002144 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002145 I.getType(), "phitmp",
2146 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002147 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002148 }
2149 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002150 }
2151 }
2152 return ReplaceInstUsesWith(I, NewPN);
2153}
2154
Chris Lattner2454a2e2008-01-29 06:52:45 +00002155
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002156/// WillNotOverflowSignedAdd - Return true if we can prove that:
2157/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2158/// This basically requires proving that the add in the original type would not
2159/// overflow to change the sign bit or have a carry out.
2160bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2161 // There are different heuristics we can use for this. Here are some simple
2162 // ones.
2163
2164 // Add has the property that adding any two 2's complement numbers can only
2165 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002166 // have at least two sign bits, we know that the addition of the two values
2167 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002168 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2169 return true;
2170
2171
2172 // If one of the operands only has one non-zero bit, and if the other operand
2173 // has a known-zero bit in a more significant place than it (not including the
2174 // sign bit) the ripple may go up to and fill the zero, but won't change the
2175 // sign. For example, (X & ~4) + 1.
2176
2177 // TODO: Implement.
2178
2179 return false;
2180}
2181
Chris Lattner2454a2e2008-01-29 06:52:45 +00002182
Chris Lattner7e708292002-06-25 16:13:24 +00002183Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002184 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002185 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002186
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002187 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2188 I.hasNoUnsignedWrap(), TD))
2189 return ReplaceInstUsesWith(I, V);
2190
2191
Chris Lattner66331a42004-04-10 22:01:55 +00002192 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002193 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002194 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002195 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002196 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002197 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002198 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002199
2200 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2201 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002202 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002203 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002204
Eli Friedman709b33d2009-07-13 22:27:52 +00002205 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002206 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002207 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002208 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002209 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002210
2211 if (isa<PHINode>(LHS))
2212 if (Instruction *NV = FoldOpIntoPhi(I))
2213 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002214
Chris Lattner4f637d42006-01-06 17:59:59 +00002215 ConstantInt *XorRHS = 0;
2216 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002217 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002218 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002219 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002220 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002221
Zhou Sheng4351c642007-04-02 08:20:41 +00002222 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002223 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2224 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002225 do {
2226 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002227 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2228 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002229 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2230 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002231 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002232 if (!MaskedValueIsZero(XorLHS,
2233 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002234 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002235 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002236 }
2237 }
2238 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002239 C0080Val = APIntOps::lshr(C0080Val, Size);
2240 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2241 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002242
Reid Spencer35c38852007-03-28 01:36:16 +00002243 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002244 // with funny bit widths then this switch statement should be removed. It
2245 // is just here to get the size of the "middle" type back up to something
2246 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002247 const Type *MiddleType = 0;
2248 switch (Size) {
2249 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002250 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2251 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2252 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002253 }
2254 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002255 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002256 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002257 }
2258 }
Chris Lattner66331a42004-04-10 22:01:55 +00002259 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002260
Owen Anderson1d0be152009-08-13 21:58:54 +00002261 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002262 return BinaryOperator::CreateXor(LHS, RHS);
2263
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002264 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002265 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002266 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002267 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002268
2269 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2270 if (RHSI->getOpcode() == Instruction::Sub)
2271 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2272 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2273 }
2274 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2275 if (LHSI->getOpcode() == Instruction::Sub)
2276 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2277 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2278 }
Robert Bocchino71698282004-07-27 21:02:21 +00002279 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002280
Chris Lattner5c4afb92002-05-08 22:46:53 +00002281 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002282 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002283 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002284 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002285 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002286 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002287 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002288 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002289 }
2290
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002291 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002292 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002293
2294 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002295 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002296 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002297 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002298
Misha Brukmanfd939082005-04-21 23:48:37 +00002299
Chris Lattner50af16a2004-11-13 19:50:12 +00002300 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002301 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002302 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002303 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002304
2305 // X*C1 + X*C2 --> X * (C1+C2)
2306 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002307 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002308 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002309 }
2310
2311 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002312 if (dyn_castFoldableMul(RHS, C2) == LHS)
2313 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002314
Chris Lattnere617c9e2007-01-05 02:17:46 +00002315 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002316 if (dyn_castNotVal(LHS) == RHS ||
2317 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002318 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002319
Chris Lattnerad3448c2003-02-18 19:57:07 +00002320
Chris Lattner564a7272003-08-13 19:01:45 +00002321 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002322 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2323 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002324 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002325
2326 // A+B --> A|B iff A and B have no bits set in common.
2327 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2328 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2329 APInt LHSKnownOne(IT->getBitWidth(), 0);
2330 APInt LHSKnownZero(IT->getBitWidth(), 0);
2331 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2332 if (LHSKnownZero != 0) {
2333 APInt RHSKnownOne(IT->getBitWidth(), 0);
2334 APInt RHSKnownZero(IT->getBitWidth(), 0);
2335 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2336
2337 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002338 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002339 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002340 }
2341 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002342
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002343 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002344 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002345 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002346 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2347 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002348 if (W != Y) {
2349 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002350 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002351 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002352 std::swap(W, X);
2353 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002354 std::swap(Y, Z);
2355 std::swap(W, X);
2356 }
2357 }
2358
2359 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002360 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002361 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002362 }
2363 }
2364 }
2365
Chris Lattner6b032052003-10-02 15:11:26 +00002366 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002367 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002368 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002369 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002370
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002371 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002372 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002373 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002374 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002375 if (Anded == CRHS) {
2376 // See if all bits from the first bit set in the Add RHS up are included
2377 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002378 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002379
2380 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002381 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002382
2383 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002384 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002385
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002386 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2387 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002388 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002389 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002390 }
2391 }
2392 }
2393
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002394 // Try to fold constant add into select arguments.
2395 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002397 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002398 }
2399
Chris Lattner42790482007-12-20 01:56:58 +00002400 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002401 {
2402 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002403 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002404 if (!SI) {
2405 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002406 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002407 }
Chris Lattner42790482007-12-20 01:56:58 +00002408 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002409 Value *TV = SI->getTrueValue();
2410 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002411 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002412
2413 // Can we fold the add into the argument of the select?
2414 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002415 if (match(FV, m_Zero()) &&
2416 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002417 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002418 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002419 if (match(TV, m_Zero()) &&
2420 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002421 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002422 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002423 }
2424 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002425
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002426 // Check for (add (sext x), y), see if we can merge this into an
2427 // integer add followed by a sext.
2428 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2429 // (add (sext x), cst) --> (sext (add x, cst'))
2430 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2431 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002432 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002433 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002434 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002435 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2436 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002437 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2438 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002439 return new SExtInst(NewAdd, I.getType());
2440 }
2441 }
2442
2443 // (add (sext x), (sext y)) --> (sext (add int x, y))
2444 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2445 // Only do this if x/y have the same type, if at last one of them has a
2446 // single use (so we don't increase the number of sexts), and if the
2447 // integer add will not overflow.
2448 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2449 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2450 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2451 RHSConv->getOperand(0))) {
2452 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002453 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2454 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002455 return new SExtInst(NewAdd, I.getType());
2456 }
2457 }
2458 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002459
2460 return Changed ? &I : 0;
2461}
2462
2463Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2464 bool Changed = SimplifyCommutative(I);
2465 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2466
2467 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2468 // X + 0 --> X
2469 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002470 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002471 (I.getType())->getValueAPF()))
2472 return ReplaceInstUsesWith(I, LHS);
2473 }
2474
2475 if (isa<PHINode>(LHS))
2476 if (Instruction *NV = FoldOpIntoPhi(I))
2477 return NV;
2478 }
2479
2480 // -A + B --> B - A
2481 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002482 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002483 return BinaryOperator::CreateFSub(RHS, LHSV);
2484
2485 // A + -B --> A - B
2486 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002487 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002488 return BinaryOperator::CreateFSub(LHS, V);
2489
2490 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2491 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2492 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2493 return ReplaceInstUsesWith(I, LHS);
2494
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002495 // Check for (add double (sitofp x), y), see if we can merge this into an
2496 // integer add followed by a promotion.
2497 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2498 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2499 // ... if the constant fits in the integer value. This is useful for things
2500 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2501 // requires a constant pool load, and generally allows the add to be better
2502 // instcombined.
2503 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2504 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002505 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002506 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002507 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002508 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2509 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002510 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2511 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002512 return new SIToFPInst(NewAdd, I.getType());
2513 }
2514 }
2515
2516 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2517 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2518 // Only do this if x/y have the same type, if at last one of them has a
2519 // single use (so we don't increase the number of int->fp conversions),
2520 // and if the integer add will not overflow.
2521 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2522 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2523 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2524 RHSConv->getOperand(0))) {
2525 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002526 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002527 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002528 return new SIToFPInst(NewAdd, I.getType());
2529 }
2530 }
2531 }
2532
Chris Lattner7e708292002-06-25 16:13:24 +00002533 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002534}
2535
Chris Lattner092543c2009-11-04 08:05:20 +00002536
2537/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2538/// code necessary to compute the offset from the base pointer (without adding
2539/// in the base pointer). Return the result as a signed integer of intptr size.
2540static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2541 TargetData &TD = *IC.getTargetData();
2542 gep_type_iterator GTI = gep_type_begin(GEP);
2543 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2544 Value *Result = Constant::getNullValue(IntPtrTy);
2545
2546 // Build a mask for high order bits.
2547 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2548 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2549
2550 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2551 ++i, ++GTI) {
2552 Value *Op = *i;
2553 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2554 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2555 if (OpC->isZero()) continue;
2556
2557 // Handle a struct index, which adds its field offset to the pointer.
2558 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2559 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2560
2561 Result = IC.Builder->CreateAdd(Result,
2562 ConstantInt::get(IntPtrTy, Size),
2563 GEP->getName()+".offs");
2564 continue;
2565 }
2566
2567 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2568 Constant *OC =
2569 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2570 Scale = ConstantExpr::getMul(OC, Scale);
2571 // Emit an add instruction.
2572 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2573 continue;
2574 }
2575 // Convert to correct type.
2576 if (Op->getType() != IntPtrTy)
2577 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2578 if (Size != 1) {
2579 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2580 // We'll let instcombine(mul) convert this to a shl if possible.
2581 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2582 }
2583
2584 // Emit an add instruction.
2585 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2586 }
2587 return Result;
2588}
2589
2590
2591/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2592/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2593/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2594/// be complex, and scales are involved. The above expression would also be
2595/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2596/// This later form is less amenable to optimization though, and we are allowed
2597/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2598///
2599/// If we can't emit an optimized form for this expression, this returns null.
2600///
2601static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2602 InstCombiner &IC) {
2603 TargetData &TD = *IC.getTargetData();
2604 gep_type_iterator GTI = gep_type_begin(GEP);
2605
2606 // Check to see if this gep only has a single variable index. If so, and if
2607 // any constant indices are a multiple of its scale, then we can compute this
2608 // in terms of the scale of the variable index. For example, if the GEP
2609 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2610 // because the expression will cross zero at the same point.
2611 unsigned i, e = GEP->getNumOperands();
2612 int64_t Offset = 0;
2613 for (i = 1; i != e; ++i, ++GTI) {
2614 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2615 // Compute the aggregate offset of constant indices.
2616 if (CI->isZero()) continue;
2617
2618 // Handle a struct index, which adds its field offset to the pointer.
2619 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2620 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2621 } else {
2622 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2623 Offset += Size*CI->getSExtValue();
2624 }
2625 } else {
2626 // Found our variable index.
2627 break;
2628 }
2629 }
2630
2631 // If there are no variable indices, we must have a constant offset, just
2632 // evaluate it the general way.
2633 if (i == e) return 0;
2634
2635 Value *VariableIdx = GEP->getOperand(i);
2636 // Determine the scale factor of the variable element. For example, this is
2637 // 4 if the variable index is into an array of i32.
2638 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2639
2640 // Verify that there are no other variable indices. If so, emit the hard way.
2641 for (++i, ++GTI; i != e; ++i, ++GTI) {
2642 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2643 if (!CI) return 0;
2644
2645 // Compute the aggregate offset of constant indices.
2646 if (CI->isZero()) continue;
2647
2648 // Handle a struct index, which adds its field offset to the pointer.
2649 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2650 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2651 } else {
2652 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2653 Offset += Size*CI->getSExtValue();
2654 }
2655 }
2656
2657 // Okay, we know we have a single variable index, which must be a
2658 // pointer/array/vector index. If there is no offset, life is simple, return
2659 // the index.
2660 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2661 if (Offset == 0) {
2662 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2663 // we don't need to bother extending: the extension won't affect where the
2664 // computation crosses zero.
2665 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2666 VariableIdx = new TruncInst(VariableIdx,
2667 TD.getIntPtrType(VariableIdx->getContext()),
2668 VariableIdx->getName(), &I);
2669 return VariableIdx;
2670 }
2671
2672 // Otherwise, there is an index. The computation we will do will be modulo
2673 // the pointer size, so get it.
2674 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2675
2676 Offset &= PtrSizeMask;
2677 VariableScale &= PtrSizeMask;
2678
2679 // To do this transformation, any constant index must be a multiple of the
2680 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2681 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2682 // multiple of the variable scale.
2683 int64_t NewOffs = Offset / (int64_t)VariableScale;
2684 if (Offset != NewOffs*(int64_t)VariableScale)
2685 return 0;
2686
2687 // Okay, we can do this evaluation. Start by converting the index to intptr.
2688 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2689 if (VariableIdx->getType() != IntPtrTy)
2690 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2691 true /*SExt*/,
2692 VariableIdx->getName(), &I);
2693 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2694 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2695}
2696
2697
2698/// Optimize pointer differences into the same array into a size. Consider:
2699/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2700/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2701///
2702Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2703 const Type *Ty) {
2704 assert(TD && "Must have target data info for this");
2705
2706 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2707 // this.
2708 bool Swapped;
2709 GetElementPtrInst *GEP;
2710
2711 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2712 GEP->getOperand(0) == RHS)
2713 Swapped = false;
2714 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2715 GEP->getOperand(0) == LHS)
2716 Swapped = true;
2717 else
2718 return 0;
2719
2720 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2721
2722 // Emit the offset of the GEP and an intptr_t.
2723 Value *Result = EmitGEPOffset(GEP, *this);
2724
2725 // If we have p - gep(p, ...) then we have to negate the result.
2726 if (Swapped)
2727 Result = Builder->CreateNeg(Result, "diff.neg");
2728
2729 return Builder->CreateIntCast(Result, Ty, true);
2730}
2731
2732
Chris Lattner7e708292002-06-25 16:13:24 +00002733Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002734 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002735
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002736 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002737 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002738
Chris Lattner092543c2009-11-04 08:05:20 +00002739 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohman186a6362009-08-12 16:04:34 +00002740 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002741 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002742
Chris Lattnere87597f2004-10-16 18:11:37 +00002743 if (isa<UndefValue>(Op0))
2744 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2745 if (isa<UndefValue>(Op1))
2746 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002747 if (I.getType() == Type::getInt1Ty(*Context))
2748 return BinaryOperator::CreateXor(Op0, Op1);
2749
Chris Lattnerd65460f2003-11-05 01:06:05 +00002750 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002751 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002752 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002753 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002754
Chris Lattnerd65460f2003-11-05 01:06:05 +00002755 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002756 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002757 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002758 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002759
Chris Lattner76b7a062007-01-15 07:02:54 +00002760 // -(X >>u 31) -> (X >>s 31)
2761 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002762 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002763 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002764 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002765 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002766 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002767 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002768 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002769 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002770 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002771 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002772 }
2773 }
Chris Lattner092543c2009-11-04 08:05:20 +00002774 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002775 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2776 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002777 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002778 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002779 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002780 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002781 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002782 }
2783 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002784 }
2785 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002786 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002787
2788 // Try to fold constant sub into select arguments.
2789 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002790 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002791 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002792
2793 // C - zext(bool) -> bool ? C - 1 : C
2794 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002795 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002796 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002797 }
2798
Chris Lattner43d84d62005-04-07 16:15:25 +00002799 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002800 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002801 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002802 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002803 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002804 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002805 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002806 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002807 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2808 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2809 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002810 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002811 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002812 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002813 }
2814
Chris Lattnerfd059242003-10-15 16:48:29 +00002815 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002816 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2817 // is not used by anyone else...
2818 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002819 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002820 // Swap the two operands of the subexpr...
2821 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2822 Op1I->setOperand(0, IIOp1);
2823 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002824
Chris Lattnera2881962003-02-18 19:28:33 +00002825 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002826 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002827 }
2828
2829 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2830 //
2831 if (Op1I->getOpcode() == Instruction::And &&
2832 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2833 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2834
Chris Lattner74381062009-08-30 07:44:24 +00002835 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002836 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002837 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002838
Reid Spencerac5209e2006-10-16 23:08:08 +00002839 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002840 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002841 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002842 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002843 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002844 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002845 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002846
Chris Lattnerad3448c2003-02-18 19:57:07 +00002847 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002848 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002849 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002850 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002851 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002852 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002853 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002854 }
Chris Lattner40371712002-05-09 01:29:19 +00002855 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002856 }
Chris Lattnera2881962003-02-18 19:28:33 +00002857
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002858 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2859 if (Op0I->getOpcode() == Instruction::Add) {
2860 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2861 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2862 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2863 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2864 } else if (Op0I->getOpcode() == Instruction::Sub) {
2865 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002866 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002867 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002868 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002869 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002870
Chris Lattner50af16a2004-11-13 19:50:12 +00002871 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002872 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002873 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002874 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002875
Chris Lattner50af16a2004-11-13 19:50:12 +00002876 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002877 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002878 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002879 }
Chris Lattner092543c2009-11-04 08:05:20 +00002880
2881 // Optimize pointer differences into the same array into a size. Consider:
2882 // &A[10] - &A[0]: we should compile this to "10".
2883 if (TD) {
2884 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2885 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2886 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2887 RHS->getOperand(0),
2888 I.getType()))
2889 return ReplaceInstUsesWith(I, Res);
2890
2891 // trunc(p)-trunc(q) -> trunc(p-q)
2892 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2893 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2894 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2895 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2896 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2897 RHS->getOperand(0),
2898 I.getType()))
2899 return ReplaceInstUsesWith(I, Res);
2900 }
2901
Chris Lattner3f5b8772002-05-06 16:14:14 +00002902 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002903}
2904
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002905Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2907
2908 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002909 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002910 return BinaryOperator::CreateFAdd(Op0, V);
2911
2912 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2913 if (Op1I->getOpcode() == Instruction::FAdd) {
2914 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002915 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002916 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002917 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002918 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002919 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002920 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002921 }
2922
2923 return 0;
2924}
2925
Chris Lattnera0141b92007-07-15 20:42:37 +00002926/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2927/// comparison only checks the sign bit. If it only checks the sign bit, set
2928/// TrueIfSigned if the result of the comparison is true when the input value is
2929/// signed.
2930static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2931 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002932 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002933 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2934 TrueIfSigned = true;
2935 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002936 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2937 TrueIfSigned = true;
2938 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002939 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2940 TrueIfSigned = false;
2941 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002942 case ICmpInst::ICMP_UGT:
2943 // True if LHS u> RHS and RHS == high-bit-mask - 1
2944 TrueIfSigned = true;
2945 return RHS->getValue() ==
2946 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2947 case ICmpInst::ICMP_UGE:
2948 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2949 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002950 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002951 default:
2952 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002953 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002954}
2955
Chris Lattner7e708292002-06-25 16:13:24 +00002956Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002957 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002959
Chris Lattnera2498472009-10-11 21:36:10 +00002960 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002961 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002962
Chris Lattner8af304a2009-10-11 07:53:15 +00002963 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002964 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2965 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002966
2967 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002968 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002969 if (SI->getOpcode() == Instruction::Shl)
2970 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002971 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002972 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002973
Zhou Sheng843f07672007-04-19 05:39:12 +00002974 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002975 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002976 if (CI->equalsInt(1)) // X * 1 == X
2977 return ReplaceInstUsesWith(I, Op0);
2978 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002979 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002980
Zhou Sheng97b52c22007-03-29 01:57:21 +00002981 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002982 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002983 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002984 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002985 }
Chris Lattnera2498472009-10-11 21:36:10 +00002986 } else if (isa<VectorType>(Op1C->getType())) {
2987 if (Op1C->isNullValue())
2988 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002989
Chris Lattnera2498472009-10-11 21:36:10 +00002990 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002991 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002992 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002993
2994 // As above, vector X*splat(1.0) -> X in all defined cases.
2995 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002996 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2997 if (CI->equalsInt(1))
2998 return ReplaceInstUsesWith(I, Op0);
2999 }
3000 }
Chris Lattnera2881962003-02-18 19:28:33 +00003001 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003002
3003 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3004 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003005 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003006 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003007 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3008 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003009 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003010
3011 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003012
3013 // Try to fold constant mul into select arguments.
3014 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003015 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003016 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003017
3018 if (isa<PHINode>(Op0))
3019 if (Instruction *NV = FoldOpIntoPhi(I))
3020 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003021 }
3022
Dan Gohman186a6362009-08-12 16:04:34 +00003023 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003024 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003025 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003026
Nick Lewycky0c730792008-11-21 07:33:58 +00003027 // (X / Y) * Y = X - (X % Y)
3028 // (X / Y) * -Y = (X % Y) - X
3029 {
Chris Lattnera2498472009-10-11 21:36:10 +00003030 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003031 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3032 if (!BO ||
3033 (BO->getOpcode() != Instruction::UDiv &&
3034 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003035 Op1C = Op0;
3036 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003037 }
Chris Lattnera2498472009-10-11 21:36:10 +00003038 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003039 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003040 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003041 (BO->getOpcode() == Instruction::UDiv ||
3042 BO->getOpcode() == Instruction::SDiv)) {
3043 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3044
Dan Gohmanfa94b942009-08-12 16:33:09 +00003045 // If the division is exact, X % Y is zero.
3046 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3047 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003048 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003049 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003050 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003051 }
3052
Chris Lattner74381062009-08-30 07:44:24 +00003053 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003054 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003055 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003056 else
Chris Lattner74381062009-08-30 07:44:24 +00003057 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003058 Rem->takeName(BO);
3059
Chris Lattnera2498472009-10-11 21:36:10 +00003060 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003061 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003062 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003063 }
3064 }
3065
Chris Lattner8af304a2009-10-11 07:53:15 +00003066 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003067 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003068 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003069
Chris Lattner8af304a2009-10-11 07:53:15 +00003070 // X*(1 << Y) --> X << Y
3071 // (1 << Y)*X --> X << Y
3072 {
3073 Value *Y;
3074 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003075 return BinaryOperator::CreateShl(Op1, Y);
3076 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003077 return BinaryOperator::CreateShl(Op0, Y);
3078 }
3079
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003080 // If one of the operands of the multiply is a cast from a boolean value, then
3081 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003082 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3083 if (!isa<VectorType>(I.getType())) {
3084 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003085 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003086
Chris Lattnerd2c58362009-10-11 21:29:45 +00003087 Value *BoolCast = 0, *OtherOp = 0;
3088 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003089 BoolCast = Op0, OtherOp = Op1;
3090 else if (MaskedValueIsZero(Op1, Negative2))
3091 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003092
Chris Lattner0036e3a2009-10-11 21:22:21 +00003093 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003094 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3095 BoolCast, "tmp");
3096 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003097 }
3098 }
3099
Chris Lattner7e708292002-06-25 16:13:24 +00003100 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003101}
3102
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003103Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3104 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003106
3107 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003108 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3109 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003110 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3111 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3112 if (Op1F->isExactlyValue(1.0))
3113 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003114 } else if (isa<VectorType>(Op1C->getType())) {
3115 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003116 // As above, vector X*splat(1.0) -> X in all defined cases.
3117 if (Constant *Splat = Op1V->getSplatValue()) {
3118 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3119 if (F->isExactlyValue(1.0))
3120 return ReplaceInstUsesWith(I, Op0);
3121 }
3122 }
3123 }
3124
3125 // Try to fold constant mul into select arguments.
3126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3128 return R;
3129
3130 if (isa<PHINode>(Op0))
3131 if (Instruction *NV = FoldOpIntoPhi(I))
3132 return NV;
3133 }
3134
Dan Gohman186a6362009-08-12 16:04:34 +00003135 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003136 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003137 return BinaryOperator::CreateFMul(Op0v, Op1v);
3138
3139 return Changed ? &I : 0;
3140}
3141
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003142/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3143/// instruction.
3144bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3145 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3146
3147 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3148 int NonNullOperand = -1;
3149 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3150 if (ST->isNullValue())
3151 NonNullOperand = 2;
3152 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3153 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3154 if (ST->isNullValue())
3155 NonNullOperand = 1;
3156
3157 if (NonNullOperand == -1)
3158 return false;
3159
3160 Value *SelectCond = SI->getOperand(0);
3161
3162 // Change the div/rem to use 'Y' instead of the select.
3163 I.setOperand(1, SI->getOperand(NonNullOperand));
3164
3165 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3166 // problem. However, the select, or the condition of the select may have
3167 // multiple uses. Based on our knowledge that the operand must be non-zero,
3168 // propagate the known value for the select into other uses of it, and
3169 // propagate a known value of the condition into its other users.
3170
3171 // If the select and condition only have a single use, don't bother with this,
3172 // early exit.
3173 if (SI->use_empty() && SelectCond->hasOneUse())
3174 return true;
3175
3176 // Scan the current block backward, looking for other uses of SI.
3177 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3178
3179 while (BBI != BBFront) {
3180 --BBI;
3181 // If we found a call to a function, we can't assume it will return, so
3182 // information from below it cannot be propagated above it.
3183 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3184 break;
3185
3186 // Replace uses of the select or its condition with the known values.
3187 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3188 I != E; ++I) {
3189 if (*I == SI) {
3190 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003191 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003192 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003193 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3194 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003195 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003196 }
3197 }
3198
3199 // If we past the instruction, quit looking for it.
3200 if (&*BBI == SI)
3201 SI = 0;
3202 if (&*BBI == SelectCond)
3203 SelectCond = 0;
3204
3205 // If we ran out of things to eliminate, break out of the loop.
3206 if (SelectCond == 0 && SI == 0)
3207 break;
3208
3209 }
3210 return true;
3211}
3212
3213
Reid Spencer1628cec2006-10-26 06:15:43 +00003214/// This function implements the transforms on div instructions that work
3215/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3216/// used by the visitors to those instructions.
3217/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003218Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003220
Chris Lattner50b2ca42008-02-19 06:12:18 +00003221 // undef / X -> 0 for integer.
3222 // undef / X -> undef for FP (the undef could be a snan).
3223 if (isa<UndefValue>(Op0)) {
3224 if (Op0->getType()->isFPOrFPVector())
3225 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003226 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003227 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003228
3229 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003230 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003231 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003232
Reid Spencer1628cec2006-10-26 06:15:43 +00003233 return 0;
3234}
Misha Brukmanfd939082005-04-21 23:48:37 +00003235
Reid Spencer1628cec2006-10-26 06:15:43 +00003236/// This function implements the transforms common to both integer division
3237/// instructions (udiv and sdiv). It is called by the visitors to those integer
3238/// division instructions.
3239/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003240Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003241 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003243 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003244 if (Op0 == Op1) {
3245 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003246 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003247 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003248 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003249 }
3250
Owen Andersoneed707b2009-07-24 23:12:02 +00003251 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003252 return ReplaceInstUsesWith(I, CI);
3253 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003254
Reid Spencer1628cec2006-10-26 06:15:43 +00003255 if (Instruction *Common = commonDivTransforms(I))
3256 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003257
3258 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3259 // This does not apply for fdiv.
3260 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3261 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003262
3263 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3264 // div X, 1 == X
3265 if (RHS->equalsInt(1))
3266 return ReplaceInstUsesWith(I, Op0);
3267
3268 // (X / C1) / C2 -> X / (C1*C2)
3269 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3270 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3271 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003272 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003273 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003274 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003275 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003276 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003277 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003278 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003279
Reid Spencerbca0e382007-03-23 20:05:17 +00003280 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003281 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3282 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3283 return R;
3284 if (isa<PHINode>(Op0))
3285 if (Instruction *NV = FoldOpIntoPhi(I))
3286 return NV;
3287 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003288 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003289
Chris Lattnera2881962003-02-18 19:28:33 +00003290 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003291 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003292 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003294
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003295 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003296 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003297 return ReplaceInstUsesWith(I, Op0);
3298
Nick Lewycky895f0852008-11-27 20:21:08 +00003299 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3300 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3301 // div X, 1 == X
3302 if (X->isOne())
3303 return ReplaceInstUsesWith(I, Op0);
3304 }
3305
Reid Spencer1628cec2006-10-26 06:15:43 +00003306 return 0;
3307}
3308
3309Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3310 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3311
3312 // Handle the integer div common cases
3313 if (Instruction *Common = commonIDivTransforms(I))
3314 return Common;
3315
Reid Spencer1628cec2006-10-26 06:15:43 +00003316 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003317 // X udiv C^2 -> X >> C
3318 // Check to see if this is an unsigned division with an exact power of 2,
3319 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003320 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003321 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003322 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003323
3324 // X udiv C, where C >= signbit
3325 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003326 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003327 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003328 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003329 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003330 }
3331
3332 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003333 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003334 if (RHSI->getOpcode() == Instruction::Shl &&
3335 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003336 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003337 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003338 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003339 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003340 if (uint32_t C2 = C1.logBase2())
3341 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003342 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003343 }
3344 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003345 }
3346
Reid Spencer1628cec2006-10-26 06:15:43 +00003347 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3348 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003349 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003350 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003351 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003352 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003353 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003354 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003355 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003356 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003357 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003358 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003359
3360 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003361 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003362 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003363
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003364 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003365 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003366 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003367 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003368 return 0;
3369}
3370
Reid Spencer1628cec2006-10-26 06:15:43 +00003371Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3372 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3373
3374 // Handle the integer div common cases
3375 if (Instruction *Common = commonIDivTransforms(I))
3376 return Common;
3377
3378 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3379 // sdiv X, -1 == -X
3380 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003381 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003382
Dan Gohmanfa94b942009-08-12 16:33:09 +00003383 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003384 if (cast<SDivOperator>(&I)->isExact() &&
3385 RHS->getValue().isNonNegative() &&
3386 RHS->getValue().isPowerOf2()) {
3387 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3388 RHS->getValue().exactLogBase2());
3389 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3390 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003391
3392 // -X/C --> X/-C provided the negation doesn't overflow.
3393 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3394 if (isa<Constant>(Sub->getOperand(0)) &&
3395 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003396 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003397 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3398 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003399 }
3400
3401 // If the sign bits of both operands are zero (i.e. we can prove they are
3402 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003403 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003404 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003405 if (MaskedValueIsZero(Op0, Mask)) {
3406 if (MaskedValueIsZero(Op1, Mask)) {
3407 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3408 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3409 }
3410 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003411 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003412 ShiftedInt->getValue().isPowerOf2()) {
3413 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3414 // Safe because the only negative value (1 << Y) can take on is
3415 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3416 // the sign bit set.
3417 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3418 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003419 }
Eli Friedman8be17392009-07-18 09:53:21 +00003420 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003421
3422 return 0;
3423}
3424
3425Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426 return commonDivTransforms(I);
3427}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003428
Reid Spencer0a783f72006-11-02 01:53:59 +00003429/// This function implements the transforms on rem instructions that work
3430/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3431/// is used by the visitors to those instructions.
3432/// @brief Transforms common to all three rem instructions
3433Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003434 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003435
Chris Lattner50b2ca42008-02-19 06:12:18 +00003436 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3437 if (I.getType()->isFPOrFPVector())
3438 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003440 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003441 if (isa<UndefValue>(Op1))
3442 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003443
3444 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003445 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3446 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003447
Reid Spencer0a783f72006-11-02 01:53:59 +00003448 return 0;
3449}
3450
3451/// This function implements the transforms common to both integer remainder
3452/// instructions (urem and srem). It is called by the visitors to those integer
3453/// remainder instructions.
3454/// @brief Common integer remainder transforms
3455Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3456 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3457
3458 if (Instruction *common = commonRemTransforms(I))
3459 return common;
3460
Dale Johannesened6af242009-01-21 00:35:19 +00003461 // 0 % X == 0 for integer, we don't need to preserve faults!
3462 if (Constant *LHS = dyn_cast<Constant>(Op0))
3463 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003465
Chris Lattner857e8cd2004-12-12 21:48:58 +00003466 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003467 // X % 0 == undef, we don't need to preserve faults!
3468 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003469 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003470
Chris Lattnera2881962003-02-18 19:28:33 +00003471 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003472 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003473
Chris Lattner97943922006-02-28 05:49:21 +00003474 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3475 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3476 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3477 return R;
3478 } else if (isa<PHINode>(Op0I)) {
3479 if (Instruction *NV = FoldOpIntoPhi(I))
3480 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003481 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003482
3483 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003484 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003485 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003486 }
Chris Lattnera2881962003-02-18 19:28:33 +00003487 }
3488
Reid Spencer0a783f72006-11-02 01:53:59 +00003489 return 0;
3490}
3491
3492Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3494
3495 if (Instruction *common = commonIRemTransforms(I))
3496 return common;
3497
3498 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3499 // X urem C^2 -> X and C
3500 // Check to see if this is an unsigned remainder with an exact power of 2,
3501 // if so, convert to a bitwise and.
3502 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003503 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003504 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003505 }
3506
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003507 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003508 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3509 if (RHSI->getOpcode() == Instruction::Shl &&
3510 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003511 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003512 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003513 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003514 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003515 }
3516 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003517 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003518
Reid Spencer0a783f72006-11-02 01:53:59 +00003519 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3520 // where C1&C2 are powers of two.
3521 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3522 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3523 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3524 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003525 if ((STO->getValue().isPowerOf2()) &&
3526 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003527 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3528 SI->getName()+".t");
3529 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3530 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003531 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003532 }
3533 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003534 }
3535
Chris Lattner3f5b8772002-05-06 16:14:14 +00003536 return 0;
3537}
3538
Reid Spencer0a783f72006-11-02 01:53:59 +00003539Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3541
Dan Gohmancff55092007-11-05 23:16:33 +00003542 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003543 if (Instruction *Common = commonIRemTransforms(I))
3544 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003545
Dan Gohman186a6362009-08-12 16:04:34 +00003546 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003547 if (!isa<Constant>(RHSNeg) ||
3548 (isa<ConstantInt>(RHSNeg) &&
3549 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003550 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003551 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003552 I.setOperand(1, RHSNeg);
3553 return &I;
3554 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003555
Dan Gohmancff55092007-11-05 23:16:33 +00003556 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003557 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003558 if (I.getType()->isInteger()) {
3559 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3560 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3561 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003563 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003564 }
3565
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003566 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003567 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3568 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003569
Nick Lewycky9dce8732008-12-20 16:48:00 +00003570 bool hasNegative = false;
3571 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3572 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3573 if (RHS->getValue().isNegative())
3574 hasNegative = true;
3575
3576 if (hasNegative) {
3577 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003578 for (unsigned i = 0; i != VWidth; ++i) {
3579 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3580 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003581 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003582 else
3583 Elts[i] = RHS;
3584 }
3585 }
3586
Owen Andersonaf7ec972009-07-28 21:19:26 +00003587 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003588 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003589 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003590 I.setOperand(1, NewRHSV);
3591 return &I;
3592 }
3593 }
3594 }
3595
Reid Spencer0a783f72006-11-02 01:53:59 +00003596 return 0;
3597}
3598
3599Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003600 return commonRemTransforms(I);
3601}
3602
Chris Lattner457dd822004-06-09 07:59:58 +00003603// isOneBitSet - Return true if there is exactly one bit set in the specified
3604// constant.
3605static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003606 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003607}
3608
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003609// isHighOnes - Return true if the constant is of the form 1+0+.
3610// This is the same as lowones(~X).
3611static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003612 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003613}
3614
Reid Spencere4d87aa2006-12-23 06:05:41 +00003615/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003616/// are carefully arranged to allow folding of expressions such as:
3617///
3618/// (A < B) | (A > B) --> (A != B)
3619///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003620/// Note that this is only valid if the first and second predicates have the
3621/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003622///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003623/// Three bits are used to represent the condition, as follows:
3624/// 0 A > B
3625/// 1 A == B
3626/// 2 A < B
3627///
3628/// <=> Value Definition
3629/// 000 0 Always false
3630/// 001 1 A > B
3631/// 010 2 A == B
3632/// 011 3 A >= B
3633/// 100 4 A < B
3634/// 101 5 A != B
3635/// 110 6 A <= B
3636/// 111 7 Always true
3637///
3638static unsigned getICmpCode(const ICmpInst *ICI) {
3639 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003640 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641 case ICmpInst::ICMP_UGT: return 1; // 001
3642 case ICmpInst::ICMP_SGT: return 1; // 001
3643 case ICmpInst::ICMP_EQ: return 2; // 010
3644 case ICmpInst::ICMP_UGE: return 3; // 011
3645 case ICmpInst::ICMP_SGE: return 3; // 011
3646 case ICmpInst::ICMP_ULT: return 4; // 100
3647 case ICmpInst::ICMP_SLT: return 4; // 100
3648 case ICmpInst::ICMP_NE: return 5; // 101
3649 case ICmpInst::ICMP_ULE: return 6; // 110
3650 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003651 // True -> 7
3652 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003653 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003654 return 0;
3655 }
3656}
3657
Evan Cheng8db90722008-10-14 17:15:11 +00003658/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3659/// predicate into a three bit mask. It also returns whether it is an ordered
3660/// predicate by reference.
3661static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3662 isOrdered = false;
3663 switch (CC) {
3664 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3665 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003666 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3667 case FCmpInst::FCMP_UGT: return 1; // 001
3668 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3669 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003670 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3671 case FCmpInst::FCMP_UGE: return 3; // 011
3672 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3673 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003674 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3675 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003676 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3677 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003678 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003679 default:
3680 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003681 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003682 return 0;
3683 }
3684}
3685
Reid Spencere4d87aa2006-12-23 06:05:41 +00003686/// getICmpValue - This is the complement of getICmpCode, which turns an
3687/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003688/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003689/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003690static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003691 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003693 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003694 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003695 case 1:
3696 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003697 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003698 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003699 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3700 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003701 case 3:
3702 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003703 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003704 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003705 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 case 4:
3707 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003708 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003710 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3711 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003712 case 6:
3713 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003714 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003715 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003716 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003717 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003718 }
3719}
3720
Evan Cheng8db90722008-10-14 17:15:11 +00003721/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3722/// opcode and two operands into either a FCmp instruction. isordered is passed
3723/// in to determine which kind of predicate to use in the new fcmp instruction.
3724static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003725 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003726 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003727 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003728 case 0:
3729 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003730 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003731 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003732 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003733 case 1:
3734 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003735 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003736 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003737 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003738 case 2:
3739 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003740 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003741 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003742 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003743 case 3:
3744 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003745 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003746 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003747 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003748 case 4:
3749 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003750 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003751 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003752 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003753 case 5:
3754 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003755 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003756 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003757 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003758 case 6:
3759 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003760 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003761 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003762 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003763 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003764 }
3765}
3766
Chris Lattnerb9553d62008-11-16 04:55:20 +00003767/// PredicatesFoldable - Return true if both predicates match sign or if at
3768/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003769static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003770 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3771 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3772 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003773}
3774
3775namespace {
3776// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3777struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003778 InstCombiner &IC;
3779 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003780 ICmpInst::Predicate pred;
3781 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3782 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3783 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003784 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003785 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3786 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003787 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3788 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003789 return false;
3790 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003791 Instruction *apply(Instruction &Log) const {
3792 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3793 if (ICI->getOperand(0) != LHS) {
3794 assert(ICI->getOperand(1) == LHS);
3795 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003796 }
3797
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003798 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003799 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003800 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003801 unsigned Code;
3802 switch (Log.getOpcode()) {
3803 case Instruction::And: Code = LHSCode & RHSCode; break;
3804 case Instruction::Or: Code = LHSCode | RHSCode; break;
3805 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003806 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003807 }
3808
Nick Lewycky4a134af2009-10-25 05:20:17 +00003809 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003810 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003811 if (Instruction *I = dyn_cast<Instruction>(RV))
3812 return I;
3813 // Otherwise, it's a constant boolean value...
3814 return IC.ReplaceInstUsesWith(Log, RV);
3815 }
3816};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003817} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003818
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003819// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3820// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003821// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003822Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003823 ConstantInt *OpRHS,
3824 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003825 BinaryOperator &TheAnd) {
3826 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003827 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003828 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003829 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003830
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003831 switch (Op->getOpcode()) {
3832 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003833 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003834 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003835 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003836 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003837 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003838 }
3839 break;
3840 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003841 if (Together == AndRHS) // (X | C) & C --> C
3842 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003843
Chris Lattner6e7ba452005-01-01 16:22:27 +00003844 if (Op->hasOneUse() && Together != OpRHS) {
3845 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003846 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003847 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003848 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003849 }
3850 break;
3851 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003852 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003853 // Adding a one to a single bit bit-field should be turned into an XOR
3854 // of the bit. First thing to check is to see if this AND is with a
3855 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003856 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003857
3858 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003859 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003860 // Ok, at this point, we know that we are masking the result of the
3861 // ADD down to exactly one bit. If the constant we are adding has
3862 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003863 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003864
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003865 // Check to see if any bits below the one bit set in AndRHSV are set.
3866 if ((AddRHS & (AndRHSV-1)) == 0) {
3867 // If not, the only thing that can effect the output of the AND is
3868 // the bit specified by AndRHSV. If that bit is set, the effect of
3869 // the XOR is to toggle the bit. If it is clear, then the ADD has
3870 // no effect.
3871 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3872 TheAnd.setOperand(0, X);
3873 return &TheAnd;
3874 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003875 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003876 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003877 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003878 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003879 }
3880 }
3881 }
3882 }
3883 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003884
3885 case Instruction::Shl: {
3886 // We know that the AND will not produce any of the bits shifted in, so if
3887 // the anded constant includes them, clear them now!
3888 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003889 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003890 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003891 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003892 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003893
Zhou Sheng290bec52007-03-29 08:15:12 +00003894 if (CI->getValue() == ShlMask) {
3895 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003896 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3897 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003898 TheAnd.setOperand(1, CI);
3899 return &TheAnd;
3900 }
3901 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003902 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003903 case Instruction::LShr:
3904 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003905 // We know that the AND will not produce any of the bits shifted in, so if
3906 // the anded constant includes them, clear them now! This only applies to
3907 // unsigned shifts, because a signed shr may bring in set bits!
3908 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003909 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003910 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003911 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003912 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003913
Zhou Sheng290bec52007-03-29 08:15:12 +00003914 if (CI->getValue() == ShrMask) {
3915 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003916 return ReplaceInstUsesWith(TheAnd, Op);
3917 } else if (CI != AndRHS) {
3918 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3919 return &TheAnd;
3920 }
3921 break;
3922 }
3923 case Instruction::AShr:
3924 // Signed shr.
3925 // See if this is shifting in some sign extension, then masking it out
3926 // with an and.
3927 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003928 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003929 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003930 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003931 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003932 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003933 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003934 // Make the argument unsigned.
3935 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003936 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003937 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003938 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003939 }
3940 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003941 }
3942 return 0;
3943}
3944
Chris Lattner8b170942002-08-09 23:47:40 +00003945
Chris Lattnera96879a2004-09-29 17:40:11 +00003946/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3947/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003948/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3949/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003950/// insert new instructions.
3951Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003952 bool isSigned, bool Inside,
3953 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003954 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003955 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003956 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003957
Chris Lattnera96879a2004-09-29 17:40:11 +00003958 if (Inside) {
3959 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003960 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003961
Reid Spencere4d87aa2006-12-23 06:05:41 +00003962 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003963 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003964 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003965 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003966 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003967 }
3968
3969 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003970 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003971 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003972 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003973 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003974 }
3975
3976 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003977 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003978
Reid Spencere4e40032007-03-21 23:19:50 +00003979 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003980 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003981 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003982 ICmpInst::Predicate pred = (isSigned ?
3983 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003984 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003985 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003986
Reid Spencere4e40032007-03-21 23:19:50 +00003987 // Emit V-Lo >u Hi-1-Lo
3988 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003989 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003990 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003991 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003992 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003993}
3994
Chris Lattner7203e152005-09-18 07:22:02 +00003995// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3996// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3997// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3998// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003999static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004000 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004001 uint32_t BitWidth = Val->getType()->getBitWidth();
4002 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004003
4004 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004005 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004006 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004007 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004008 return true;
4009}
4010
Chris Lattner7203e152005-09-18 07:22:02 +00004011/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4012/// where isSub determines whether the operator is a sub. If we can fold one of
4013/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004014///
4015/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4016/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4017/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4018///
4019/// return (A +/- B).
4020///
4021Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004022 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004023 Instruction &I) {
4024 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4025 if (!LHSI || LHSI->getNumOperands() != 2 ||
4026 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4027
4028 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4029
4030 switch (LHSI->getOpcode()) {
4031 default: return 0;
4032 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004033 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004034 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004035 if ((Mask->getValue().countLeadingZeros() +
4036 Mask->getValue().countPopulation()) ==
4037 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004038 break;
4039
4040 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4041 // part, we don't need any explicit masks to take them out of A. If that
4042 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004043 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004044 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004045 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004046 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004047 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004048 break;
4049 }
4050 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004051 return 0;
4052 case Instruction::Or:
4053 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004054 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004055 if ((Mask->getValue().countLeadingZeros() +
4056 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004057 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004058 break;
4059 return 0;
4060 }
4061
Chris Lattnerc8e77562005-09-18 04:24:45 +00004062 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004063 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4064 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004065}
4066
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004067/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4068Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4069 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner3f40e232009-11-29 00:51:17 +00004070 // (icmp eq A, null) & (icmp eq B, null) -->
4071 // (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4072 if (TD &&
4073 LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4074 RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4075 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4076 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4077 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4078 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4079 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4080 Value *NewOr = Builder->CreateOr(A, B);
4081 return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4082 Constant::getNullValue(IntPtrTy));
4083 }
4084
Chris Lattnerea065fb2008-11-16 05:10:52 +00004085 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004086 ConstantInt *LHSCst, *RHSCst;
4087 ICmpInst::Predicate LHSCC, RHSCC;
4088
Chris Lattnerea065fb2008-11-16 05:10:52 +00004089 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004090 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004091 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004092 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004093 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004094 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004095
Chris Lattner3f40e232009-11-29 00:51:17 +00004096 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4097 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4098 // where C is a power of 2
4099 if (LHSCC == ICmpInst::ICMP_ULT &&
4100 LHSCst->getValue().isPowerOf2()) {
4101 Value *NewOr = Builder->CreateOr(Val, Val2);
4102 return new ICmpInst(LHSCC, NewOr, LHSCst);
4103 }
4104
4105 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4106 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4107 Value *NewOr = Builder->CreateOr(Val, Val2);
4108 return new ICmpInst(LHSCC, NewOr, LHSCst);
4109 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004110 }
4111
4112 // From here on, we only handle:
4113 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4114 if (Val != Val2) return 0;
4115
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004116 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4117 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4118 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4119 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4120 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4121 return 0;
4122
4123 // We can't fold (ugt x, C) & (sgt x, C2).
4124 if (!PredicatesFoldable(LHSCC, RHSCC))
4125 return 0;
4126
4127 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004128 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004129 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004130 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004131 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004132 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004133 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004134 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4135
4136 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004137 std::swap(LHS, RHS);
4138 std::swap(LHSCst, RHSCst);
4139 std::swap(LHSCC, RHSCC);
4140 }
4141
4142 // At this point, we know we have have two icmp instructions
4143 // comparing a value against two constants and and'ing the result
4144 // together. Because of the above check, we know that we only have
4145 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4146 // (from the FoldICmpLogical check above), that the two constants
4147 // are not equal and that the larger constant is on the RHS
4148 assert(LHSCst != RHSCst && "Compares not folded above?");
4149
4150 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004151 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004152 case ICmpInst::ICMP_EQ:
4153 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004154 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004155 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4156 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4157 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004158 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004159 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4160 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4161 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4162 return ReplaceInstUsesWith(I, LHS);
4163 }
4164 case ICmpInst::ICMP_NE:
4165 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004166 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004167 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004168 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004169 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004170 break; // (X != 13 & X u< 15) -> no change
4171 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004172 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004173 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004174 break; // (X != 13 & X s< 15) -> no change
4175 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4176 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4177 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4178 return ReplaceInstUsesWith(I, RHS);
4179 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004180 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004181 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004182 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004183 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004184 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004185 }
4186 break; // (X != 13 & X != 15) -> no change
4187 }
4188 break;
4189 case ICmpInst::ICMP_ULT:
4190 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004191 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004192 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4193 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004194 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004195 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4196 break;
4197 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4198 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4199 return ReplaceInstUsesWith(I, LHS);
4200 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4201 break;
4202 }
4203 break;
4204 case ICmpInst::ICMP_SLT:
4205 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004206 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004207 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4208 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004209 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004210 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4211 break;
4212 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4213 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4214 return ReplaceInstUsesWith(I, LHS);
4215 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4216 break;
4217 }
4218 break;
4219 case ICmpInst::ICMP_UGT:
4220 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004221 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004222 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4223 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4224 return ReplaceInstUsesWith(I, RHS);
4225 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4226 break;
4227 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004228 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004229 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004230 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004231 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004232 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004233 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004234 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4235 break;
4236 }
4237 break;
4238 case ICmpInst::ICMP_SGT:
4239 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004240 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004241 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4242 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4243 return ReplaceInstUsesWith(I, RHS);
4244 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4245 break;
4246 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004247 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004248 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004249 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004250 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004251 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004252 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004253 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4254 break;
4255 }
4256 break;
4257 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004258
4259 return 0;
4260}
4261
Chris Lattner42d1be02009-07-23 05:14:02 +00004262Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4263 FCmpInst *RHS) {
4264
4265 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4266 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4267 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4268 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4269 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4270 // If either of the constants are nans, then the whole thing returns
4271 // false.
4272 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004273 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004274 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004275 LHS->getOperand(0), RHS->getOperand(0));
4276 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004277
4278 // Handle vector zeros. This occurs because the canonical form of
4279 // "fcmp ord x,x" is "fcmp ord x, 0".
4280 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4281 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004282 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004283 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004284 return 0;
4285 }
4286
4287 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4288 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4289 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4290
4291
4292 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4293 // Swap RHS operands to match LHS.
4294 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4295 std::swap(Op1LHS, Op1RHS);
4296 }
4297
4298 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4299 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4300 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004301 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004302
4303 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004304 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004305 if (Op0CC == FCmpInst::FCMP_TRUE)
4306 return ReplaceInstUsesWith(I, RHS);
4307 if (Op1CC == FCmpInst::FCMP_TRUE)
4308 return ReplaceInstUsesWith(I, LHS);
4309
4310 bool Op0Ordered;
4311 bool Op1Ordered;
4312 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4313 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4314 if (Op1Pred == 0) {
4315 std::swap(LHS, RHS);
4316 std::swap(Op0Pred, Op1Pred);
4317 std::swap(Op0Ordered, Op1Ordered);
4318 }
4319 if (Op0Pred == 0) {
4320 // uno && ueq -> uno && (uno || eq) -> ueq
4321 // ord && olt -> ord && (ord && lt) -> olt
4322 if (Op0Ordered == Op1Ordered)
4323 return ReplaceInstUsesWith(I, RHS);
4324
4325 // uno && oeq -> uno && (ord && eq) -> false
4326 // uno && ord -> false
4327 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004328 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004329 // ord && ueq -> ord && (uno || eq) -> oeq
4330 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4331 Op0LHS, Op0RHS, Context));
4332 }
4333 }
4334
4335 return 0;
4336}
4337
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004338
Chris Lattner7e708292002-06-25 16:13:24 +00004339Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004340 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004341 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004342
Chris Lattnerd06094f2009-11-10 00:55:12 +00004343 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4344 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004345
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004346 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004347 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004348 if (SimplifyDemandedInstructionBits(I))
4349 return &I;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004350
Dan Gohman6de29f82009-06-15 22:12:54 +00004351
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004352 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004353 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004354 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004355
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004356 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004357 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004358 Value *Op0LHS = Op0I->getOperand(0);
4359 Value *Op0RHS = Op0I->getOperand(1);
4360 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004361 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004362 case Instruction::Xor:
4363 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004364 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004365 if (!Op0I->hasOneUse()) break;
4366
4367 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4368 // Not masking anything out for the LHS, move to RHS.
4369 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4370 Op0RHS->getName()+".masked");
4371 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4372 }
4373 if (!isa<Constant>(Op0RHS) &&
4374 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4375 // Not masking anything out for the RHS, move to LHS.
4376 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4377 Op0LHS->getName()+".masked");
4378 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004379 }
4380
Chris Lattner6e7ba452005-01-01 16:22:27 +00004381 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004382 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004383 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4384 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4385 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4386 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004387 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004388 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004389 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004390 break;
4391
4392 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004393 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4394 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4395 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4396 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004397 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004398
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004399 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4400 // has 1's for all bits that the subtraction with A might affect.
4401 if (Op0I->hasOneUse()) {
4402 uint32_t BitWidth = AndRHSMask.getBitWidth();
4403 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4404 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4405
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004406 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004407 if (!(A && A->isZero()) && // avoid infinite recursion.
4408 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004409 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004410 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4411 }
4412 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004413 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004414
4415 case Instruction::Shl:
4416 case Instruction::LShr:
4417 // (1 << x) & 1 --> zext(x == 0)
4418 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004419 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004420 Value *NewICmp =
4421 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004422 return new ZExtInst(NewICmp, I.getType());
4423 }
4424 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004425 }
4426
Chris Lattner58403262003-07-23 19:25:52 +00004427 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004428 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004429 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004430 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004431 // If this is an integer truncation or change from signed-to-unsigned, and
4432 // if the source is an and/or with immediate, transform it. This
4433 // frequently occurs for bitfield accesses.
4434 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004435 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004436 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004437 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004438 if (CastOp->getOpcode() == Instruction::And) {
4439 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004440 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4441 // This will fold the two constants together, which may allow
4442 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004443 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004444 CastOp->getOperand(0), I.getType(),
4445 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004446 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004447 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004448 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004449 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004450 } else if (CastOp->getOpcode() == Instruction::Or) {
4451 // Change: and (cast (or X, C1) to T), C2
4452 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004453 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004454 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004455 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004456 return ReplaceInstUsesWith(I, AndRHS);
4457 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004458 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004459 }
Chris Lattner06782f82003-07-23 19:36:21 +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 Lattnerc6a8aff2003-07-23 17:57:01 +00004469 }
4470
Chris Lattner5b62aa72004-06-18 06:07:51 +00004471
Misha Brukmancb6267b2004-07-30 12:50:08 +00004472 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004473 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4474 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4475 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4476 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4477 I.getName()+".demorgan");
4478 return BinaryOperator::CreateNot(Or);
4479 }
4480
Chris Lattner2082ad92006-02-13 23:07:23 +00004481 {
Chris Lattner003b6202007-06-15 05:58:24 +00004482 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004483 // (A|B) & ~(A&B) -> A^B
4484 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4485 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4486 ((A == C && B == D) || (A == D && B == C)))
4487 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004488
Chris Lattnerd06094f2009-11-10 00:55:12 +00004489 // ~(A&B) & (A|B) -> A^B
4490 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4491 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4492 ((A == C && B == D) || (A == D && B == C)))
4493 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004494
4495 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004496 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004497 if (A == Op1) { // (A^B)&A -> A&(A^B)
4498 I.swapOperands(); // Simplify below
4499 std::swap(Op0, Op1);
4500 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4501 cast<BinaryOperator>(Op0)->swapOperands();
4502 I.swapOperands(); // Simplify below
4503 std::swap(Op0, Op1);
4504 }
4505 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004506
Chris Lattner64daab52006-04-01 08:03:55 +00004507 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004508 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004509 if (B == Op0) { // B&(A^B) -> B&(B^A)
4510 cast<BinaryOperator>(Op1)->swapOperands();
4511 std::swap(A, B);
4512 }
Chris Lattner74381062009-08-30 07:44:24 +00004513 if (A == Op0) // A&(A^B) -> A & ~B
4514 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004515 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004516
4517 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004518 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4519 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004520 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004521 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4522 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004523 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004524 }
4525
Reid Spencere4d87aa2006-12-23 06:05:41 +00004526 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4527 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004528 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004529 return R;
4530
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004531 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4532 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4533 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004534 }
4535
Chris Lattner6fc205f2006-05-05 06:39:07 +00004536 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004537 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4538 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4539 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4540 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004541 if (SrcTy == Op1C->getOperand(0)->getType() &&
4542 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004543 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004544 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4545 I.getType(), TD) &&
4546 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4547 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004548 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4549 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004550 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004551 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004552 }
Chris Lattnere511b742006-11-14 07:46:50 +00004553
4554 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004555 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4556 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4557 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004558 SI0->getOperand(1) == SI1->getOperand(1) &&
4559 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004560 Value *NewOp =
4561 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4562 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004563 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004564 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004565 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004566 }
4567
Evan Cheng8db90722008-10-14 17:15:11 +00004568 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004569 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004570 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4571 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4572 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004573 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004574
Chris Lattner7e708292002-06-25 16:13:24 +00004575 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004576}
4577
Chris Lattner8c34cd22008-10-05 02:13:19 +00004578/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4579/// capable of providing pieces of a bswap. The subexpression provides pieces
4580/// of a bswap if it is proven that each of the non-zero bytes in the output of
4581/// the expression came from the corresponding "byte swapped" byte in some other
4582/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4583/// we know that the expression deposits the low byte of %X into the high byte
4584/// of the bswap result and that all other bytes are zero. This expression is
4585/// accepted, the high byte of ByteValues is set to X to indicate a correct
4586/// match.
4587///
4588/// This function returns true if the match was unsuccessful and false if so.
4589/// On entry to the function the "OverallLeftShift" is a signed integer value
4590/// indicating the number of bytes that the subexpression is later shifted. For
4591/// example, if the expression is later right shifted by 16 bits, the
4592/// OverallLeftShift value would be -2 on entry. This is used to specify which
4593/// byte of ByteValues is actually being set.
4594///
4595/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4596/// byte is masked to zero by a user. For example, in (X & 255), X will be
4597/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4598/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4599/// always in the local (OverallLeftShift) coordinate space.
4600///
4601static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4602 SmallVector<Value*, 8> &ByteValues) {
4603 if (Instruction *I = dyn_cast<Instruction>(V)) {
4604 // If this is an or instruction, it may be an inner node of the bswap.
4605 if (I->getOpcode() == Instruction::Or) {
4606 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4607 ByteValues) ||
4608 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4609 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004610 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004611
4612 // If this is a logical shift by a constant multiple of 8, recurse with
4613 // OverallLeftShift and ByteMask adjusted.
4614 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4615 unsigned ShAmt =
4616 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4617 // Ensure the shift amount is defined and of a byte value.
4618 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4619 return true;
4620
4621 unsigned ByteShift = ShAmt >> 3;
4622 if (I->getOpcode() == Instruction::Shl) {
4623 // X << 2 -> collect(X, +2)
4624 OverallLeftShift += ByteShift;
4625 ByteMask >>= ByteShift;
4626 } else {
4627 // X >>u 2 -> collect(X, -2)
4628 OverallLeftShift -= ByteShift;
4629 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004630 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004631 }
4632
4633 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4634 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4635
4636 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4637 ByteValues);
4638 }
4639
4640 // If this is a logical 'and' with a mask that clears bytes, clear the
4641 // corresponding bytes in ByteMask.
4642 if (I->getOpcode() == Instruction::And &&
4643 isa<ConstantInt>(I->getOperand(1))) {
4644 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4645 unsigned NumBytes = ByteValues.size();
4646 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4647 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4648
4649 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4650 // If this byte is masked out by a later operation, we don't care what
4651 // the and mask is.
4652 if ((ByteMask & (1 << i)) == 0)
4653 continue;
4654
4655 // If the AndMask is all zeros for this byte, clear the bit.
4656 APInt MaskB = AndMask & Byte;
4657 if (MaskB == 0) {
4658 ByteMask &= ~(1U << i);
4659 continue;
4660 }
4661
4662 // If the AndMask is not all ones for this byte, it's not a bytezap.
4663 if (MaskB != Byte)
4664 return true;
4665
4666 // Otherwise, this byte is kept.
4667 }
4668
4669 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4670 ByteValues);
4671 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004672 }
4673
Chris Lattner8c34cd22008-10-05 02:13:19 +00004674 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4675 // the input value to the bswap. Some observations: 1) if more than one byte
4676 // is demanded from this input, then it could not be successfully assembled
4677 // into a byteswap. At least one of the two bytes would not be aligned with
4678 // their ultimate destination.
4679 if (!isPowerOf2_32(ByteMask)) return true;
4680 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004681
Chris Lattner8c34cd22008-10-05 02:13:19 +00004682 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4683 // is demanded, it needs to go into byte 0 of the result. This means that the
4684 // byte needs to be shifted until it lands in the right byte bucket. The
4685 // shift amount depends on the position: if the byte is coming from the high
4686 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4687 // low part, it must be shifted left.
4688 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4689 if (InputByteNo < ByteValues.size()/2) {
4690 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4691 return true;
4692 } else {
4693 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4694 return true;
4695 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004696
4697 // If the destination byte value is already defined, the values are or'd
4698 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004699 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004700 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004701 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004702 return false;
4703}
4704
4705/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4706/// If so, insert the new bswap intrinsic and return it.
4707Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004708 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004709 if (!ITy || ITy->getBitWidth() % 16 ||
4710 // ByteMask only allows up to 32-byte values.
4711 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004712 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004713
4714 /// ByteValues - For each byte of the result, we keep track of which value
4715 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004716 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004717 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004718
4719 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004720 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4721 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004722 return 0;
4723
4724 // Check to see if all of the bytes come from the same value.
4725 Value *V = ByteValues[0];
4726 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4727
4728 // Check to make sure that all of the bytes come from the same value.
4729 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4730 if (ByteValues[i] != V)
4731 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004732 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004733 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004734 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004735 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004736}
4737
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004738/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4739/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4740/// we can simplify this expression to "cond ? C : D or B".
4741static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004742 Value *C, Value *D,
4743 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004744 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004745 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004746 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004747 return 0;
4748
Chris Lattnera6a474d2008-11-16 04:26:55 +00004749 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004750 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004751 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004752 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004753 return SelectInst::Create(Cond, C, B);
4754 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004755 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004756 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004757 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004758 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004759 return 0;
4760}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004761
Chris Lattner69d4ced2008-11-16 05:20:07 +00004762/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4763Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4764 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattner3f40e232009-11-29 00:51:17 +00004765 // (icmp ne A, null) | (icmp ne B, null) -->
4766 // (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4767 if (TD &&
4768 LHS->getPredicate() == ICmpInst::ICMP_NE &&
4769 RHS->getPredicate() == ICmpInst::ICMP_NE &&
4770 isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4771 isa<ConstantPointerNull>(RHS->getOperand(1))) {
4772 const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4773 Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4774 Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4775 Value *NewOr = Builder->CreateOr(A, B);
4776 return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4777 Constant::getNullValue(IntPtrTy));
4778 }
4779
Chris Lattner69d4ced2008-11-16 05:20:07 +00004780 Value *Val, *Val2;
4781 ConstantInt *LHSCst, *RHSCst;
4782 ICmpInst::Predicate LHSCC, RHSCC;
4783
4784 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004785 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4786 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004787 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004788
4789
4790 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4791 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4792 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4793 Value *NewOr = Builder->CreateOr(Val, Val2);
4794 return new ICmpInst(LHSCC, NewOr, LHSCst);
4795 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004796
4797 // From here on, we only handle:
4798 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4799 if (Val != Val2) return 0;
4800
4801 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4802 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4803 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4804 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4805 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4806 return 0;
4807
4808 // We can't fold (ugt x, C) | (sgt x, C2).
4809 if (!PredicatesFoldable(LHSCC, RHSCC))
4810 return 0;
4811
4812 // Ensure that the larger constant is on the RHS.
4813 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004814 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004815 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004816 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004817 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4818 else
4819 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4820
4821 if (ShouldSwap) {
4822 std::swap(LHS, RHS);
4823 std::swap(LHSCst, RHSCst);
4824 std::swap(LHSCC, RHSCC);
4825 }
4826
4827 // At this point, we know we have have two icmp instructions
4828 // comparing a value against two constants and or'ing the result
4829 // together. Because of the above check, we know that we only have
4830 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4831 // FoldICmpLogical check above), that the two constants are not
4832 // equal.
4833 assert(LHSCst != RHSCst && "Compares not folded above?");
4834
4835 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004836 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004837 case ICmpInst::ICMP_EQ:
4838 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004839 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004840 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004841 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004842 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004843 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004844 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004845 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004846 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004847 }
4848 break; // (X == 13 | X == 15) -> no change
4849 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4850 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4851 break;
4852 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4853 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4854 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4855 return ReplaceInstUsesWith(I, RHS);
4856 }
4857 break;
4858 case ICmpInst::ICMP_NE:
4859 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004860 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004861 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4862 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4863 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4864 return ReplaceInstUsesWith(I, LHS);
4865 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4866 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4867 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004868 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004869 }
4870 break;
4871 case ICmpInst::ICMP_ULT:
4872 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004873 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004874 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4875 break;
4876 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4877 // If RHSCst is [us]MAXINT, it is always false. Not handling
4878 // this can cause overflow.
4879 if (RHSCst->isMaxValue(false))
4880 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004881 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004882 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004883 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4884 break;
4885 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4886 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4887 return ReplaceInstUsesWith(I, RHS);
4888 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4889 break;
4890 }
4891 break;
4892 case ICmpInst::ICMP_SLT:
4893 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004894 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004895 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4896 break;
4897 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4898 // If RHSCst is [us]MAXINT, it is always false. Not handling
4899 // this can cause overflow.
4900 if (RHSCst->isMaxValue(true))
4901 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004902 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004903 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004904 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4905 break;
4906 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4907 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4908 return ReplaceInstUsesWith(I, RHS);
4909 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4910 break;
4911 }
4912 break;
4913 case ICmpInst::ICMP_UGT:
4914 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004915 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004916 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4917 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4918 return ReplaceInstUsesWith(I, LHS);
4919 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4920 break;
4921 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4922 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004923 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004924 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4925 break;
4926 }
4927 break;
4928 case ICmpInst::ICMP_SGT:
4929 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004930 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004931 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4932 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4933 return ReplaceInstUsesWith(I, LHS);
4934 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4935 break;
4936 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4937 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004938 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004939 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4940 break;
4941 }
4942 break;
4943 }
4944 return 0;
4945}
4946
Chris Lattner5414cc52009-07-23 05:46:22 +00004947Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4948 FCmpInst *RHS) {
4949 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4950 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4951 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4952 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4953 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4954 // If either of the constants are nans, then the whole thing returns
4955 // true.
4956 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004957 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004958
4959 // Otherwise, no need to compare the two constants, compare the
4960 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004961 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004962 LHS->getOperand(0), RHS->getOperand(0));
4963 }
4964
4965 // Handle vector zeros. This occurs because the canonical form of
4966 // "fcmp uno x,x" is "fcmp uno x, 0".
4967 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4968 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004969 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004970 LHS->getOperand(0), RHS->getOperand(0));
4971
4972 return 0;
4973 }
4974
4975 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4976 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4977 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4978
4979 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4980 // Swap RHS operands to match LHS.
4981 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4982 std::swap(Op1LHS, Op1RHS);
4983 }
4984 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4985 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4986 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004987 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004988 Op0LHS, Op0RHS);
4989 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004990 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004991 if (Op0CC == FCmpInst::FCMP_FALSE)
4992 return ReplaceInstUsesWith(I, RHS);
4993 if (Op1CC == FCmpInst::FCMP_FALSE)
4994 return ReplaceInstUsesWith(I, LHS);
4995 bool Op0Ordered;
4996 bool Op1Ordered;
4997 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4998 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4999 if (Op0Ordered == Op1Ordered) {
5000 // If both are ordered or unordered, return a new fcmp with
5001 // or'ed predicates.
5002 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5003 Op0LHS, Op0RHS, Context);
5004 if (Instruction *I = dyn_cast<Instruction>(RV))
5005 return I;
5006 // Otherwise, it's a constant boolean value...
5007 return ReplaceInstUsesWith(I, RV);
5008 }
5009 }
5010 return 0;
5011}
5012
Bill Wendlinga698a472008-12-01 08:23:25 +00005013/// FoldOrWithConstants - This helper function folds:
5014///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005015/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00005016///
5017/// into:
5018///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005019/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005020///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005021/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005022Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005023 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005024 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5025 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005026
Bill Wendling286a0542008-12-02 06:24:20 +00005027 Value *V1 = 0;
5028 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005029 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005030
Bill Wendling29976b92008-12-02 06:18:11 +00005031 APInt Xor = CI1->getValue() ^ CI2->getValue();
5032 if (!Xor.isAllOnesValue()) return 0;
5033
Bill Wendling286a0542008-12-02 06:24:20 +00005034 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005035 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005036 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005037 }
5038
5039 return 0;
5040}
5041
Chris Lattner7e708292002-06-25 16:13:24 +00005042Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005043 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005044 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005045
Chris Lattnerd06094f2009-11-10 00:55:12 +00005046 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5047 return ReplaceInstUsesWith(I, V);
5048
5049
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005050 // See if we can simplify any instructions used by the instruction whose sole
5051 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005052 if (SimplifyDemandedInstructionBits(I))
5053 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005054
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005055 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005056 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005057 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005058 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005059 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005060 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005061 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005062 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005063 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005064 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005065
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005066 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005067 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005068 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005069 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005070 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005071 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005072 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005073 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005074
5075 // Try to fold constant and into select arguments.
5076 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005077 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005078 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005079 if (isa<PHINode>(Op0))
5080 if (Instruction *NV = FoldOpIntoPhi(I))
5081 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005082 }
5083
Chris Lattner4f637d42006-01-06 17:59:59 +00005084 Value *A = 0, *B = 0;
5085 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005086
Chris Lattner6423d4c2006-07-10 20:25:24 +00005087 // (A | B) | C and A | (B | C) -> bswap if possible.
5088 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005089 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5090 match(Op1, m_Or(m_Value(), m_Value())) ||
5091 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5092 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005093 if (Instruction *BSwap = MatchBSwap(I))
5094 return BSwap;
5095 }
5096
Chris Lattner6e4c6492005-05-09 04:58:36 +00005097 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005098 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005099 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005100 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005101 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005102 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005103 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005104 }
5105
5106 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005107 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005108 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005109 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005110 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005111 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005112 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005113 }
5114
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005115 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005116 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005117 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5118 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005119 Value *V1 = 0, *V2 = 0, *V3 = 0;
5120 C1 = dyn_cast<ConstantInt>(C);
5121 C2 = dyn_cast<ConstantInt>(D);
5122 if (C1 && C2) { // (A & C1)|(B & C2)
5123 // If we have: ((V + N) & C1) | (V & C2)
5124 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5125 // replace with V+N.
5126 if (C1->getValue() == ~C2->getValue()) {
5127 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005128 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005129 // Add commutes, try both ways.
5130 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5131 return ReplaceInstUsesWith(I, A);
5132 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5133 return ReplaceInstUsesWith(I, A);
5134 }
5135 // Or commutes, try both ways.
5136 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005137 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005138 // Add commutes, try both ways.
5139 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5140 return ReplaceInstUsesWith(I, B);
5141 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5142 return ReplaceInstUsesWith(I, B);
5143 }
5144 }
Chris Lattner044e5332007-04-08 08:01:49 +00005145 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005146 }
5147
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005148 // Check to see if we have any common things being and'ed. If so, find the
5149 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005150 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5151 if (A == B) // (A & C)|(A & D) == A & (C|D)
5152 V1 = A, V2 = C, V3 = D;
5153 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5154 V1 = A, V2 = B, V3 = C;
5155 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5156 V1 = C, V2 = A, V3 = D;
5157 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5158 V1 = C, V2 = A, V3 = B;
5159
5160 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005161 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005162 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005163 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005164 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005165
Dan Gohman1975d032008-10-30 20:40:10 +00005166 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005167 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005168 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005169 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005170 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005171 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005172 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005173 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005174 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005175
Bill Wendlingb01865c2008-11-30 13:52:49 +00005176 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005177 if ((match(C, m_Not(m_Specific(D))) &&
5178 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005179 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005180 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005181 if ((match(A, m_Not(m_Specific(D))) &&
5182 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005183 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005184 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005185 if ((match(C, m_Not(m_Specific(B))) &&
5186 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005187 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005188 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005189 if ((match(A, m_Not(m_Specific(B))) &&
5190 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005191 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005192 }
Chris Lattnere511b742006-11-14 07:46:50 +00005193
5194 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005195 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5196 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5197 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005198 SI0->getOperand(1) == SI1->getOperand(1) &&
5199 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005200 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5201 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005202 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005203 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005204 }
5205 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005206
Bill Wendlingb3833d12008-12-01 01:07:11 +00005207 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005208 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5209 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005210 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005211 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005212 }
5213 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005214 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5215 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005216 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005217 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005218 }
5219
Chris Lattnerd06094f2009-11-10 00:55:12 +00005220 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5221 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5222 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5223 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5224 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5225 I.getName()+".demorgan");
5226 return BinaryOperator::CreateNot(And);
5227 }
Chris Lattnera2881962003-02-18 19:28:33 +00005228
Reid Spencere4d87aa2006-12-23 06:05:41 +00005229 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5230 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005231 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005232 return R;
5233
Chris Lattner69d4ced2008-11-16 05:20:07 +00005234 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5235 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5236 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005237 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005238
5239 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005240 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005241 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005242 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005243 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5244 !isa<ICmpInst>(Op1C->getOperand(0))) {
5245 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005246 if (SrcTy == Op1C->getOperand(0)->getType() &&
5247 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005248 // Only do this if the casts both really cause code to be
5249 // generated.
5250 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5251 I.getType(), TD) &&
5252 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5253 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005254 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5255 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005256 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005257 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005258 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005259 }
Chris Lattner99c65742007-10-24 05:38:08 +00005260 }
5261
5262
5263 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5264 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005265 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5266 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5267 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005268 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005269
Chris Lattner7e708292002-06-25 16:13:24 +00005270 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005271}
5272
Dan Gohman844731a2008-05-13 00:00:25 +00005273namespace {
5274
Chris Lattnerc317d392004-02-16 01:20:27 +00005275// XorSelf - Implements: X ^ X --> 0
5276struct XorSelf {
5277 Value *RHS;
5278 XorSelf(Value *rhs) : RHS(rhs) {}
5279 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5280 Instruction *apply(BinaryOperator &Xor) const {
5281 return &Xor;
5282 }
5283};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005284
Dan Gohman844731a2008-05-13 00:00:25 +00005285}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005286
Chris Lattner7e708292002-06-25 16:13:24 +00005287Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005288 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005289 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005290
Evan Chengd34af782008-03-25 20:07:13 +00005291 if (isa<UndefValue>(Op1)) {
5292 if (isa<UndefValue>(Op0))
5293 // Handle undef ^ undef -> 0 special case. This is a common
5294 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005295 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005296 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005297 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005298
Chris Lattnerc317d392004-02-16 01:20:27 +00005299 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005300 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005301 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005302 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005303 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005304
5305 // See if we can simplify any instructions used by the instruction whose sole
5306 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005307 if (SimplifyDemandedInstructionBits(I))
5308 return &I;
5309 if (isa<VectorType>(I.getType()))
5310 if (isa<ConstantAggregateZero>(Op1))
5311 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005312
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005313 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005314 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005315 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5316 if (Op0I->getOpcode() == Instruction::And ||
5317 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005318 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5319 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5320 if (dyn_castNotVal(Op0I->getOperand(1)))
5321 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005322 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005323 Value *NotY =
5324 Builder->CreateNot(Op0I->getOperand(1),
5325 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005326 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005327 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005328 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005329 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005330
5331 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5332 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5333 if (isFreeToInvert(Op0I->getOperand(0)) &&
5334 isFreeToInvert(Op0I->getOperand(1))) {
5335 Value *NotX =
5336 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5337 Value *NotY =
5338 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5339 if (Op0I->getOpcode() == Instruction::And)
5340 return BinaryOperator::CreateOr(NotX, NotY);
5341 return BinaryOperator::CreateAnd(NotX, NotY);
5342 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005343 }
5344 }
5345 }
5346
5347
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005348 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005349 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005350 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005351 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005352 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005353 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005354
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005355 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005356 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005357 FCI->getOperand(0), FCI->getOperand(1));
5358 }
5359
Nick Lewycky517e1f52008-05-31 19:01:33 +00005360 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5361 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5362 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5363 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5364 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005365 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5366 (RHS == ConstantExpr::getCast(Opcode,
5367 ConstantInt::getTrue(*Context),
5368 Op0C->getDestTy()))) {
5369 CI->setPredicate(CI->getInversePredicate());
5370 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005371 }
5372 }
5373 }
5374 }
5375
Reid Spencere4d87aa2006-12-23 06:05:41 +00005376 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005377 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005378 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5379 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005380 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5381 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005382 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005383 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005384 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005385
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005386 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005387 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005388 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005389 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005390 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005391 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005392 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005393 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005394 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005395 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005396 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005397 Constant *C = ConstantInt::get(*Context,
5398 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005399 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005400
Chris Lattner7c4049c2004-01-12 19:35:11 +00005401 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005402 } else if (Op0I->getOpcode() == Instruction::Or) {
5403 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005404 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005405 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005406 // Anything in both C1 and C2 is known to be zero, remove it from
5407 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005408 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5409 NewRHS = ConstantExpr::getAnd(NewRHS,
5410 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005411 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005412 I.setOperand(0, Op0I->getOperand(0));
5413 I.setOperand(1, NewRHS);
5414 return &I;
5415 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005416 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005417 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005418 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005419
5420 // Try to fold constant and into select arguments.
5421 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005422 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005423 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005424 if (isa<PHINode>(Op0))
5425 if (Instruction *NV = FoldOpIntoPhi(I))
5426 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005427 }
5428
Dan Gohman186a6362009-08-12 16:04:34 +00005429 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005430 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005431 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005432
Dan Gohman186a6362009-08-12 16:04:34 +00005433 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005434 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005435 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005436
Chris Lattner318bf792007-03-18 22:51:34 +00005437
5438 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5439 if (Op1I) {
5440 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005441 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005442 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005443 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005444 I.swapOperands();
5445 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005446 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005447 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005448 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005449 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005450 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005451 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005452 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005453 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005454 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005455 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005456 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005457 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005458 std::swap(A, B);
5459 }
Chris Lattner318bf792007-03-18 22:51:34 +00005460 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005461 I.swapOperands(); // Simplified below.
5462 std::swap(Op0, Op1);
5463 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005464 }
Chris Lattner318bf792007-03-18 22:51:34 +00005465 }
5466
5467 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5468 if (Op0I) {
5469 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005470 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005471 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005472 if (A == Op1) // (B|A)^B == (A|B)^B
5473 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005474 if (B == Op1) // (A|B)^B == A & ~B
5475 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005476 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005477 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005478 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005479 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005480 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005481 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005482 if (A == Op1) // (A&B)^A -> (B&A)^A
5483 std::swap(A, B);
5484 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005485 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005486 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005487 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005488 }
Chris Lattner318bf792007-03-18 22:51:34 +00005489 }
5490
5491 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5492 if (Op0I && Op1I && Op0I->isShift() &&
5493 Op0I->getOpcode() == Op1I->getOpcode() &&
5494 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5495 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005496 Value *NewOp =
5497 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5498 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005499 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005500 Op1I->getOperand(1));
5501 }
5502
5503 if (Op0I && Op1I) {
5504 Value *A, *B, *C, *D;
5505 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005506 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5507 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005508 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005509 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005510 }
5511 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005512 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5513 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005514 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005515 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005516 }
5517
5518 // (A & B)^(C & D)
5519 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005520 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5521 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005522 // (X & Y)^(X & Y) -> (Y^Z) & X
5523 Value *X = 0, *Y = 0, *Z = 0;
5524 if (A == C)
5525 X = A, Y = B, Z = D;
5526 else if (A == D)
5527 X = A, Y = B, Z = C;
5528 else if (B == C)
5529 X = B, Y = A, Z = D;
5530 else if (B == D)
5531 X = B, Y = A, Z = C;
5532
5533 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005534 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005535 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005536 }
5537 }
5538 }
5539
Reid Spencere4d87aa2006-12-23 06:05:41 +00005540 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5541 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005542 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005543 return R;
5544
Chris Lattner6fc205f2006-05-05 06:39:07 +00005545 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005546 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005547 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005548 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5549 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005550 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005551 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005552 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5553 I.getType(), TD) &&
5554 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5555 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005556 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5557 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005558 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005559 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005560 }
Chris Lattner99c65742007-10-24 05:38:08 +00005561 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005562
Chris Lattner7e708292002-06-25 16:13:24 +00005563 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005564}
5565
Owen Andersond672ecb2009-07-03 00:17:18 +00005566static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005567 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005568 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005569}
Chris Lattnera96879a2004-09-29 17:40:11 +00005570
Dan Gohman6de29f82009-06-15 22:12:54 +00005571static bool HasAddOverflow(ConstantInt *Result,
5572 ConstantInt *In1, ConstantInt *In2,
5573 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005574 if (IsSigned)
5575 if (In2->getValue().isNegative())
5576 return Result->getValue().sgt(In1->getValue());
5577 else
5578 return Result->getValue().slt(In1->getValue());
5579 else
5580 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005581}
5582
Dan Gohman6de29f82009-06-15 22:12:54 +00005583/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005584/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005585static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005586 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005587 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005588 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005589
Dan Gohman6de29f82009-06-15 22:12:54 +00005590 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5591 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005592 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005593 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5594 ExtractElement(In1, Idx, Context),
5595 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005596 IsSigned))
5597 return true;
5598 }
5599 return false;
5600 }
5601
5602 return HasAddOverflow(cast<ConstantInt>(Result),
5603 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5604 IsSigned);
5605}
5606
5607static bool HasSubOverflow(ConstantInt *Result,
5608 ConstantInt *In1, ConstantInt *In2,
5609 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005610 if (IsSigned)
5611 if (In2->getValue().isNegative())
5612 return Result->getValue().slt(In1->getValue());
5613 else
5614 return Result->getValue().sgt(In1->getValue());
5615 else
5616 return Result->getValue().ugt(In1->getValue());
5617}
5618
Dan Gohman6de29f82009-06-15 22:12:54 +00005619/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5620/// overflowed for this type.
5621static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005622 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005623 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005624 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005625
5626 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5627 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005628 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005629 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5630 ExtractElement(In1, Idx, Context),
5631 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005632 IsSigned))
5633 return true;
5634 }
5635 return false;
5636 }
5637
5638 return HasSubOverflow(cast<ConstantInt>(Result),
5639 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5640 IsSigned);
5641}
5642
Chris Lattner10c0d912008-04-22 02:53:33 +00005643
Reid Spencere4d87aa2006-12-23 06:05:41 +00005644/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005645/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005646Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005647 ICmpInst::Predicate Cond,
5648 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005649 // Look through bitcasts.
5650 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5651 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005652
Chris Lattner574da9b2005-01-13 20:14:25 +00005653 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005654 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005655 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005656 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005657 // know pointers can't overflow since the gep is inbounds. See if we can
5658 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005659 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5660
5661 // If not, synthesize the offset the hard way.
5662 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005663 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005664 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005665 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005666 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005667 // If the base pointers are different, but the indices are the same, just
5668 // compare the base pointer.
5669 if (PtrBase != GEPRHS->getOperand(0)) {
5670 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005671 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005672 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005673 if (IndicesTheSame)
5674 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5675 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5676 IndicesTheSame = false;
5677 break;
5678 }
5679
5680 // If all indices are the same, just compare the base pointers.
5681 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005682 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005683 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005684
5685 // Otherwise, the base pointers are different and the indices are
5686 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005687 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005688 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005689
Chris Lattnere9d782b2005-01-13 22:25:21 +00005690 // If one of the GEPs has all zero indices, recurse.
5691 bool AllZeros = true;
5692 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5693 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5694 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5695 AllZeros = false;
5696 break;
5697 }
5698 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005699 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5700 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005701
5702 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005703 AllZeros = true;
5704 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5705 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5706 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5707 AllZeros = false;
5708 break;
5709 }
5710 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005711 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005712
Chris Lattner4401c9c2005-01-14 00:20:05 +00005713 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5714 // If the GEPs only differ by one index, compare it.
5715 unsigned NumDifferences = 0; // Keep track of # differences.
5716 unsigned DiffOperand = 0; // The operand that differs.
5717 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5718 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005719 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5720 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005721 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005722 NumDifferences = 2;
5723 break;
5724 } else {
5725 if (NumDifferences++) break;
5726 DiffOperand = i;
5727 }
5728 }
5729
5730 if (NumDifferences == 0) // SAME GEP?
5731 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005732 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005733 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005734
Chris Lattner4401c9c2005-01-14 00:20:05 +00005735 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005736 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5737 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005738 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005739 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005740 }
5741 }
5742
Reid Spencere4d87aa2006-12-23 06:05:41 +00005743 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005744 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005745 if (TD &&
5746 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005747 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5748 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005749 Value *L = EmitGEPOffset(GEPLHS, *this);
5750 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005751 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005752 }
5753 }
5754 return 0;
5755}
5756
Chris Lattnera5406232008-05-19 20:18:56 +00005757/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5758///
5759Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5760 Instruction *LHSI,
5761 Constant *RHSC) {
5762 if (!isa<ConstantFP>(RHSC)) return 0;
5763 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5764
5765 // Get the width of the mantissa. We don't want to hack on conversions that
5766 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005767 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005768 if (MantissaWidth == -1) return 0; // Unknown.
5769
5770 // Check to see that the input is converted from an integer type that is small
5771 // enough that preserves all bits. TODO: check here for "known" sign bits.
5772 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005773 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005774
5775 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005776 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5777 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005778 ++InputSize;
5779
5780 // If the conversion would lose info, don't hack on this.
5781 if ((int)InputSize > MantissaWidth)
5782 return 0;
5783
5784 // Otherwise, we can potentially simplify the comparison. We know that it
5785 // will always come through as an integer value and we know the constant is
5786 // not a NAN (it would have been previously simplified).
5787 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5788
5789 ICmpInst::Predicate Pred;
5790 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005791 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005792 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005793 case FCmpInst::FCMP_OEQ:
5794 Pred = ICmpInst::ICMP_EQ;
5795 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005796 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005797 case FCmpInst::FCMP_OGT:
5798 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5799 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005800 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005801 case FCmpInst::FCMP_OGE:
5802 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5803 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005804 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005805 case FCmpInst::FCMP_OLT:
5806 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5807 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005808 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005809 case FCmpInst::FCMP_OLE:
5810 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5811 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005812 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005813 case FCmpInst::FCMP_ONE:
5814 Pred = ICmpInst::ICMP_NE;
5815 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005816 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005817 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005818 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005819 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005820 }
5821
5822 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5823
5824 // Now we know that the APFloat is a normal number, zero or inf.
5825
Chris Lattner85162782008-05-20 03:50:52 +00005826 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005827 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005828 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005829
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005830 if (!LHSUnsigned) {
5831 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5832 // and large values.
5833 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5834 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5835 APFloat::rmNearestTiesToEven);
5836 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5837 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5838 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005839 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5840 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005841 }
5842 } else {
5843 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5844 // +INF and large values.
5845 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5846 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5847 APFloat::rmNearestTiesToEven);
5848 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5849 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5850 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5852 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005853 }
Chris Lattnera5406232008-05-19 20:18:56 +00005854 }
5855
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005856 if (!LHSUnsigned) {
5857 // See if the RHS value is < SignedMin.
5858 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5859 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5860 APFloat::rmNearestTiesToEven);
5861 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5862 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5863 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005864 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5865 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005866 }
Chris Lattnera5406232008-05-19 20:18:56 +00005867 }
5868
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005869 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5870 // [0, UMAX], but it may still be fractional. See if it is fractional by
5871 // casting the FP value to the integer value and back, checking for equality.
5872 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005873 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005874 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5875 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005876 if (!RHS.isZero()) {
5877 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005878 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5879 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005880 if (!Equal) {
5881 // If we had a comparison against a fractional value, we have to adjust
5882 // the compare predicate and sometimes the value. RHSC is rounded towards
5883 // zero at this point.
5884 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005885 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005886 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005887 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005888 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005889 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005890 case ICmpInst::ICMP_ULE:
5891 // (float)int <= 4.4 --> int <= 4
5892 // (float)int <= -4.4 --> false
5893 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005894 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005895 break;
5896 case ICmpInst::ICMP_SLE:
5897 // (float)int <= 4.4 --> int <= 4
5898 // (float)int <= -4.4 --> int < -4
5899 if (RHS.isNegative())
5900 Pred = ICmpInst::ICMP_SLT;
5901 break;
5902 case ICmpInst::ICMP_ULT:
5903 // (float)int < -4.4 --> false
5904 // (float)int < 4.4 --> int <= 4
5905 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005906 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005907 Pred = ICmpInst::ICMP_ULE;
5908 break;
5909 case ICmpInst::ICMP_SLT:
5910 // (float)int < -4.4 --> int < -4
5911 // (float)int < 4.4 --> int <= 4
5912 if (!RHS.isNegative())
5913 Pred = ICmpInst::ICMP_SLE;
5914 break;
5915 case ICmpInst::ICMP_UGT:
5916 // (float)int > 4.4 --> int > 4
5917 // (float)int > -4.4 --> true
5918 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005919 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005920 break;
5921 case ICmpInst::ICMP_SGT:
5922 // (float)int > 4.4 --> int > 4
5923 // (float)int > -4.4 --> int >= -4
5924 if (RHS.isNegative())
5925 Pred = ICmpInst::ICMP_SGE;
5926 break;
5927 case ICmpInst::ICMP_UGE:
5928 // (float)int >= -4.4 --> true
5929 // (float)int >= 4.4 --> int > 4
5930 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005931 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005932 Pred = ICmpInst::ICMP_UGT;
5933 break;
5934 case ICmpInst::ICMP_SGE:
5935 // (float)int >= -4.4 --> int >= -4
5936 // (float)int >= 4.4 --> int > 4
5937 if (!RHS.isNegative())
5938 Pred = ICmpInst::ICMP_SGT;
5939 break;
5940 }
Chris Lattnera5406232008-05-19 20:18:56 +00005941 }
5942 }
5943
5944 // Lower this FP comparison into an appropriate integer version of the
5945 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005946 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005947}
5948
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00005950 bool Changed = false;
5951
5952 /// Orders the operands of the compare so that they are listed from most
5953 /// complex to least complex. This puts constants before unary operators,
5954 /// before binary operators.
5955 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5956 I.swapOperands();
5957 Changed = true;
5958 }
5959
Chris Lattner8b170942002-08-09 23:47:40 +00005960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00005961
Chris Lattner210c5d42009-11-09 23:55:12 +00005962 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5963 return ReplaceInstUsesWith(I, V);
5964
Chris Lattner58e97462007-01-14 19:42:17 +00005965 // Simplify 'fcmp pred X, X'
5966 if (Op0 == Op1) {
5967 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005968 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005969 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5970 case FCmpInst::FCMP_ULT: // True if unordered or less than
5971 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5972 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5973 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5974 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005975 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005976 return &I;
5977
5978 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5979 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5980 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5981 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5982 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5983 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005984 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005985 return &I;
5986 }
5987 }
5988
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 // Handle fcmp with constant RHS
5990 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5991 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5992 switch (LHSI->getOpcode()) {
5993 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005994 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5995 // block. If in the same block, we're encouraging jump threading. If
5996 // not, we are just pessimizing the code by making an i1 phi.
5997 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005998 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005999 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006000 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006001 case Instruction::SIToFP:
6002 case Instruction::UIToFP:
6003 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6004 return NV;
6005 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006006 case Instruction::Select:
6007 // If either operand of the select is a constant, we can fold the
6008 // comparison into the select arms, which will cause one to be
6009 // constant folded and the select turned into a bitwise or.
6010 Value *Op1 = 0, *Op2 = 0;
6011 if (LHSI->hasOneUse()) {
6012 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6013 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006014 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006015 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006016 Op2 = Builder->CreateFCmp(I.getPredicate(),
6017 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006018 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6019 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006020 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006021 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006022 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6023 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006024 }
6025 }
6026
6027 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006028 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006029 break;
6030 }
6031 }
6032
6033 return Changed ? &I : 0;
6034}
6035
6036Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006037 bool Changed = false;
6038
6039 /// Orders the operands of the compare so that they are listed from most
6040 /// complex to least complex. This puts constants before unary operators,
6041 /// before binary operators.
6042 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6043 I.swapOperands();
6044 Changed = true;
6045 }
6046
Reid Spencere4d87aa2006-12-23 06:05:41 +00006047 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006048
Chris Lattner210c5d42009-11-09 23:55:12 +00006049 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6050 return ReplaceInstUsesWith(I, V);
6051
6052 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006053
Reid Spencere4d87aa2006-12-23 06:05:41 +00006054 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006055 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006056 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006057 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006058 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006059 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006060 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006061 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006062 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006063 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006064
Reid Spencere4d87aa2006-12-23 06:05:41 +00006065 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006066 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006067 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006068 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006069 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006070 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006071 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006072 case ICmpInst::ICMP_SGT:
6073 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006074 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006075 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006076 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006077 return BinaryOperator::CreateAnd(Not, Op0);
6078 }
6079 case ICmpInst::ICMP_UGE:
6080 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6081 // FALL THROUGH
6082 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006083 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006084 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006085 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006086 case ICmpInst::ICMP_SGE:
6087 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6088 // FALL THROUGH
6089 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006090 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006091 return BinaryOperator::CreateOr(Not, Op0);
6092 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006093 }
Chris Lattner8b170942002-08-09 23:47:40 +00006094 }
6095
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 unsigned BitWidth = 0;
6097 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006098 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6099 else if (Ty->isIntOrIntVector())
6100 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006101
6102 bool isSignBit = false;
6103
Dan Gohman81b28ce2008-09-16 18:46:06 +00006104 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006105 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006106 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006107
Chris Lattnerb6566012008-01-05 01:18:20 +00006108 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6109 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006110 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006111 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006112 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006113 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006114
Dan Gohman81b28ce2008-09-16 18:46:06 +00006115 // If we have an icmp le or icmp ge instruction, turn it into the
6116 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006117 // them being folded in the code below. The SimplifyICmpInst code has
6118 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006119 switch (I.getPredicate()) {
6120 default: break;
6121 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006122 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006123 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006124 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006125 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006126 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006127 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006128 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006129 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006130 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006131 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006132 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006133 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006134 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006135 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006136 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006137 }
6138
Chris Lattner183661e2008-07-11 05:40:05 +00006139 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006140 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006141 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006142 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6143 }
6144
6145 // See if we can fold the comparison based on range information we can get
6146 // by checking whether bits are known to be zero or one in the input.
6147 if (BitWidth != 0) {
6148 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6149 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6150
6151 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006152 isSignBit ? APInt::getSignBit(BitWidth)
6153 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006155 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006156 if (SimplifyDemandedBits(I.getOperandUse(1),
6157 APInt::getAllOnesValue(BitWidth),
6158 Op1KnownZero, Op1KnownOne, 0))
6159 return &I;
6160
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006161 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006162 // in. Compute the Min, Max and RHS values based on the known bits. For the
6163 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6165 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006166 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6168 Op0Min, Op0Max);
6169 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6170 Op1Min, Op1Max);
6171 } else {
6172 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6173 Op0Min, Op0Max);
6174 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6175 Op1Min, Op1Max);
6176 }
6177
Chris Lattner183661e2008-07-11 05:40:05 +00006178 // If Min and Max are known to be the same, then SimplifyDemandedBits
6179 // figured out that the LHS is a constant. Just constant fold this now so
6180 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006181 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006182 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006183 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006184 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006185 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006186 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187
Chris Lattner183661e2008-07-11 05:40:05 +00006188 // Based on the range information we know about the LHS, see if we can
6189 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006191 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006192 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006193 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006194 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006195 break;
6196 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006197 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006198 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006199 break;
6200 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006201 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006202 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006203 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006204 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006205 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006206 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006207 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6208 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006209 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006210 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006211
6212 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6213 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006214 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006215 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216 }
Chris Lattner84dff672008-07-11 05:08:55 +00006217 break;
6218 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006219 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006220 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006222 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006223
6224 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006225 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006226 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6227 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006228 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006229 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006230
6231 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6232 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006233 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006234 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006235 }
Chris Lattner84dff672008-07-11 05:08:55 +00006236 break;
6237 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006238 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006239 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006240 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006241 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006242 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006243 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006244 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6245 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006246 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006247 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006248 }
Chris Lattner84dff672008-07-11 05:08:55 +00006249 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006250 case ICmpInst::ICMP_SGT:
6251 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006252 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006253 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006254 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006255
6256 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006257 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006258 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6259 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006260 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006261 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006262 }
6263 break;
6264 case ICmpInst::ICMP_SGE:
6265 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6266 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006267 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006268 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006269 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006270 break;
6271 case ICmpInst::ICMP_SLE:
6272 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6273 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006274 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006275 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006276 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006277 break;
6278 case ICmpInst::ICMP_UGE:
6279 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6280 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006281 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006282 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006283 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006284 break;
6285 case ICmpInst::ICMP_ULE:
6286 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6287 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006288 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006289 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006290 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006291 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006292 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006293
6294 // Turn a signed comparison into an unsigned one if both operands
6295 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006296 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006297 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6298 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006299 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006300 }
6301
6302 // Test if the ICmpInst instruction is used exclusively by a select as
6303 // part of a minimum or maximum operation. If so, refrain from doing
6304 // any other folding. This helps out other analyses which understand
6305 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6306 // and CodeGen. And in this case, at least one of the comparison
6307 // operands has at least one user besides the compare (the select),
6308 // which would often largely negate the benefit of folding anyway.
6309 if (I.hasOneUse())
6310 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6311 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6312 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6313 return 0;
6314
6315 // See if we are doing a comparison between a constant and an instruction that
6316 // can be folded into the comparison.
6317 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006318 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006319 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006320 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006321 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006322 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6323 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006324 }
6325
Chris Lattner01deb9d2007-04-03 17:43:25 +00006326 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006327 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6328 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6329 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006330 case Instruction::GetElementPtr:
6331 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006332 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006333 bool isAllZeros = true;
6334 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6335 if (!isa<Constant>(LHSI->getOperand(i)) ||
6336 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6337 isAllZeros = false;
6338 break;
6339 }
6340 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006341 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006342 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006343 }
6344 break;
6345
Chris Lattner6970b662005-04-23 15:31:55 +00006346 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006347 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006348 // block. If in the same block, we're encouraging jump threading. If
6349 // not, we are just pessimizing the code by making an i1 phi.
6350 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006351 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006352 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006353 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006354 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006355 // If either operand of the select is a constant, we can fold the
6356 // comparison into the select arms, which will cause one to be
6357 // constant folded and the select turned into a bitwise or.
6358 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006359 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6360 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6361 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6362 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6363
6364 // We only want to perform this transformation if it will not lead to
6365 // additional code. This is true if either both sides of the select
6366 // fold to a constant (in which case the icmp is replaced with a select
6367 // which will usually simplify) or this is the only user of the
6368 // select (in which case we are trading a select+icmp for a simpler
6369 // select+icmp).
6370 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6371 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006372 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6373 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006374 if (!Op2)
6375 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6376 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006377 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006378 }
Chris Lattner6970b662005-04-23 15:31:55 +00006379 break;
6380 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006381 case Instruction::Call:
6382 // If we have (malloc != null), and if the malloc has a single use, we
6383 // can assume it is successful and remove the malloc.
6384 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6385 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006386 // Need to explicitly erase malloc call here, instead of adding it to
6387 // Worklist, because it won't get DCE'd from the Worklist since
6388 // isInstructionTriviallyDead() returns false for function calls.
6389 // It is OK to replace LHSI/MallocCall with Undef because the
6390 // instruction that uses it will be erased via Worklist.
6391 if (extractMallocCall(LHSI)) {
6392 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6393 EraseInstFromFunction(*LHSI);
6394 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006395 ConstantInt::get(Type::getInt1Ty(*Context),
6396 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006397 }
6398 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6399 if (MallocCall->hasOneUse()) {
6400 MallocCall->replaceAllUsesWith(
6401 UndefValue::get(MallocCall->getType()));
6402 EraseInstFromFunction(*MallocCall);
6403 Worklist.Add(LHSI); // The malloc's bitcast use.
6404 return ReplaceInstUsesWith(I,
6405 ConstantInt::get(Type::getInt1Ty(*Context),
6406 !I.isTrueWhenEqual()));
6407 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006408 }
6409 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006410 }
Chris Lattner6970b662005-04-23 15:31:55 +00006411 }
6412
Reid Spencere4d87aa2006-12-23 06:05:41 +00006413 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006414 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006415 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006416 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006417 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006418 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6419 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006420 return NI;
6421
Reid Spencere4d87aa2006-12-23 06:05:41 +00006422 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006423 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6424 // now.
6425 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6426 if (isa<PointerType>(Op0->getType()) &&
6427 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006428 // We keep moving the cast from the left operand over to the right
6429 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006430 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006431
Chris Lattner57d86372007-01-06 01:45:59 +00006432 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6433 // so eliminate it as well.
6434 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6435 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006436
Chris Lattnerde90b762003-11-03 04:25:02 +00006437 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006438 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006439 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006440 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006441 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006442 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006443 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006444 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006445 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006446 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006447 }
Chris Lattner57d86372007-01-06 01:45:59 +00006448 }
6449
6450 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006451 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006452 // This comes up when you have code like
6453 // int X = A < B;
6454 // if (X) ...
6455 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006456 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006457 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006458 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006459 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006460 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006461
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006462 // See if it's the same type of instruction on the left and right.
6463 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6464 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006465 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006466 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006467 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006468 default: break;
6469 case Instruction::Add:
6470 case Instruction::Sub:
6471 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006472 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006473 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006474 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006475 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6476 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6477 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006478 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006479 ? I.getUnsignedPredicate()
6480 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006481 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006482 Op1I->getOperand(0));
6483 }
6484
6485 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006486 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006487 ? I.getUnsignedPredicate()
6488 : I.getSignedPredicate();
6489 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006490 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006491 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006492 }
6493 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006494 break;
6495 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006496 if (!I.isEquality())
6497 break;
6498
Nick Lewycky5d52c452008-08-21 05:56:10 +00006499 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6500 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6501 // Mask = -1 >> count-trailing-zeros(Cst).
6502 if (!CI->isZero() && !CI->isOne()) {
6503 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006504 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006505 APInt::getLowBitsSet(AP.getBitWidth(),
6506 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006507 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006508 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6509 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006510 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006511 }
6512 }
6513 break;
6514 }
6515 }
6516 }
6517 }
6518
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006519 // ~x < ~y --> y < x
6520 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006521 if (match(Op0, m_Not(m_Value(A))) &&
6522 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006523 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006524 }
6525
Chris Lattner65b72ba2006-09-18 04:22:48 +00006526 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006527 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006528
6529 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006530 if (match(Op0, m_Neg(m_Value(A))) &&
6531 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006532 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006533
Dan Gohman4ae51262009-08-12 16:23:25 +00006534 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006535 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6536 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006537 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006538 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006539 }
6540
Dan Gohman4ae51262009-08-12 16:23:25 +00006541 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006542 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006543 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006544 if (match(B, m_ConstantInt(C1)) &&
6545 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006546 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006547 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006548 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6549 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006550 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006551
6552 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006553 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6554 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6555 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6556 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006557 }
6558 }
6559
Dan Gohman4ae51262009-08-12 16:23:25 +00006560 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006561 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006562 // A == (A^B) -> B == 0
6563 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006564 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006565 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006566 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006567
6568 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006569 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006570 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006571 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006572
6573 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006574 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006575 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006576 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006577
Chris Lattner9c2328e2006-11-14 06:06:06 +00006578 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6579 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006580 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6581 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006582 Value *X = 0, *Y = 0, *Z = 0;
6583
6584 if (A == C) {
6585 X = B; Y = D; Z = A;
6586 } else if (A == D) {
6587 X = B; Y = C; Z = A;
6588 } else if (B == C) {
6589 X = A; Y = D; Z = B;
6590 } else if (B == D) {
6591 X = A; Y = C; Z = B;
6592 }
6593
6594 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006595 Op1 = Builder->CreateXor(X, Y, "tmp");
6596 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006597 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006598 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006599 return &I;
6600 }
6601 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006602 }
Chris Lattner7e708292002-06-25 16:13:24 +00006603 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006604}
6605
Chris Lattner562ef782007-06-20 23:46:26 +00006606
6607/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6608/// and CmpRHS are both known to be integer constants.
6609Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6610 ConstantInt *DivRHS) {
6611 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6612 const APInt &CmpRHSV = CmpRHS->getValue();
6613
6614 // FIXME: If the operand types don't match the type of the divide
6615 // then don't attempt this transform. The code below doesn't have the
6616 // logic to deal with a signed divide and an unsigned compare (and
6617 // vice versa). This is because (x /s C1) <s C2 produces different
6618 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6619 // (x /u C1) <u C2. Simply casting the operands and result won't
6620 // work. :( The if statement below tests that condition and bails
6621 // if it finds it.
6622 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006623 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006624 return 0;
6625 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006626 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006627 if (DivIsSigned && DivRHS->isAllOnesValue())
6628 return 0; // The overflow computation also screws up here
6629 if (DivRHS->isOne())
6630 return 0; // Not worth bothering, and eliminates some funny cases
6631 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006632
6633 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6634 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6635 // C2 (CI). By solving for X we can turn this into a range check
6636 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006637 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006638
6639 // Determine if the product overflows by seeing if the product is
6640 // not equal to the divide. Make sure we do the same kind of divide
6641 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006642 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6643 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006644
6645 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006646 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006647
Chris Lattner1dbfd482007-06-21 18:11:19 +00006648 // Figure out the interval that is being checked. For example, a comparison
6649 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6650 // Compute this interval based on the constants involved and the signedness of
6651 // the compare/divide. This computes a half-open interval, keeping track of
6652 // whether either value in the interval overflows. After analysis each
6653 // overflow variable is set to 0 if it's corresponding bound variable is valid
6654 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6655 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006656 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006657
Chris Lattner562ef782007-06-20 23:46:26 +00006658 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006659 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006660 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006661 HiOverflow = LoOverflow = ProdOV;
6662 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006663 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006664 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006665 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006666 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006667 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006668 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006669 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006670 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6671 HiOverflow = LoOverflow = ProdOV;
6672 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006673 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006674 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006675 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006676 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006677 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6678 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006679 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006680 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006681 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006682 true) ? -1 : 0;
6683 }
Chris Lattner562ef782007-06-20 23:46:26 +00006684 }
Dan Gohman76491272008-02-13 22:09:18 +00006685 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006686 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006687 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006688 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006689 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006690 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6691 HiOverflow = 1; // [INTMIN+1, overflow)
6692 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6693 }
Dan Gohman76491272008-02-13 22:09:18 +00006694 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006695 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006696 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006697 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006698 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006699 LoOverflow = AddWithOverflow(LoBound, HiBound,
6700 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006701 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006702 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6703 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006704 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006705 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006706 }
6707
Chris Lattner1dbfd482007-06-21 18:11:19 +00006708 // Dividing by a negative swaps the condition. LT <-> GT
6709 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006710 }
6711
6712 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006713 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006714 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006715 case ICmpInst::ICMP_EQ:
6716 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006717 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006718 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006719 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006720 ICmpInst::ICMP_UGE, X, LoBound);
6721 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006722 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006723 ICmpInst::ICMP_ULT, X, HiBound);
6724 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006725 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006726 case ICmpInst::ICMP_NE:
6727 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006728 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006729 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006730 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006731 ICmpInst::ICMP_ULT, X, LoBound);
6732 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006733 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006734 ICmpInst::ICMP_UGE, X, HiBound);
6735 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006736 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006737 case ICmpInst::ICMP_ULT:
6738 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006739 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006740 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006741 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006742 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006743 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006744 case ICmpInst::ICMP_UGT:
6745 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006746 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006747 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006748 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006749 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006750 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006751 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006752 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006753 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006754 }
6755}
6756
6757
Chris Lattner01deb9d2007-04-03 17:43:25 +00006758/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6759///
6760Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6761 Instruction *LHSI,
6762 ConstantInt *RHS) {
6763 const APInt &RHSV = RHS->getValue();
6764
6765 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006766 case Instruction::Trunc:
6767 if (ICI.isEquality() && LHSI->hasOneUse()) {
6768 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6769 // of the high bits truncated out of x are known.
6770 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6771 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6772 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6773 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6774 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6775
6776 // If all the high bits are known, we can do this xform.
6777 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6778 // Pull in the high bits from known-ones set.
6779 APInt NewRHS(RHS->getValue());
6780 NewRHS.zext(SrcBits);
6781 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006782 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006783 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006784 }
6785 }
6786 break;
6787
Duncan Sands0091bf22007-04-04 06:42:45 +00006788 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006789 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6790 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6791 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006792 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6793 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006794 Value *CompareVal = LHSI->getOperand(0);
6795
6796 // If the sign bit of the XorCST is not set, there is no change to
6797 // the operation, just stop using the Xor.
6798 if (!XorCST->getValue().isNegative()) {
6799 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006800 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006801 return &ICI;
6802 }
6803
6804 // Was the old condition true if the operand is positive?
6805 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6806
6807 // If so, the new one isn't.
6808 isTrueIfPositive ^= true;
6809
6810 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006811 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006812 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006813 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006814 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006815 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006816 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006817
6818 if (LHSI->hasOneUse()) {
6819 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6820 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6821 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006822 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006823 ? ICI.getUnsignedPredicate()
6824 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006825 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006826 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006827 }
6828
6829 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006830 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006831 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006832 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006833 ? ICI.getUnsignedPredicate()
6834 : ICI.getSignedPredicate();
6835 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006836 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006837 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006838 }
6839 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006840 }
6841 break;
6842 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6843 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6844 LHSI->getOperand(0)->hasOneUse()) {
6845 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6846
6847 // If the LHS is an AND of a truncating cast, we can widen the
6848 // and/compare to be the input width without changing the value
6849 // produced, eliminating a cast.
6850 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6851 // We can do this transformation if either the AND constant does not
6852 // have its sign bit set or if it is an equality comparison.
6853 // Extending a relational comparison when we're checking the sign
6854 // bit would not work.
6855 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006856 (ICI.isEquality() ||
6857 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858 uint32_t BitWidth =
6859 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6860 APInt NewCST = AndCST->getValue();
6861 NewCST.zext(BitWidth);
6862 APInt NewCI = RHSV;
6863 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006864 Value *NewAnd =
6865 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006866 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006867 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006868 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006869 }
6870 }
6871
6872 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6873 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6874 // happens a LOT in code produced by the C front-end, for bitfield
6875 // access.
6876 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6877 if (Shift && !Shift->isShift())
6878 Shift = 0;
6879
6880 ConstantInt *ShAmt;
6881 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6882 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6883 const Type *AndTy = AndCST->getType(); // Type of the and.
6884
6885 // We can fold this as long as we can't shift unknown bits
6886 // into the mask. This can only happen with signed shift
6887 // rights, as they sign-extend.
6888 if (ShAmt) {
6889 bool CanFold = Shift->isLogicalShift();
6890 if (!CanFold) {
6891 // To test for the bad case of the signed shr, see if any
6892 // of the bits shifted in could be tested after the mask.
6893 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6894 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6895
6896 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6897 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6898 AndCST->getValue()) == 0)
6899 CanFold = true;
6900 }
6901
6902 if (CanFold) {
6903 Constant *NewCst;
6904 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006905 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006906 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006907 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006908
6909 // Check to see if we are shifting out any of the bits being
6910 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006911 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006912 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006913 // If we shifted bits out, the fold is not going to work out.
6914 // As a special case, check to see if this means that the
6915 // result is always true or false now.
6916 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006917 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006918 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006919 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006920 } else {
6921 ICI.setOperand(1, NewCst);
6922 Constant *NewAndCST;
6923 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006924 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006925 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006926 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006927 LHSI->setOperand(1, NewAndCST);
6928 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006929 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006930 return &ICI;
6931 }
6932 }
6933 }
6934
6935 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6936 // preferable because it allows the C<<Y expression to be hoisted out
6937 // of a loop if Y is invariant and X is not.
6938 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006939 ICI.isEquality() && !Shift->isArithmeticShift() &&
6940 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006941 // Compute C << Y.
6942 Value *NS;
6943 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006944 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006945 } else {
6946 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006947 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006948 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006949
6950 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006951 Value *NewAnd =
6952 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006953
6954 ICI.setOperand(0, NewAnd);
6955 return &ICI;
6956 }
6957 }
6958 break;
6959
Chris Lattnera0141b92007-07-15 20:42:37 +00006960 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6961 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6962 if (!ShAmt) break;
6963
6964 uint32_t TypeBits = RHSV.getBitWidth();
6965
6966 // Check that the shift amount is in range. If not, don't perform
6967 // undefined shifts. When the shift is visited it will be
6968 // simplified.
6969 if (ShAmt->uge(TypeBits))
6970 break;
6971
6972 if (ICI.isEquality()) {
6973 // If we are comparing against bits always shifted out, the
6974 // comparison cannot succeed.
6975 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006976 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006977 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006978 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6979 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006980 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006981 return ReplaceInstUsesWith(ICI, Cst);
6982 }
6983
6984 if (LHSI->hasOneUse()) {
6985 // Otherwise strength reduce the shift into an and.
6986 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6987 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006988 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006989 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006990
Chris Lattner74381062009-08-30 07:44:24 +00006991 Value *And =
6992 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006993 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006994 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006995 }
6996 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006997
6998 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6999 bool TrueIfSigned = false;
7000 if (LHSI->hasOneUse() &&
7001 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7002 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007003 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007004 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007005 Value *And =
7006 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007007 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007008 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007009 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007010 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007011 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007012
7013 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007014 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007015 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007016 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007017 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007018
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007019 // Check that the shift amount is in range. If not, don't perform
7020 // undefined shifts. When the shift is visited it will be
7021 // simplified.
7022 uint32_t TypeBits = RHSV.getBitWidth();
7023 if (ShAmt->uge(TypeBits))
7024 break;
7025
7026 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007027
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007028 // If we are comparing against bits always shifted out, the
7029 // comparison cannot succeed.
7030 APInt Comp = RHSV << ShAmtVal;
7031 if (LHSI->getOpcode() == Instruction::LShr)
7032 Comp = Comp.lshr(ShAmtVal);
7033 else
7034 Comp = Comp.ashr(ShAmtVal);
7035
7036 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7037 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007038 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007039 return ReplaceInstUsesWith(ICI, Cst);
7040 }
7041
7042 // Otherwise, check to see if the bits shifted out are known to be zero.
7043 // If so, we can compare against the unshifted value:
7044 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007045 if (LHSI->hasOneUse() &&
7046 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007047 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007048 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007049 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007050 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007051
Evan Chengf30752c2008-04-23 00:38:06 +00007052 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007053 // Otherwise strength reduce the shift into an and.
7054 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007055 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007056
Chris Lattner74381062009-08-30 07:44:24 +00007057 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7058 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007059 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007060 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007061 }
7062 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007063 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007064
7065 case Instruction::SDiv:
7066 case Instruction::UDiv:
7067 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7068 // Fold this div into the comparison, producing a range check.
7069 // Determine, based on the divide type, what the range is being
7070 // checked. If there is an overflow on the low or high side, remember
7071 // it, otherwise compute the range [low, hi) bounding the new value.
7072 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007073 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7074 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7075 DivRHS))
7076 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007078
7079 case Instruction::Add:
7080 // Fold: icmp pred (add, X, C1), C2
7081
7082 if (!ICI.isEquality()) {
7083 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7084 if (!LHSC) break;
7085 const APInt &LHSV = LHSC->getValue();
7086
7087 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7088 .subtract(LHSV);
7089
Nick Lewycky4a134af2009-10-25 05:20:17 +00007090 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007091 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007092 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007093 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007094 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007095 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007096 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007097 }
7098 } else {
7099 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007100 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007101 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007102 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007103 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007104 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007105 }
7106 }
7107 }
7108 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007109 }
7110
7111 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7112 if (ICI.isEquality()) {
7113 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7114
7115 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7116 // the second operand is a constant, simplify a bit.
7117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7118 switch (BO->getOpcode()) {
7119 case Instruction::SRem:
7120 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7121 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7122 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7123 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007124 Value *NewRem =
7125 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7126 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007127 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007128 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007129 }
7130 }
7131 break;
7132 case Instruction::Add:
7133 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7134 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7135 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007136 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007137 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007138 } else if (RHSV == 0) {
7139 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7140 // efficiently invertible, or if the add has just this one use.
7141 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7142
Dan Gohman186a6362009-08-12 16:04:34 +00007143 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007144 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007145 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007146 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007147 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007148 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007150 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007151 }
7152 }
7153 break;
7154 case Instruction::Xor:
7155 // For the xor case, we can xor two constants together, eliminating
7156 // the explicit xor.
7157 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007158 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007159 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007160
7161 // FALLTHROUGH
7162 case Instruction::Sub:
7163 // Replace (([sub|xor] A, B) != 0) with (A != B)
7164 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007165 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007166 BO->getOperand(1));
7167 break;
7168
7169 case Instruction::Or:
7170 // If bits are being or'd in that are not present in the constant we
7171 // are comparing against, then the comparison could never succeed!
7172 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007173 Constant *NotCI = ConstantExpr::getNot(RHS);
7174 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007175 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007176 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007177 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007178 }
7179 break;
7180
7181 case Instruction::And:
7182 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7183 // If bits are being compared against that are and'd out, then the
7184 // comparison can never succeed!
7185 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007186 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007187 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007188 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007189
7190 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7191 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007192 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007193 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007194 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007195
7196 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007197 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007198 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007199 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007200 ICmpInst::Predicate pred = isICMP_NE ?
7201 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007202 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007203 }
7204
7205 // ((X & ~7) == 0) --> X < 8
7206 if (RHSV == 0 && isHighOnes(BOC)) {
7207 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007208 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007209 ICmpInst::Predicate pred = isICMP_NE ?
7210 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007211 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007212 }
7213 }
7214 default: break;
7215 }
7216 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7217 // Handle icmp {eq|ne} <intrinsic>, intcst.
7218 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007219 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007220 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007221 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007222 return &ICI;
7223 }
7224 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007225 }
7226 return 0;
7227}
7228
7229/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7230/// We only handle extending casts so far.
7231///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007232Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7233 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007234 Value *LHSCIOp = LHSCI->getOperand(0);
7235 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007236 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007237 Value *RHSCIOp;
7238
Chris Lattner8c756c12007-05-05 22:41:33 +00007239 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7240 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007241 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7242 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007243 cast<IntegerType>(DestTy)->getBitWidth()) {
7244 Value *RHSOp = 0;
7245 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007246 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007247 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7248 RHSOp = RHSC->getOperand(0);
7249 // If the pointer types don't match, insert a bitcast.
7250 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007251 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007252 }
7253
7254 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007255 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007256 }
7257
7258 // The code below only handles extension cast instructions, so far.
7259 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007260 if (LHSCI->getOpcode() != Instruction::ZExt &&
7261 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007262 return 0;
7263
Reid Spencere4d87aa2006-12-23 06:05:41 +00007264 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007265 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007266
Reid Spencere4d87aa2006-12-23 06:05:41 +00007267 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007268 // Not an extension from the same type?
7269 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007270 if (RHSCIOp->getType() != LHSCIOp->getType())
7271 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007272
Nick Lewycky4189a532008-01-28 03:48:02 +00007273 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007274 // and the other is a zext), then we can't handle this.
7275 if (CI->getOpcode() != LHSCI->getOpcode())
7276 return 0;
7277
Nick Lewycky4189a532008-01-28 03:48:02 +00007278 // Deal with equality cases early.
7279 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007280 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007281
7282 // A signed comparison of sign extended values simplifies into a
7283 // signed comparison.
7284 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007285 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007286
7287 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007288 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007289 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007290
Reid Spencere4d87aa2006-12-23 06:05:41 +00007291 // If we aren't dealing with a constant on the RHS, exit early
7292 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7293 if (!CI)
7294 return 0;
7295
7296 // Compute the constant that would happen if we truncated to SrcTy then
7297 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007298 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7299 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007300 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007301
7302 // If the re-extended constant didn't change...
7303 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007304 // Deal with equality cases early.
7305 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007306 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007307
7308 // A signed comparison of sign extended values simplifies into a
7309 // signed comparison.
7310 if (isSignedExt && isSignedCmp)
7311 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7312
7313 // The other three cases all fold into an unsigned comparison.
7314 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007315 }
7316
7317 // The re-extended constant changed so the constant cannot be represented
7318 // in the shorter type. Consequently, we cannot emit a simple comparison.
7319
7320 // First, handle some easy cases. We know the result cannot be equal at this
7321 // point so handle the ICI.isEquality() cases
7322 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007323 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007324 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007325 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007326
7327 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7328 // should have been folded away previously and not enter in here.
7329 Value *Result;
7330 if (isSignedCmp) {
7331 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007332 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007333 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007334 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007335 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007336 } else {
7337 // We're performing an unsigned comparison.
7338 if (isSignedExt) {
7339 // We're performing an unsigned comp with a sign extended value.
7340 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007341 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007342 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007343 } else {
7344 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007345 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007346 }
7347 }
7348
7349 // Finally, return the value computed.
7350 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007351 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007352 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007353
7354 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7355 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7356 "ICmp should be folded!");
7357 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007358 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007359 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007360}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007361
Reid Spencer832254e2007-02-02 02:16:23 +00007362Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7363 return commonShiftTransforms(I);
7364}
7365
7366Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7367 return commonShiftTransforms(I);
7368}
7369
7370Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007371 if (Instruction *R = commonShiftTransforms(I))
7372 return R;
7373
7374 Value *Op0 = I.getOperand(0);
7375
7376 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7377 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7378 if (CSI->isAllOnesValue())
7379 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007380
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007381 // See if we can turn a signed shr into an unsigned shr.
7382 if (MaskedValueIsZero(Op0,
7383 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7384 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7385
7386 // Arithmetic shifting an all-sign-bit value is a no-op.
7387 unsigned NumSignBits = ComputeNumSignBits(Op0);
7388 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7389 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007390
Chris Lattner348f6652007-12-06 01:59:46 +00007391 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007392}
7393
7394Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7395 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007396 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007397
7398 // shl X, 0 == X and shr X, 0 == X
7399 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007400 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7401 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007402 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007403
Reid Spencere4d87aa2006-12-23 06:05:41 +00007404 if (isa<UndefValue>(Op0)) {
7405 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007406 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007407 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007408 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007409 }
7410 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007411 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7412 return ReplaceInstUsesWith(I, Op0);
7413 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007415 }
7416
Dan Gohman9004c8a2009-05-21 02:28:33 +00007417 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007418 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007419 return &I;
7420
Chris Lattner2eefe512004-04-09 19:05:30 +00007421 // Try to fold constant and into select arguments.
7422 if (isa<Constant>(Op0))
7423 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007424 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007425 return R;
7426
Reid Spencerb83eb642006-10-20 07:07:24 +00007427 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007428 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7429 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007430 return 0;
7431}
7432
Reid Spencerb83eb642006-10-20 07:07:24 +00007433Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007434 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007435 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007436
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007437 // See if we can simplify any instructions used by the instruction whose sole
7438 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007439 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007440
Dan Gohmana119de82009-06-14 23:30:43 +00007441 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7442 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007443 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007444 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007445 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007446 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007447 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007448 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007449 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007450 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007451 }
7452
7453 // ((X*C1) << C2) == (X * (C1 << C2))
7454 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7455 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7456 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007457 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007458 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007459
7460 // Try to fold constant and into select arguments.
7461 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7462 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7463 return R;
7464 if (isa<PHINode>(Op0))
7465 if (Instruction *NV = FoldOpIntoPhi(I))
7466 return NV;
7467
Chris Lattner8999dd32007-12-22 09:07:47 +00007468 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7469 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7470 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7471 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7472 // place. Don't try to do this transformation in this case. Also, we
7473 // require that the input operand is a shift-by-constant so that we have
7474 // confidence that the shifts will get folded together. We could do this
7475 // xform in more cases, but it is unlikely to be profitable.
7476 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7477 isa<ConstantInt>(TrOp->getOperand(1))) {
7478 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007479 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007480 // (shift2 (shift1 & 0x00FF), c2)
7481 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007482
7483 // For logical shifts, the truncation has the effect of making the high
7484 // part of the register be zeros. Emulate this by inserting an AND to
7485 // clear the top bits as needed. This 'and' will usually be zapped by
7486 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007487 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7488 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007489 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7490
7491 // The mask we constructed says what the trunc would do if occurring
7492 // between the shifts. We want to know the effect *after* the second
7493 // shift. We know that it is a logical shift by a constant, so adjust the
7494 // mask as appropriate.
7495 if (I.getOpcode() == Instruction::Shl)
7496 MaskV <<= Op1->getZExtValue();
7497 else {
7498 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7499 MaskV = MaskV.lshr(Op1->getZExtValue());
7500 }
7501
Chris Lattner74381062009-08-30 07:44:24 +00007502 // shift1 & 0x00FF
7503 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7504 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007505
7506 // Return the value truncated to the interesting size.
7507 return new TruncInst(And, I.getType());
7508 }
7509 }
7510
Chris Lattner4d5542c2006-01-06 07:12:35 +00007511 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007512 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7513 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7514 Value *V1, *V2;
7515 ConstantInt *CC;
7516 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007517 default: break;
7518 case Instruction::Add:
7519 case Instruction::And:
7520 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007521 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007522 // These operators commute.
7523 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007524 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007525 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007526 m_Specific(Op1)))) {
7527 Value *YS = // (Y << C)
7528 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7529 // (X + (Y << C))
7530 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7531 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007532 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007533 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007534 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007535 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007536
Chris Lattner150f12a2005-09-18 06:30:59 +00007537 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007538 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007539 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007540 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007541 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007542 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007543 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007544 Value *YS = // (Y << C)
7545 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7546 Op0BO->getName());
7547 // X & (CC << C)
7548 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7549 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007550 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007551 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007552 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007553
Reid Spencera07cb7d2007-02-02 14:41:37 +00007554 // FALL THROUGH.
7555 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007556 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007557 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007558 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007559 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007560 Value *YS = // (Y << C)
7561 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7562 // (X + (Y << C))
7563 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7564 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007565 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007566 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007567 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007568 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007569
Chris Lattner13d4ab42006-05-31 21:14:00 +00007570 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007571 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7572 match(Op0BO->getOperand(0),
7573 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007574 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007575 cast<BinaryOperator>(Op0BO->getOperand(0))
7576 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007577 Value *YS = // (Y << C)
7578 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7579 // X & (CC << C)
7580 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7581 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007582
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007583 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007584 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007585
Chris Lattner11021cb2005-09-18 05:12:10 +00007586 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007587 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007588 }
7589
7590
7591 // If the operand is an bitwise operator with a constant RHS, and the
7592 // shift is the only use, we can pull it out of the shift.
7593 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7594 bool isValid = true; // Valid only for And, Or, Xor
7595 bool highBitSet = false; // Transform if high bit of constant set?
7596
7597 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007598 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007599 case Instruction::Add:
7600 isValid = isLeftShift;
7601 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007602 case Instruction::Or:
7603 case Instruction::Xor:
7604 highBitSet = false;
7605 break;
7606 case Instruction::And:
7607 highBitSet = true;
7608 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007609 }
7610
7611 // If this is a signed shift right, and the high bit is modified
7612 // by the logical operation, do not perform the transformation.
7613 // The highBitSet boolean indicates the value of the high bit of
7614 // the constant which would cause it to be modified for this
7615 // operation.
7616 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007617 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007618 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007619
7620 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007621 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007622
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007623 Value *NewShift =
7624 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007625 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007626
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007627 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007628 NewRHS);
7629 }
7630 }
7631 }
7632 }
7633
Chris Lattnerad0124c2006-01-06 07:52:12 +00007634 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007635 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7636 if (ShiftOp && !ShiftOp->isShift())
7637 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007638
Reid Spencerb83eb642006-10-20 07:07:24 +00007639 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007640 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007641 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7642 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007643 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7644 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7645 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007646
Zhou Sheng4351c642007-04-02 08:20:41 +00007647 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648
7649 const IntegerType *Ty = cast<IntegerType>(I.getType());
7650
7651 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007652 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007653 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7654 // saturates.
7655 if (AmtSum >= TypeBits) {
7656 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007657 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007658 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7659 }
7660
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007661 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007662 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007663 }
7664
7665 if (ShiftOp->getOpcode() == Instruction::LShr &&
7666 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007667 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007668 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007669
Chris Lattnerb87056f2007-02-05 00:57:54 +00007670 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007671 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007672 }
7673
7674 if (ShiftOp->getOpcode() == Instruction::AShr &&
7675 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007676 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007677 if (AmtSum >= TypeBits)
7678 AmtSum = TypeBits-1;
7679
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007680 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007681
Zhou Shenge9e03f62007-03-28 15:02:20 +00007682 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007683 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007684 }
7685
Chris Lattnerb87056f2007-02-05 00:57:54 +00007686 // Okay, if we get here, one shift must be left, and the other shift must be
7687 // right. See if the amounts are equal.
7688 if (ShiftAmt1 == ShiftAmt2) {
7689 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7690 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007691 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007692 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007693 }
7694 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7695 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007696 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007697 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007698 }
7699 // We can simplify ((X << C) >>s C) into a trunc + sext.
7700 // NOTE: we could do this for any C, but that would make 'unusual' integer
7701 // types. For now, just stick to ones well-supported by the code
7702 // generators.
7703 const Type *SExtType = 0;
7704 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007705 case 1 :
7706 case 8 :
7707 case 16 :
7708 case 32 :
7709 case 64 :
7710 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007711 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007712 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007713 default: break;
7714 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007715 if (SExtType)
7716 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007717 // Otherwise, we can't handle it yet.
7718 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007719 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007720
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007721 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007722 if (I.getOpcode() == Instruction::Shl) {
7723 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7724 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007725 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007726
Reid Spencer55702aa2007-03-25 21:11:44 +00007727 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007728 return BinaryOperator::CreateAnd(Shift,
7729 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007730 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007731
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007732 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007733 if (I.getOpcode() == Instruction::LShr) {
7734 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007735 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007736
Reid Spencerd5e30f02007-03-26 17:18:58 +00007737 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007738 return BinaryOperator::CreateAnd(Shift,
7739 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007740 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007741
7742 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7743 } else {
7744 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007745 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007746
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007747 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007748 if (I.getOpcode() == Instruction::Shl) {
7749 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7750 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007751 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7752 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007753
Reid Spencer55702aa2007-03-25 21:11:44 +00007754 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007755 return BinaryOperator::CreateAnd(Shift,
7756 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007757 }
7758
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007759 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007760 if (I.getOpcode() == Instruction::LShr) {
7761 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007762 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007763
Reid Spencer68d27cf2007-03-26 23:45:51 +00007764 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007765 return BinaryOperator::CreateAnd(Shift,
7766 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007767 }
7768
7769 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007770 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007771 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007772 return 0;
7773}
7774
Chris Lattnera1be5662002-05-02 17:06:02 +00007775
Chris Lattnercfd65102005-10-29 04:36:15 +00007776/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7777/// expression. If so, decompose it, returning some value X, such that Val is
7778/// X*Scale+Offset.
7779///
7780static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007781 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007782 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7783 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007784 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007785 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007786 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007787 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007788 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7789 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7790 if (I->getOpcode() == Instruction::Shl) {
7791 // This is a value scaled by '1 << the shift amt'.
7792 Scale = 1U << RHS->getZExtValue();
7793 Offset = 0;
7794 return I->getOperand(0);
7795 } else if (I->getOpcode() == Instruction::Mul) {
7796 // This value is scaled by 'RHS'.
7797 Scale = RHS->getZExtValue();
7798 Offset = 0;
7799 return I->getOperand(0);
7800 } else if (I->getOpcode() == Instruction::Add) {
7801 // We have X+C. Check to see if we really have (X*C2)+C1,
7802 // where C1 is divisible by C2.
7803 unsigned SubScale;
7804 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007805 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7806 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007807 Offset += RHS->getZExtValue();
7808 Scale = SubScale;
7809 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007810 }
7811 }
7812 }
7813
7814 // Otherwise, we can't look past this.
7815 Scale = 1;
7816 Offset = 0;
7817 return Val;
7818}
7819
7820
Chris Lattnerb3f83972005-10-24 06:03:58 +00007821/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7822/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007823Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007824 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007825 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007826
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007827 BuilderTy AllocaBuilder(*Builder);
7828 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7829
Chris Lattnerb53c2382005-10-24 06:22:12 +00007830 // Remove any uses of AI that are dead.
7831 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007832
Chris Lattnerb53c2382005-10-24 06:22:12 +00007833 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7834 Instruction *User = cast<Instruction>(*UI++);
7835 if (isInstructionTriviallyDead(User)) {
7836 while (UI != E && *UI == User)
7837 ++UI; // If this instruction uses AI more than once, don't break UI.
7838
Chris Lattnerb53c2382005-10-24 06:22:12 +00007839 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007840 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007841 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007842 }
7843 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007844
7845 // This requires TargetData to get the alloca alignment and size information.
7846 if (!TD) return 0;
7847
Chris Lattnerb3f83972005-10-24 06:03:58 +00007848 // Get the type really allocated and the type casted to.
7849 const Type *AllocElTy = AI.getAllocatedType();
7850 const Type *CastElTy = PTy->getElementType();
7851 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007852
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007853 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7854 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007855 if (CastElTyAlign < AllocElTyAlign) return 0;
7856
Chris Lattner39387a52005-10-24 06:35:18 +00007857 // If the allocation has multiple uses, only promote it if we are strictly
7858 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007859 // same, we open the door to infinite loops of various kinds. (A reference
7860 // from a dbg.declare doesn't count as a use for this purpose.)
7861 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7862 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007863
Duncan Sands777d2302009-05-09 07:06:46 +00007864 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7865 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007866 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007867
Chris Lattner455fcc82005-10-29 03:19:53 +00007868 // See if we can satisfy the modulus by pulling a scale out of the array
7869 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007870 unsigned ArraySizeScale;
7871 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007872 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007873 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7874 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007875
Chris Lattner455fcc82005-10-29 03:19:53 +00007876 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7877 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007878 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7879 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007880
Chris Lattner455fcc82005-10-29 03:19:53 +00007881 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7882 Value *Amt = 0;
7883 if (Scale == 1) {
7884 Amt = NumElements;
7885 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007886 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007887 // Insert before the alloca, not before the cast.
7888 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007889 }
7890
Jeff Cohen86796be2007-04-04 16:58:57 +00007891 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007892 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007893 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007894 }
7895
Victor Hernandez7b929da2009-10-23 21:09:37 +00007896 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007897 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007898 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007899
Dale Johannesena0a66372009-03-05 00:39:02 +00007900 // If the allocation has one real use plus a dbg.declare, just remove the
7901 // declare.
7902 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7903 EraseInstFromFunction(*DI);
7904 }
7905 // If the allocation has multiple real uses, insert a cast and change all
7906 // things that used it to use the new cast. This will also hack on CI, but it
7907 // will die soon.
7908 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007909 // New is the allocation instruction, pointer typed. AI is the original
7910 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007911 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007912 AI.replaceAllUsesWith(NewCast);
7913 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007914 return ReplaceInstUsesWith(CI, New);
7915}
7916
Chris Lattner70074e02006-05-13 02:06:03 +00007917/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007918/// and return it as type Ty without inserting any new casts and without
7919/// changing the computed value. This is used by code that tries to decide
7920/// whether promoting or shrinking integer operations to wider or smaller types
7921/// will allow us to eliminate a truncate or extend.
7922///
7923/// This is a truncation operation if Ty is smaller than V->getType(), or an
7924/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007925///
7926/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7927/// should return true if trunc(V) can be computed by computing V in the smaller
7928/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7929/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7930/// efficiently truncated.
7931///
7932/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7933/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7934/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007935bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007936 unsigned CastOpc,
7937 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007938 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007939 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007941
7942 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007943 if (!I) return false;
7944
Dan Gohman6de29f82009-06-15 22:12:54 +00007945 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007946
Chris Lattner951626b2007-08-02 06:11:14 +00007947 // If this is an extension or truncate, we can often eliminate it.
7948 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7949 // If this is a cast from the destination type, we can trivially eliminate
7950 // it, and this will remove a cast overall.
7951 if (I->getOperand(0)->getType() == Ty) {
7952 // If the first operand is itself a cast, and is eliminable, do not count
7953 // this as an eliminable cast. We would prefer to eliminate those two
7954 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007955 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007956 ++NumCastsRemoved;
7957 return true;
7958 }
7959 }
7960
7961 // We can't extend or shrink something that has multiple uses: doing so would
7962 // require duplicating the instruction in general, which isn't profitable.
7963 if (!I->hasOneUse()) return false;
7964
Evan Chengf35fd542009-01-15 17:01:23 +00007965 unsigned Opc = I->getOpcode();
7966 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007967 case Instruction::Add:
7968 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007969 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007970 case Instruction::And:
7971 case Instruction::Or:
7972 case Instruction::Xor:
7973 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007974 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007975 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007976 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007977 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007978
Eli Friedman070a9812009-07-13 22:46:01 +00007979 case Instruction::UDiv:
7980 case Instruction::URem: {
7981 // UDiv and URem can be truncated if all the truncated bits are zero.
7982 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7983 uint32_t BitWidth = Ty->getScalarSizeInBits();
7984 if (BitWidth < OrigBitWidth) {
7985 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7986 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7987 MaskedValueIsZero(I->getOperand(1), Mask)) {
7988 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7989 NumCastsRemoved) &&
7990 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7991 NumCastsRemoved);
7992 }
7993 }
7994 break;
7995 }
Chris Lattner46b96052006-11-29 07:18:39 +00007996 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007997 // If we are truncating the result of this SHL, and if it's a shift of a
7998 // constant amount, we can always perform a SHL in a smaller type.
7999 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008000 uint32_t BitWidth = Ty->getScalarSizeInBits();
8001 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008002 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008003 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008004 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008005 }
8006 break;
8007 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008008 // If this is a truncate of a logical shr, we can truncate it to a smaller
8009 // lshr iff we know that the bits we would otherwise be shifting in are
8010 // already zeros.
8011 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008012 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8013 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008014 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008015 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008016 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8017 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008018 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008019 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008020 }
8021 }
Chris Lattner46b96052006-11-29 07:18:39 +00008022 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008023 case Instruction::ZExt:
8024 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008025 case Instruction::Trunc:
8026 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008027 // can safely replace it. Note that replacing it does not reduce the number
8028 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008029 if (Opc == CastOpc)
8030 return true;
8031
8032 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008033 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008034 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008035 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008036 case Instruction::Select: {
8037 SelectInst *SI = cast<SelectInst>(I);
8038 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008039 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008040 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008041 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008042 }
Chris Lattner8114b712008-06-18 04:00:49 +00008043 case Instruction::PHI: {
8044 // We can change a phi if we can change all operands.
8045 PHINode *PN = cast<PHINode>(I);
8046 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8047 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008048 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008049 return false;
8050 return true;
8051 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008052 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008053 // TODO: Can handle more cases here.
8054 break;
8055 }
8056
8057 return false;
8058}
8059
8060/// EvaluateInDifferentType - Given an expression that
8061/// CanEvaluateInDifferentType returns true for, actually insert the code to
8062/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008063Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008064 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008065 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008066 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008067
8068 // Otherwise, it must be an instruction.
8069 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008070 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008071 unsigned Opc = I->getOpcode();
8072 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008073 case Instruction::Add:
8074 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008075 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008076 case Instruction::And:
8077 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008078 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008079 case Instruction::AShr:
8080 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008081 case Instruction::Shl:
8082 case Instruction::UDiv:
8083 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008084 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008085 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008086 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008087 break;
8088 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008089 case Instruction::Trunc:
8090 case Instruction::ZExt:
8091 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008092 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008093 // just return the source. There's no need to insert it because it is not
8094 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008095 if (I->getOperand(0)->getType() == Ty)
8096 return I->getOperand(0);
8097
Chris Lattner8114b712008-06-18 04:00:49 +00008098 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008099 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008100 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008101 case Instruction::Select: {
8102 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8103 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8104 Res = SelectInst::Create(I->getOperand(0), True, False);
8105 break;
8106 }
Chris Lattner8114b712008-06-18 04:00:49 +00008107 case Instruction::PHI: {
8108 PHINode *OPN = cast<PHINode>(I);
8109 PHINode *NPN = PHINode::Create(Ty);
8110 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8111 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8112 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8113 }
8114 Res = NPN;
8115 break;
8116 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008117 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008118 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008119 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008120 break;
8121 }
8122
Chris Lattner8114b712008-06-18 04:00:49 +00008123 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008124 return InsertNewInstBefore(Res, *I);
8125}
8126
Reid Spencer3da59db2006-11-27 01:05:10 +00008127/// @brief Implement the transforms common to all CastInst visitors.
8128Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008129 Value *Src = CI.getOperand(0);
8130
Dan Gohman23d9d272007-05-11 21:10:54 +00008131 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008132 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008133 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008134 if (Instruction::CastOps opc =
8135 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8136 // The first cast (CSrc) is eliminable so we need to fix up or replace
8137 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008138 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008139 }
8140 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008141
Reid Spencer3da59db2006-11-27 01:05:10 +00008142 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008143 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8144 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8145 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008146
8147 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008148 if (isa<PHINode>(Src)) {
8149 // We don't do this if this would create a PHI node with an illegal type if
8150 // it is currently legal.
8151 if (!isa<IntegerType>(Src->getType()) ||
8152 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008153 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008154 if (Instruction *NV = FoldOpIntoPhi(CI))
8155 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008156 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008157
Reid Spencer3da59db2006-11-27 01:05:10 +00008158 return 0;
8159}
8160
Chris Lattner46cd5a12009-01-09 05:44:56 +00008161/// FindElementAtOffset - Given a type and a constant offset, determine whether
8162/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008163/// the specified offset. If so, fill them into NewIndices and return the
8164/// resultant element type, otherwise return null.
8165static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8166 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008167 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008168 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008169 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008170 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008171
8172 // Start with the index over the outer type. Note that the type size
8173 // might be zero (even if the offset isn't zero) if the indexed type
8174 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008175 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008176 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008177 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008178 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008179 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008180
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008181 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008182 if (Offset < 0) {
8183 --FirstIdx;
8184 Offset += TySize;
8185 assert(Offset >= 0);
8186 }
8187 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8188 }
8189
Owen Andersoneed707b2009-07-24 23:12:02 +00008190 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008191
8192 // Index into the types. If we fail, set OrigBase to null.
8193 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008194 // Indexing into tail padding between struct/array elements.
8195 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008196 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008197
Chris Lattner46cd5a12009-01-09 05:44:56 +00008198 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8199 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008200 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8201 "Offset must stay within the indexed type");
8202
Chris Lattner46cd5a12009-01-09 05:44:56 +00008203 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008204 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008205
8206 Offset -= SL->getElementOffset(Elt);
8207 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008208 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008209 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008210 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008211 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008212 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008213 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008214 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008215 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008216 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008217 }
8218 }
8219
Chris Lattner3914f722009-01-24 01:00:13 +00008220 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008221}
8222
Chris Lattnerd3e28342007-04-27 17:44:50 +00008223/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8224Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8225 Value *Src = CI.getOperand(0);
8226
Chris Lattnerd3e28342007-04-27 17:44:50 +00008227 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008228 // If casting the result of a getelementptr instruction with no offset, turn
8229 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008230 if (GEP->hasAllZeroIndices()) {
8231 // Changing the cast operand is usually not a good idea but it is safe
8232 // here because the pointer operand is being replaced with another
8233 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008234 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008235 CI.setOperand(0, GEP->getOperand(0));
8236 return &CI;
8237 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008238
8239 // If the GEP has a single use, and the base pointer is a bitcast, and the
8240 // GEP computes a constant offset, see if we can convert these three
8241 // instructions into fewer. This typically happens with unions and other
8242 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008243 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008244 if (GEP->hasAllConstantIndices()) {
8245 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008246 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008247 int64_t Offset = OffsetV->getSExtValue();
8248
8249 // Get the base pointer input of the bitcast, and the type it points to.
8250 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8251 const Type *GEPIdxTy =
8252 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008253 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008254 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008255 // If we were able to index down into an element, create the GEP
8256 // and bitcast the result. This eliminates one bitcast, potentially
8257 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008258 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8259 Builder->CreateInBoundsGEP(OrigBase,
8260 NewIndices.begin(), NewIndices.end()) :
8261 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008262 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008263
Chris Lattner46cd5a12009-01-09 05:44:56 +00008264 if (isa<BitCastInst>(CI))
8265 return new BitCastInst(NGEP, CI.getType());
8266 assert(isa<PtrToIntInst>(CI));
8267 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008268 }
8269 }
8270 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008271 }
8272
8273 return commonCastTransforms(CI);
8274}
8275
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008276/// commonIntCastTransforms - This function implements the common transforms
8277/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008278Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8279 if (Instruction *Result = commonCastTransforms(CI))
8280 return Result;
8281
8282 Value *Src = CI.getOperand(0);
8283 const Type *SrcTy = Src->getType();
8284 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008285 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8286 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008287
Reid Spencer3da59db2006-11-27 01:05:10 +00008288 // See if we can simplify any instructions used by the LHS whose sole
8289 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008290 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008291 return &CI;
8292
8293 // If the source isn't an instruction or has more than one use then we
8294 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008295 Instruction *SrcI = dyn_cast<Instruction>(Src);
8296 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008297 return 0;
8298
Chris Lattnerc739cd62007-03-03 05:27:34 +00008299 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008300 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008301 // Only do this if the dest type is a simple type, don't convert the
8302 // expression tree to something weird like i93 unless the source is also
8303 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008304 if ((isa<VectorType>(DestTy) ||
8305 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8306 CanEvaluateInDifferentType(SrcI, DestTy,
8307 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008308 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008309 // eliminates the cast, so it is always a win. If this is a zero-extension,
8310 // we need to do an AND to maintain the clear top-part of the computation,
8311 // so we require that the input have eliminated at least one cast. If this
8312 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008313 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008314 bool DoXForm = false;
8315 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008316 switch (CI.getOpcode()) {
8317 default:
8318 // All the others use floating point so we shouldn't actually
8319 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008320 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008321 case Instruction::Trunc:
8322 DoXForm = true;
8323 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008324 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008325 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008326
Chris Lattner39c27ed2009-01-31 19:05:27 +00008327 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008328 // If it's unnecessary to issue an AND to clear the high bits, it's
8329 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008330 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008331 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8332 if (MaskedValueIsZero(TryRes, Mask))
8333 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008334
8335 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008336 if (TryI->use_empty())
8337 EraseInstFromFunction(*TryI);
8338 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008339 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008340 }
Evan Chengf35fd542009-01-15 17:01:23 +00008341 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008342 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008343 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008344 // If we do not have to emit the truncate + sext pair, then it's always
8345 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008346 //
8347 // It's not safe to eliminate the trunc + sext pair if one of the
8348 // eliminated cast is a truncate. e.g.
8349 // t2 = trunc i32 t1 to i16
8350 // t3 = sext i16 t2 to i32
8351 // !=
8352 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008353 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008354 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8355 if (NumSignBits > (DestBitSize - SrcBitSize))
8356 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008357
8358 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008359 if (TryI->use_empty())
8360 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008361 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008362 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008363 }
Evan Chengf35fd542009-01-15 17:01:23 +00008364 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008365
8366 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008367 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8368 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008369 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8370 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008371 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008372 // Just replace this cast with the result.
8373 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008374
Reid Spencer3da59db2006-11-27 01:05:10 +00008375 assert(Res->getType() == DestTy);
8376 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008377 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008378 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008379 // Just replace this cast with the result.
8380 return ReplaceInstUsesWith(CI, Res);
8381 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008383
8384 // If the high bits are already zero, just replace this cast with the
8385 // result.
8386 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8387 if (MaskedValueIsZero(Res, Mask))
8388 return ReplaceInstUsesWith(CI, Res);
8389
8390 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008391 Constant *C = ConstantInt::get(*Context,
8392 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008393 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008394 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008395 case Instruction::SExt: {
8396 // If the high bits are already filled with sign bit, just replace this
8397 // cast with the result.
8398 unsigned NumSignBits = ComputeNumSignBits(Res);
8399 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008400 return ReplaceInstUsesWith(CI, Res);
8401
Reid Spencer3da59db2006-11-27 01:05:10 +00008402 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008403 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008404 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008405 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008406 }
8407 }
8408
8409 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8410 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8411
8412 switch (SrcI->getOpcode()) {
8413 case Instruction::Add:
8414 case Instruction::Mul:
8415 case Instruction::And:
8416 case Instruction::Or:
8417 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008418 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008419 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8420 // Don't insert two casts unless at least one can be eliminated.
8421 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008422 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008423 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8424 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008425 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008426 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008427 }
8428 }
8429
8430 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8431 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8432 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008433 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008434 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008435 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008436 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008437 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008438 }
8439 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008440
Eli Friedman65445c52009-07-13 21:45:57 +00008441 case Instruction::Shl: {
8442 // Canonicalize trunc inside shl, if we can.
8443 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8444 if (CI && DestBitSize < SrcBitSize &&
8445 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008446 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8447 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008448 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008449 }
8450 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008451 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008452 }
8453 return 0;
8454}
8455
Chris Lattner8a9f5712007-04-11 06:57:46 +00008456Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008457 if (Instruction *Result = commonIntCastTransforms(CI))
8458 return Result;
8459
8460 Value *Src = CI.getOperand(0);
8461 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008462 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8463 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008464
8465 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008466 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008467 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008468 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008469 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008470 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008471 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008472
Chris Lattner4f9797d2009-03-24 18:15:30 +00008473 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8474 ConstantInt *ShAmtV = 0;
8475 Value *ShiftOp = 0;
8476 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008477 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008478 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8479
8480 // Get a mask for the bits shifting in.
8481 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8482 if (MaskedValueIsZero(ShiftOp, Mask)) {
8483 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008484 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008485
8486 // Okay, we can shrink this. Truncate the input, then return a new
8487 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008488 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008489 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008490 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008491 }
8492 }
Chris Lattner9956c052009-11-08 19:23:30 +00008493
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008494 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008495}
8496
Evan Chengb98a10e2008-03-24 00:21:34 +00008497/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8498/// in order to eliminate the icmp.
8499Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8500 bool DoXform) {
8501 // If we are just checking for a icmp eq of a single bit and zext'ing it
8502 // to an integer, then shift the bit to the appropriate place and then
8503 // cast to integer to avoid the comparison.
8504 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8505 const APInt &Op1CV = Op1C->getValue();
8506
8507 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8508 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8509 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8510 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8511 if (!DoXform) return ICI;
8512
8513 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008514 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008515 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008516 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008517 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008518 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008519
8520 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008521 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008522 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008523 }
8524
8525 return ReplaceInstUsesWith(CI, In);
8526 }
8527
8528
8529
8530 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8531 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8532 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8533 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8534 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8535 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8536 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8537 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8538 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8539 // This only works for EQ and NE
8540 ICI->isEquality()) {
8541 // If Op1C some other power of two, convert:
8542 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8543 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8544 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8545 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8546
8547 APInt KnownZeroMask(~KnownZero);
8548 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8549 if (!DoXform) return ICI;
8550
8551 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8552 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8553 // (X&4) == 2 --> false
8554 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008555 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008556 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008557 return ReplaceInstUsesWith(CI, Res);
8558 }
8559
8560 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8561 Value *In = ICI->getOperand(0);
8562 if (ShiftAmt) {
8563 // Perform a logical shr by shiftamt.
8564 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008565 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8566 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008567 }
8568
8569 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008570 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008571 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008572 }
8573
8574 if (CI.getType() == In->getType())
8575 return ReplaceInstUsesWith(CI, In);
8576 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008577 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008578 }
8579 }
8580 }
8581
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008582 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8583 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8584 // may lead to additional simplifications.
8585 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8586 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8587 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008588 Value *LHS = ICI->getOperand(0);
8589 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008590
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008591 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8592 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8593 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8594 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8595 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008596
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008597 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8598 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8599 APInt UnknownBit = ~KnownBits;
8600 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008601 if (!DoXform) return ICI;
8602
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008603 Value *Result = Builder->CreateXor(LHS, RHS);
8604
8605 // Mask off any bits that are set and won't be shifted away.
8606 if (KnownOneLHS.uge(UnknownBit))
8607 Result = Builder->CreateAnd(Result,
8608 ConstantInt::get(ITy, UnknownBit));
8609
8610 // Shift the bit we're testing down to the lsb.
8611 Result = Builder->CreateLShr(
8612 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8613
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008614 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008615 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8616 Result->takeName(ICI);
8617 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008618 }
8619 }
8620 }
8621 }
8622
Evan Chengb98a10e2008-03-24 00:21:34 +00008623 return 0;
8624}
8625
Chris Lattner8a9f5712007-04-11 06:57:46 +00008626Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008627 // If one of the common conversion will work ..
8628 if (Instruction *Result = commonIntCastTransforms(CI))
8629 return Result;
8630
8631 Value *Src = CI.getOperand(0);
8632
Chris Lattnera84f47c2009-02-17 20:47:23 +00008633 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8634 // types and if the sizes are just right we can convert this into a logical
8635 // 'and' which will be much cheaper than the pair of casts.
8636 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8637 // Get the sizes of the types involved. We know that the intermediate type
8638 // will be smaller than A or C, but don't know the relation between A and C.
8639 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008640 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8641 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8642 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008643 // If we're actually extending zero bits, then if
8644 // SrcSize < DstSize: zext(a & mask)
8645 // SrcSize == DstSize: a & mask
8646 // SrcSize > DstSize: trunc(a) & mask
8647 if (SrcSize < DstSize) {
8648 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008649 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008650 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008651 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008652 }
8653
8654 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008655 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008656 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008657 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008658 }
8659 if (SrcSize > DstSize) {
8660 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008661 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008662 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008663 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008664 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008665 }
8666 }
8667
Evan Chengb98a10e2008-03-24 00:21:34 +00008668 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8669 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008670
Evan Chengb98a10e2008-03-24 00:21:34 +00008671 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8672 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8673 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8674 // of the (zext icmp) will be transformed.
8675 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8676 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8677 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8678 (transformZExtICmp(LHS, CI, false) ||
8679 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008680 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8681 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008682 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008683 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008684 }
8685
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008686 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008687 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8688 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8689 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8690 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008691 if (TI0->getType() == CI.getType())
8692 return
8693 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008694 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008695 }
8696
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008697 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8698 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8699 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8700 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8701 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8702 And->getOperand(1) == C)
8703 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8704 Value *TI0 = TI->getOperand(0);
8705 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008706 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008707 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008708 return BinaryOperator::CreateXor(NewAnd, ZC);
8709 }
8710 }
8711
Reid Spencer3da59db2006-11-27 01:05:10 +00008712 return 0;
8713}
8714
Chris Lattner8a9f5712007-04-11 06:57:46 +00008715Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008716 if (Instruction *I = commonIntCastTransforms(CI))
8717 return I;
8718
Chris Lattner8a9f5712007-04-11 06:57:46 +00008719 Value *Src = CI.getOperand(0);
8720
Dan Gohman1975d032008-10-30 20:40:10 +00008721 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008722 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008723 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008724 Constant::getAllOnesValue(CI.getType()),
8725 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008726
8727 // See if the value being truncated is already sign extended. If so, just
8728 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008729 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008730 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008731 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8732 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8733 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008734 unsigned NumSignBits = ComputeNumSignBits(Op);
8735
8736 if (OpBits == DestBits) {
8737 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8738 // bits, it is already ready.
8739 if (NumSignBits > DestBits-MidBits)
8740 return ReplaceInstUsesWith(CI, Op);
8741 } else if (OpBits < DestBits) {
8742 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8743 // bits, just sext from i32.
8744 if (NumSignBits > OpBits-MidBits)
8745 return new SExtInst(Op, CI.getType(), "tmp");
8746 } else {
8747 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8748 // bits, just truncate to i32.
8749 if (NumSignBits > OpBits-MidBits)
8750 return new TruncInst(Op, CI.getType(), "tmp");
8751 }
8752 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008753
8754 // If the input is a shl/ashr pair of a same constant, then this is a sign
8755 // extension from a smaller value. If we could trust arbitrary bitwidth
8756 // integers, we could turn this into a truncate to the smaller bit and then
8757 // use a sext for the whole extension. Since we don't, look deeper and check
8758 // for a truncate. If the source and dest are the same type, eliminate the
8759 // trunc and extend and just do shifts. For example, turn:
8760 // %a = trunc i32 %i to i8
8761 // %b = shl i8 %a, 6
8762 // %c = ashr i8 %b, 6
8763 // %d = sext i8 %c to i32
8764 // into:
8765 // %a = shl i32 %i, 30
8766 // %d = ashr i32 %a, 30
8767 Value *A = 0;
8768 ConstantInt *BA = 0, *CA = 0;
8769 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008770 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008771 BA == CA && isa<TruncInst>(A)) {
8772 Value *I = cast<TruncInst>(A)->getOperand(0);
8773 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008774 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8775 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008776 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008777 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008778 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008779 return BinaryOperator::CreateAShr(I, ShAmtV);
8780 }
8781 }
8782
Chris Lattnerba417832007-04-11 06:12:58 +00008783 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008784}
8785
Chris Lattnerb7530652008-01-27 05:29:54 +00008786/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8787/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008788static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008789 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008790 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008791 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008792 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8793 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008794 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008795 return 0;
8796}
8797
8798/// LookThroughFPExtensions - If this is an fp extension instruction, look
8799/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008800static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008801 if (Instruction *I = dyn_cast<Instruction>(V))
8802 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008803 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008804
8805 // If this value is a constant, return the constant in the smallest FP type
8806 // that can accurately represent it. This allows us to turn
8807 // (float)((double)X+2.0) into x+2.0f.
8808 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008809 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008810 return V; // No constant folding of this.
8811 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008812 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008813 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008814 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008815 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008816 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008817 return V;
8818 // Don't try to shrink to various long double types.
8819 }
8820
8821 return V;
8822}
8823
8824Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8825 if (Instruction *I = commonCastTransforms(CI))
8826 return I;
8827
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008828 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008829 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008830 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008831 // many builtins (sqrt, etc).
8832 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8833 if (OpI && OpI->hasOneUse()) {
8834 switch (OpI->getOpcode()) {
8835 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008836 case Instruction::FAdd:
8837 case Instruction::FSub:
8838 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008839 case Instruction::FDiv:
8840 case Instruction::FRem:
8841 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008842 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8843 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008844 if (LHSTrunc->getType() != SrcTy &&
8845 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008846 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008847 // If the source types were both smaller than the destination type of
8848 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008849 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8850 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008851 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8852 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008853 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008854 }
8855 }
8856 break;
8857 }
8858 }
8859 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008860}
8861
8862Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8863 return commonCastTransforms(CI);
8864}
8865
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008866Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008867 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8868 if (OpI == 0)
8869 return commonCastTransforms(FI);
8870
8871 // fptoui(uitofp(X)) --> X
8872 // fptoui(sitofp(X)) --> X
8873 // This is safe if the intermediate type has enough bits in its mantissa to
8874 // accurately represent all values of X. For example, do not do this with
8875 // i64->float->i64. This is also safe for sitofp case, because any negative
8876 // 'X' value would cause an undefined result for the fptoui.
8877 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8878 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008879 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008880 OpI->getType()->getFPMantissaWidth())
8881 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008882
8883 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008884}
8885
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008886Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008887 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8888 if (OpI == 0)
8889 return commonCastTransforms(FI);
8890
8891 // fptosi(sitofp(X)) --> X
8892 // fptosi(uitofp(X)) --> X
8893 // This is safe if the intermediate type has enough bits in its mantissa to
8894 // accurately represent all values of X. For example, do not do this with
8895 // i64->float->i64. This is also safe for sitofp case, because any negative
8896 // 'X' value would cause an undefined result for the fptoui.
8897 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8898 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008899 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008900 OpI->getType()->getFPMantissaWidth())
8901 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008902
8903 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008904}
8905
8906Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8907 return commonCastTransforms(CI);
8908}
8909
8910Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8911 return commonCastTransforms(CI);
8912}
8913
Chris Lattnera0e69692009-03-24 18:35:40 +00008914Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8915 // If the destination integer type is smaller than the intptr_t type for
8916 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8917 // trunc to be exposed to other transforms. Don't do this for extending
8918 // ptrtoint's, because we don't know if the target sign or zero extends its
8919 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008920 if (TD &&
8921 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008922 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8923 TD->getIntPtrType(CI.getContext()),
8924 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008925 return new TruncInst(P, CI.getType());
8926 }
8927
Chris Lattnerd3e28342007-04-27 17:44:50 +00008928 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008929}
8930
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008931Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008932 // If the source integer type is larger than the intptr_t type for
8933 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8934 // allows the trunc to be exposed to other transforms. Don't do this for
8935 // extending inttoptr's, because we don't know if the target sign or zero
8936 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008937 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008938 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008939 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8940 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008941 return new IntToPtrInst(P, CI.getType());
8942 }
8943
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008944 if (Instruction *I = commonCastTransforms(CI))
8945 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008946
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008947 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008948}
8949
Chris Lattnerd3e28342007-04-27 17:44:50 +00008950Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008951 // If the operands are integer typed then apply the integer transforms,
8952 // otherwise just apply the common ones.
8953 Value *Src = CI.getOperand(0);
8954 const Type *SrcTy = Src->getType();
8955 const Type *DestTy = CI.getType();
8956
Eli Friedman7e25d452009-07-13 20:53:00 +00008957 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008958 if (Instruction *I = commonPointerCastTransforms(CI))
8959 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008960 } else {
8961 if (Instruction *Result = commonCastTransforms(CI))
8962 return Result;
8963 }
8964
8965
8966 // Get rid of casts from one type to the same type. These are useless and can
8967 // be replaced by the operand.
8968 if (DestTy == Src->getType())
8969 return ReplaceInstUsesWith(CI, Src);
8970
Reid Spencer3da59db2006-11-27 01:05:10 +00008971 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008972 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8973 const Type *DstElTy = DstPTy->getElementType();
8974 const Type *SrcElTy = SrcPTy->getElementType();
8975
Nate Begeman83ad90a2008-03-31 00:22:16 +00008976 // If the address spaces don't match, don't eliminate the bitcast, which is
8977 // required for changing types.
8978 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8979 return 0;
8980
Victor Hernandez83d63912009-09-18 22:35:49 +00008981 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008982 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008983 // There is no need to modify malloc calls because it is their bitcast that
8984 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008985 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008986 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8987 return V;
8988
Chris Lattnerd717c182007-05-05 22:32:24 +00008989 // If the source and destination are pointers, and this cast is equivalent
8990 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008991 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008992 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008993 unsigned NumZeros = 0;
8994 while (SrcElTy != DstElTy &&
8995 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8996 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8997 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8998 ++NumZeros;
8999 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009000
Chris Lattnerd3e28342007-04-27 17:44:50 +00009001 // If we found a path from the src to dest, create the getelementptr now.
9002 if (SrcElTy == DstElTy) {
9003 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009004 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9005 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009006 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009007 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009008
Eli Friedman2451a642009-07-18 23:06:53 +00009009 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9010 if (DestVTy->getNumElements() == 1) {
9011 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009012 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009013 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009014 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009015 }
9016 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9017 }
9018 }
9019
9020 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9021 if (SrcVTy->getNumElements() == 1) {
9022 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009023 Value *Elem =
9024 Builder->CreateExtractElement(Src,
9025 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009026 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9027 }
9028 }
9029 }
9030
Reid Spencer3da59db2006-11-27 01:05:10 +00009031 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9032 if (SVI->hasOneUse()) {
9033 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9034 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009035 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009036 cast<VectorType>(DestTy)->getNumElements() ==
9037 SVI->getType()->getNumElements() &&
9038 SVI->getType()->getNumElements() ==
9039 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009040 CastInst *Tmp;
9041 // If either of the operands is a cast from CI.getType(), then
9042 // evaluating the shuffle in the casted destination's type will allow
9043 // us to eliminate at least one cast.
9044 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9045 Tmp->getOperand(0)->getType() == DestTy) ||
9046 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9047 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009048 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9049 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009050 // Return a new shuffle vector. Use the same element ID's, as we
9051 // know the vector types match #elts.
9052 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009053 }
9054 }
9055 }
9056 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009057 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009058}
9059
Chris Lattnere576b912004-04-09 23:46:01 +00009060/// GetSelectFoldableOperands - We want to turn code that looks like this:
9061/// %C = or %A, %B
9062/// %D = select %cond, %C, %A
9063/// into:
9064/// %C = select %cond, %B, 0
9065/// %D = or %A, %C
9066///
9067/// Assuming that the specified instruction is an operand to the select, return
9068/// a bitmask indicating which operands of this instruction are foldable if they
9069/// equal the other incoming value of the select.
9070///
9071static unsigned GetSelectFoldableOperands(Instruction *I) {
9072 switch (I->getOpcode()) {
9073 case Instruction::Add:
9074 case Instruction::Mul:
9075 case Instruction::And:
9076 case Instruction::Or:
9077 case Instruction::Xor:
9078 return 3; // Can fold through either operand.
9079 case Instruction::Sub: // Can only fold on the amount subtracted.
9080 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009081 case Instruction::LShr:
9082 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009083 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009084 default:
9085 return 0; // Cannot fold
9086 }
9087}
9088
9089/// GetSelectFoldableConstant - For the same transformation as the previous
9090/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009091static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009092 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009093 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009094 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009095 case Instruction::Add:
9096 case Instruction::Sub:
9097 case Instruction::Or:
9098 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009099 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009100 case Instruction::LShr:
9101 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009102 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009103 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009104 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009105 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009106 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009107 }
9108}
9109
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009110/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9111/// have the same opcode and only one use each. Try to simplify this.
9112Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9113 Instruction *FI) {
9114 if (TI->getNumOperands() == 1) {
9115 // If this is a non-volatile load or a cast from the same type,
9116 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009117 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009118 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9119 return 0;
9120 } else {
9121 return 0; // unknown unary op.
9122 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009123
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009124 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009125 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009126 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009127 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009128 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009129 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009130 }
9131
Reid Spencer832254e2007-02-02 02:16:23 +00009132 // Only handle binary operators here.
9133 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009134 return 0;
9135
9136 // Figure out if the operations have any operands in common.
9137 Value *MatchOp, *OtherOpT, *OtherOpF;
9138 bool MatchIsOpZero;
9139 if (TI->getOperand(0) == FI->getOperand(0)) {
9140 MatchOp = TI->getOperand(0);
9141 OtherOpT = TI->getOperand(1);
9142 OtherOpF = FI->getOperand(1);
9143 MatchIsOpZero = true;
9144 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9145 MatchOp = TI->getOperand(1);
9146 OtherOpT = TI->getOperand(0);
9147 OtherOpF = FI->getOperand(0);
9148 MatchIsOpZero = false;
9149 } else if (!TI->isCommutative()) {
9150 return 0;
9151 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9152 MatchOp = TI->getOperand(0);
9153 OtherOpT = TI->getOperand(1);
9154 OtherOpF = FI->getOperand(0);
9155 MatchIsOpZero = true;
9156 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9157 MatchOp = TI->getOperand(1);
9158 OtherOpT = TI->getOperand(0);
9159 OtherOpF = FI->getOperand(1);
9160 MatchIsOpZero = true;
9161 } else {
9162 return 0;
9163 }
9164
9165 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009166 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9167 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009168 InsertNewInstBefore(NewSI, SI);
9169
9170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9171 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009172 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009173 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009174 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009175 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009176 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009177 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009178}
9179
Evan Chengde621922009-03-31 20:42:45 +00009180static bool isSelect01(Constant *C1, Constant *C2) {
9181 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9182 if (!C1I)
9183 return false;
9184 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9185 if (!C2I)
9186 return false;
9187 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9188}
9189
9190/// FoldSelectIntoOp - Try fold the select into one of the operands to
9191/// facilitate further optimization.
9192Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9193 Value *FalseVal) {
9194 // See the comment above GetSelectFoldableOperands for a description of the
9195 // transformation we are doing here.
9196 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9197 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9198 !isa<Constant>(FalseVal)) {
9199 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9200 unsigned OpToFold = 0;
9201 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9202 OpToFold = 1;
9203 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9204 OpToFold = 2;
9205 }
9206
9207 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009208 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009209 Value *OOp = TVI->getOperand(2-OpToFold);
9210 // Avoid creating select between 2 constants unless it's selecting
9211 // between 0 and 1.
9212 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9213 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9214 InsertNewInstBefore(NewSel, SI);
9215 NewSel->takeName(TVI);
9216 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9217 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009218 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009219 }
9220 }
9221 }
9222 }
9223 }
9224
9225 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9226 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9227 !isa<Constant>(TrueVal)) {
9228 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9229 unsigned OpToFold = 0;
9230 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9231 OpToFold = 1;
9232 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9233 OpToFold = 2;
9234 }
9235
9236 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009237 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009238 Value *OOp = FVI->getOperand(2-OpToFold);
9239 // Avoid creating select between 2 constants unless it's selecting
9240 // between 0 and 1.
9241 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9242 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9243 InsertNewInstBefore(NewSel, SI);
9244 NewSel->takeName(FVI);
9245 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9246 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009247 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009248 }
9249 }
9250 }
9251 }
9252 }
9253
9254 return 0;
9255}
9256
Dan Gohman81b28ce2008-09-16 18:46:06 +00009257/// visitSelectInstWithICmp - Visit a SelectInst that has an
9258/// ICmpInst as its first operand.
9259///
9260Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9261 ICmpInst *ICI) {
9262 bool Changed = false;
9263 ICmpInst::Predicate Pred = ICI->getPredicate();
9264 Value *CmpLHS = ICI->getOperand(0);
9265 Value *CmpRHS = ICI->getOperand(1);
9266 Value *TrueVal = SI.getTrueValue();
9267 Value *FalseVal = SI.getFalseValue();
9268
9269 // Check cases where the comparison is with a constant that
9270 // can be adjusted to fit the min/max idiom. We may edit ICI in
9271 // place here, so make sure the select is the only user.
9272 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009273 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009274 switch (Pred) {
9275 default: break;
9276 case ICmpInst::ICMP_ULT:
9277 case ICmpInst::ICMP_SLT: {
9278 // X < MIN ? T : F --> F
9279 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9280 return ReplaceInstUsesWith(SI, FalseVal);
9281 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009282 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009283 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9284 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9285 Pred = ICmpInst::getSwappedPredicate(Pred);
9286 CmpRHS = AdjustedRHS;
9287 std::swap(FalseVal, TrueVal);
9288 ICI->setPredicate(Pred);
9289 ICI->setOperand(1, CmpRHS);
9290 SI.setOperand(1, TrueVal);
9291 SI.setOperand(2, FalseVal);
9292 Changed = true;
9293 }
9294 break;
9295 }
9296 case ICmpInst::ICMP_UGT:
9297 case ICmpInst::ICMP_SGT: {
9298 // X > MAX ? T : F --> F
9299 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9300 return ReplaceInstUsesWith(SI, FalseVal);
9301 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009302 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009303 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9304 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9305 Pred = ICmpInst::getSwappedPredicate(Pred);
9306 CmpRHS = AdjustedRHS;
9307 std::swap(FalseVal, TrueVal);
9308 ICI->setPredicate(Pred);
9309 ICI->setOperand(1, CmpRHS);
9310 SI.setOperand(1, TrueVal);
9311 SI.setOperand(2, FalseVal);
9312 Changed = true;
9313 }
9314 break;
9315 }
9316 }
9317
Dan Gohman1975d032008-10-30 20:40:10 +00009318 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9319 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009320 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009321 if (match(TrueVal, m_ConstantInt<-1>()) &&
9322 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009323 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009324 else if (match(TrueVal, m_ConstantInt<0>()) &&
9325 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009326 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9327
Dan Gohman1975d032008-10-30 20:40:10 +00009328 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9329 // If we are just checking for a icmp eq of a single bit and zext'ing it
9330 // to an integer, then shift the bit to the appropriate place and then
9331 // cast to integer to avoid the comparison.
9332 const APInt &Op1CV = CI->getValue();
9333
9334 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9335 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9336 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009337 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009338 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009339 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009340 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009341 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009342 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009343 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009344 if (In->getType() != SI.getType())
9345 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009346 true/*SExt*/, "tmp", ICI);
9347
9348 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009349 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009350 In->getName()+".not"), *ICI);
9351
9352 return ReplaceInstUsesWith(SI, In);
9353 }
9354 }
9355 }
9356
Dan Gohman81b28ce2008-09-16 18:46:06 +00009357 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9358 // Transform (X == Y) ? X : Y -> Y
9359 if (Pred == ICmpInst::ICMP_EQ)
9360 return ReplaceInstUsesWith(SI, FalseVal);
9361 // Transform (X != Y) ? X : Y -> X
9362 if (Pred == ICmpInst::ICMP_NE)
9363 return ReplaceInstUsesWith(SI, TrueVal);
9364 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9365
9366 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9367 // Transform (X == Y) ? Y : X -> X
9368 if (Pred == ICmpInst::ICMP_EQ)
9369 return ReplaceInstUsesWith(SI, FalseVal);
9370 // Transform (X != Y) ? Y : X -> Y
9371 if (Pred == ICmpInst::ICMP_NE)
9372 return ReplaceInstUsesWith(SI, TrueVal);
9373 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9374 }
9375
9376 /// NOTE: if we wanted to, this is where to detect integer ABS
9377
9378 return Changed ? &SI : 0;
9379}
9380
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009381
Chris Lattner7f239582009-10-22 00:17:26 +00009382/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9383/// PHI node (but the two may be in different blocks). See if the true/false
9384/// values (V) are live in all of the predecessor blocks of the PHI. For
9385/// example, cases like this cannot be mapped:
9386///
9387/// X = phi [ C1, BB1], [C2, BB2]
9388/// Y = add
9389/// Z = select X, Y, 0
9390///
9391/// because Y is not live in BB1/BB2.
9392///
9393static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9394 const SelectInst &SI) {
9395 // If the value is a non-instruction value like a constant or argument, it
9396 // can always be mapped.
9397 const Instruction *I = dyn_cast<Instruction>(V);
9398 if (I == 0) return true;
9399
9400 // If V is a PHI node defined in the same block as the condition PHI, we can
9401 // map the arguments.
9402 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9403
9404 if (const PHINode *VP = dyn_cast<PHINode>(I))
9405 if (VP->getParent() == CondPHI->getParent())
9406 return true;
9407
9408 // Otherwise, if the PHI and select are defined in the same block and if V is
9409 // defined in a different block, then we can transform it.
9410 if (SI.getParent() == CondPHI->getParent() &&
9411 I->getParent() != CondPHI->getParent())
9412 return true;
9413
9414 // Otherwise we have a 'hard' case and we can't tell without doing more
9415 // detailed dominator based analysis, punt.
9416 return false;
9417}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009418
Chris Lattner3d69f462004-03-12 05:52:32 +00009419Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009420 Value *CondVal = SI.getCondition();
9421 Value *TrueVal = SI.getTrueValue();
9422 Value *FalseVal = SI.getFalseValue();
9423
9424 // select true, X, Y -> X
9425 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009426 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009427 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009428
9429 // select C, X, X -> X
9430 if (TrueVal == FalseVal)
9431 return ReplaceInstUsesWith(SI, TrueVal);
9432
Chris Lattnere87597f2004-10-16 18:11:37 +00009433 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9434 return ReplaceInstUsesWith(SI, FalseVal);
9435 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9436 return ReplaceInstUsesWith(SI, TrueVal);
9437 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9438 if (isa<Constant>(TrueVal))
9439 return ReplaceInstUsesWith(SI, TrueVal);
9440 else
9441 return ReplaceInstUsesWith(SI, FalseVal);
9442 }
9443
Owen Anderson1d0be152009-08-13 21:58:54 +00009444 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009445 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009446 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009447 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009448 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009449 } else {
9450 // Change: A = select B, false, C --> A = and !B, C
9451 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009452 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009453 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009454 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009455 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009456 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009457 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009458 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009459 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009460 } else {
9461 // Change: A = select B, C, true --> A = or !B, C
9462 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009463 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009464 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009465 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009466 }
9467 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009468
9469 // select a, b, a -> a&b
9470 // select a, a, b -> a|b
9471 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009472 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009473 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009474 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009475 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009476
Chris Lattner2eefe512004-04-09 19:05:30 +00009477 // Selecting between two integer constants?
9478 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9479 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009480 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009481 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009482 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009483 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009484 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009485 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009486 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009487 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009488 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009489 }
Chris Lattner457dd822004-06-09 07:59:58 +00009490
Reid Spencere4d87aa2006-12-23 06:05:41 +00009491 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009492 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009493 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009494 // non-constant value, eliminate this whole mess. This corresponds to
9495 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009496 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009497 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009498 cast<Constant>(IC->getOperand(1))->isNullValue())
9499 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9500 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009501 isa<ConstantInt>(ICA->getOperand(1)) &&
9502 (ICA->getOperand(1) == TrueValC ||
9503 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009504 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9505 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009506 // know whether we have a icmp_ne or icmp_eq and whether the
9507 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009508 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009509 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009510 Value *V = ICA;
9511 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009512 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009513 Instruction::Xor, V, ICA->getOperand(1)), SI);
9514 return ReplaceInstUsesWith(SI, V);
9515 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009516 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009517 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009518
9519 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009520 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9521 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009522 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009523 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9524 // This is not safe in general for floating point:
9525 // consider X== -0, Y== +0.
9526 // It becomes safe if either operand is a nonzero constant.
9527 ConstantFP *CFPt, *CFPf;
9528 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9529 !CFPt->getValueAPF().isZero()) ||
9530 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9531 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009532 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009533 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009534 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009535 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009536 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009537 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009538
Reid Spencere4d87aa2006-12-23 06:05:41 +00009539 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009540 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009541 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9542 // This is not safe in general for floating point:
9543 // consider X== -0, Y== +0.
9544 // It becomes safe if either operand is a nonzero constant.
9545 ConstantFP *CFPt, *CFPf;
9546 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9547 !CFPt->getValueAPF().isZero()) ||
9548 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9549 !CFPf->getValueAPF().isZero()))
9550 return ReplaceInstUsesWith(SI, FalseVal);
9551 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009552 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009553 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9554 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009555 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009556 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009557 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009558 }
9559
9560 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009561 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9562 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9563 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009564
Chris Lattner87875da2005-01-13 22:52:24 +00009565 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9566 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9567 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009568 Instruction *AddOp = 0, *SubOp = 0;
9569
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009570 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9571 if (TI->getOpcode() == FI->getOpcode())
9572 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9573 return IV;
9574
9575 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9576 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009577 if ((TI->getOpcode() == Instruction::Sub &&
9578 FI->getOpcode() == Instruction::Add) ||
9579 (TI->getOpcode() == Instruction::FSub &&
9580 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009581 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009582 } else if ((FI->getOpcode() == Instruction::Sub &&
9583 TI->getOpcode() == Instruction::Add) ||
9584 (FI->getOpcode() == Instruction::FSub &&
9585 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009586 AddOp = TI; SubOp = FI;
9587 }
9588
9589 if (AddOp) {
9590 Value *OtherAddOp = 0;
9591 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9592 OtherAddOp = AddOp->getOperand(1);
9593 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9594 OtherAddOp = AddOp->getOperand(0);
9595 }
9596
9597 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009598 // So at this point we know we have (Y -> OtherAddOp):
9599 // select C, (add X, Y), (sub X, Z)
9600 Value *NegVal; // Compute -Z
9601 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009602 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009603 } else {
9604 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009605 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009606 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009607 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009608
9609 Value *NewTrueOp = OtherAddOp;
9610 Value *NewFalseOp = NegVal;
9611 if (AddOp != TI)
9612 std::swap(NewTrueOp, NewFalseOp);
9613 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009614 SelectInst::Create(CondVal, NewTrueOp,
9615 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009616
9617 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009618 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009619 }
9620 }
9621 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009622
Chris Lattnere576b912004-04-09 23:46:01 +00009623 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009624 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009625 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9626 if (FoldI)
9627 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009628 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009629
Chris Lattner7f239582009-10-22 00:17:26 +00009630 // See if we can fold the select into a phi node if the condition is a select.
9631 if (isa<PHINode>(SI.getCondition()))
9632 // The true/false values have to be live in the PHI predecessor's blocks.
9633 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9634 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9635 if (Instruction *NV = FoldOpIntoPhi(SI))
9636 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009637
Chris Lattnera1df33c2005-04-24 07:30:14 +00009638 if (BinaryOperator::isNot(CondVal)) {
9639 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9640 SI.setOperand(1, FalseVal);
9641 SI.setOperand(2, TrueVal);
9642 return &SI;
9643 }
9644
Chris Lattner3d69f462004-03-12 05:52:32 +00009645 return 0;
9646}
9647
Dan Gohmaneee962e2008-04-10 18:43:06 +00009648/// EnforceKnownAlignment - If the specified pointer points to an object that
9649/// we control, modify the object's alignment to PrefAlign. This isn't
9650/// often possible though. If alignment is important, a more reliable approach
9651/// is to simply align all global variables and allocation instructions to
9652/// their preferred alignment from the beginning.
9653///
9654static unsigned EnforceKnownAlignment(Value *V,
9655 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009656
Dan Gohmaneee962e2008-04-10 18:43:06 +00009657 User *U = dyn_cast<User>(V);
9658 if (!U) return Align;
9659
Dan Gohmanca178902009-07-17 20:47:02 +00009660 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009661 default: break;
9662 case Instruction::BitCast:
9663 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9664 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009665 // If all indexes are zero, it is just the alignment of the base pointer.
9666 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009667 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009668 if (!isa<Constant>(*i) ||
9669 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009670 AllZeroOperands = false;
9671 break;
9672 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009673
9674 if (AllZeroOperands) {
9675 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009676 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009677 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009678 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009679 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009680 }
9681
9682 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9683 // If there is a large requested alignment and we can, bump up the alignment
9684 // of the global.
9685 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009686 if (GV->getAlignment() >= PrefAlign)
9687 Align = GV->getAlignment();
9688 else {
9689 GV->setAlignment(PrefAlign);
9690 Align = PrefAlign;
9691 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009692 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009693 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9694 // If there is a requested alignment and if this is an alloca, round up.
9695 if (AI->getAlignment() >= PrefAlign)
9696 Align = AI->getAlignment();
9697 else {
9698 AI->setAlignment(PrefAlign);
9699 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009700 }
9701 }
9702
9703 return Align;
9704}
9705
9706/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9707/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9708/// and it is more than the alignment of the ultimate object, see if we can
9709/// increase the alignment of the ultimate object, making this check succeed.
9710unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9711 unsigned PrefAlign) {
9712 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9713 sizeof(PrefAlign) * CHAR_BIT;
9714 APInt Mask = APInt::getAllOnesValue(BitWidth);
9715 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9716 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9717 unsigned TrailZ = KnownZero.countTrailingOnes();
9718 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9719
9720 if (PrefAlign > Align)
9721 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9722
9723 // We don't need to make any adjustment.
9724 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009725}
9726
Chris Lattnerf497b022008-01-13 23:50:23 +00009727Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009728 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009729 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009730 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009731 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009732
9733 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009734 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009735 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009736 return MI;
9737 }
9738
9739 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9740 // load/store.
9741 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9742 if (MemOpLength == 0) return 0;
9743
Chris Lattner37ac6082008-01-14 00:28:35 +00009744 // Source and destination pointer types are always "i8*" for intrinsic. See
9745 // if the size is something we can handle with a single primitive load/store.
9746 // A single load+store correctly handles overlapping memory in the memmove
9747 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009748 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009749 if (Size == 0) return MI; // Delete this mem transfer.
9750
9751 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009752 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009753
Chris Lattner37ac6082008-01-14 00:28:35 +00009754 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009755 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009756 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009757
9758 // Memcpy forces the use of i8* for the source and destination. That means
9759 // that if you're using memcpy to move one double around, you'll get a cast
9760 // from double* to i8*. We'd much rather use a double load+store rather than
9761 // an i64 load+store, here because this improves the odds that the source or
9762 // dest address will be promotable. See if we can find a better type than the
9763 // integer datatype.
9764 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9765 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009766 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009767 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9768 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009769 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009770 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9771 if (STy->getNumElements() == 1)
9772 SrcETy = STy->getElementType(0);
9773 else
9774 break;
9775 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9776 if (ATy->getNumElements() == 1)
9777 SrcETy = ATy->getElementType();
9778 else
9779 break;
9780 } else
9781 break;
9782 }
9783
Dan Gohman8f8e2692008-05-23 01:52:21 +00009784 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009785 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009786 }
9787 }
9788
9789
Chris Lattnerf497b022008-01-13 23:50:23 +00009790 // If the memcpy/memmove provides better alignment info than we can
9791 // infer, use it.
9792 SrcAlign = std::max(SrcAlign, CopyAlign);
9793 DstAlign = std::max(DstAlign, CopyAlign);
9794
Chris Lattner08142f22009-08-30 19:47:22 +00009795 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9796 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009797 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9798 InsertNewInstBefore(L, *MI);
9799 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9800
9801 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009802 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009803 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009804}
Chris Lattner3d69f462004-03-12 05:52:32 +00009805
Chris Lattner69ea9d22008-04-30 06:39:11 +00009806Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9807 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009808 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009809 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009810 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009811 return MI;
9812 }
9813
9814 // Extract the length and alignment and fill if they are constant.
9815 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9816 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009817 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009818 return 0;
9819 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009820 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009821
9822 // If the length is zero, this is a no-op
9823 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9824
9825 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9826 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009827 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009828
9829 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009830 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009831
9832 // Alignment 0 is identity for alignment 1 for memset, but not store.
9833 if (Alignment == 0) Alignment = 1;
9834
9835 // Extract the fill value and store.
9836 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009837 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009838 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009839
9840 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009841 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009842 return MI;
9843 }
9844
9845 return 0;
9846}
9847
9848
Chris Lattner8b0ea312006-01-13 20:11:04 +00009849/// visitCallInst - CallInst simplification. This mostly only handles folding
9850/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9851/// the heavy lifting.
9852///
Chris Lattner9fe38862003-06-19 17:00:31 +00009853Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009854 if (isFreeCall(&CI))
9855 return visitFree(CI);
9856
Chris Lattneraab6ec42009-05-13 17:39:14 +00009857 // If the caller function is nounwind, mark the call as nounwind, even if the
9858 // callee isn't.
9859 if (CI.getParent()->getParent()->doesNotThrow() &&
9860 !CI.doesNotThrow()) {
9861 CI.setDoesNotThrow();
9862 return &CI;
9863 }
9864
Chris Lattner8b0ea312006-01-13 20:11:04 +00009865 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9866 if (!II) return visitCallSite(&CI);
9867
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009868 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9869 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009870 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009871 bool Changed = false;
9872
9873 // memmove/cpy/set of zero bytes is a noop.
9874 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9875 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9876
Chris Lattner35b9e482004-10-12 04:52:52 +00009877 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009878 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009879 // Replace the instruction with just byte operations. We would
9880 // transform other cases to loads/stores, but we don't know if
9881 // alignment is sufficient.
9882 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009883 }
9884
Chris Lattner35b9e482004-10-12 04:52:52 +00009885 // If we have a memmove and the source operation is a constant global,
9886 // then the source and dest pointers can't alias, so we can change this
9887 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009888 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009889 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9890 if (GVSrc->isConstant()) {
9891 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009892 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9893 const Type *Tys[1];
9894 Tys[0] = CI.getOperand(3)->getType();
9895 CI.setOperand(0,
9896 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009897 Changed = true;
9898 }
Eli Friedman0c826d92009-12-17 21:07:31 +00009899 }
Chris Lattnera935db82008-05-28 05:30:41 +00009900
Eli Friedman0c826d92009-12-17 21:07:31 +00009901 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +00009902 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +00009903 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +00009904 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009905 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009906
Chris Lattner95a959d2006-03-06 20:18:44 +00009907 // If we can determine a pointer alignment that is bigger than currently
9908 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009909 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009910 if (Instruction *I = SimplifyMemTransfer(MI))
9911 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009912 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9913 if (Instruction *I = SimplifyMemSet(MSI))
9914 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009915 }
9916
Chris Lattner8b0ea312006-01-13 20:11:04 +00009917 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009918 }
9919
9920 switch (II->getIntrinsicID()) {
9921 default: break;
9922 case Intrinsic::bswap:
9923 // bswap(bswap(x)) -> x
9924 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9925 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9926 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9927 break;
Chris Lattner2bbac752009-11-26 21:42:47 +00009928 case Intrinsic::uadd_with_overflow: {
9929 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9930 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
9931 uint32_t BitWidth = IT->getBitWidth();
9932 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +00009933 APInt LHSKnownZero(BitWidth, 0);
9934 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00009935 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
9936 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
9937 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
9938
9939 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +00009940 APInt RHSKnownZero(BitWidth, 0);
9941 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +00009942 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
9943 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
9944 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
9945 if (LHSKnownNegative && RHSKnownNegative) {
9946 // The sign bit is set in both cases: this MUST overflow.
9947 // Create a simple add instruction, and insert it into the struct.
9948 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
9949 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00009950 Constant *V[] = {
9951 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
9952 };
Chris Lattner2bbac752009-11-26 21:42:47 +00009953 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9954 return InsertValueInst::Create(Struct, Add, 0);
9955 }
9956
9957 if (LHSKnownPositive && RHSKnownPositive) {
9958 // The sign bit is clear in both cases: this CANNOT overflow.
9959 // Create a simple add instruction, and insert it into the struct.
9960 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
9961 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +00009962 Constant *V[] = {
9963 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
9964 };
Chris Lattner2bbac752009-11-26 21:42:47 +00009965 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9966 return InsertValueInst::Create(Struct, Add, 0);
9967 }
9968 }
9969 }
9970 // FALL THROUGH uadd into sadd
9971 case Intrinsic::sadd_with_overflow:
9972 // Canonicalize constants into the RHS.
9973 if (isa<Constant>(II->getOperand(1)) &&
9974 !isa<Constant>(II->getOperand(2))) {
9975 Value *LHS = II->getOperand(1);
9976 II->setOperand(1, II->getOperand(2));
9977 II->setOperand(2, LHS);
9978 return II;
9979 }
9980
9981 // X + undef -> undef
9982 if (isa<UndefValue>(II->getOperand(2)))
9983 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9984
9985 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
9986 // X + 0 -> {X, false}
9987 if (RHS->isZero()) {
9988 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +00009989 UndefValue::get(II->getOperand(0)->getType()),
9990 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +00009991 };
9992 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9993 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
9994 }
9995 }
9996 break;
9997 case Intrinsic::usub_with_overflow:
9998 case Intrinsic::ssub_with_overflow:
9999 // undef - X -> undef
10000 // X - undef -> undef
10001 if (isa<UndefValue>(II->getOperand(1)) ||
10002 isa<UndefValue>(II->getOperand(2)))
10003 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10004
10005 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10006 // X - 0 -> {X, false}
10007 if (RHS->isZero()) {
10008 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010009 UndefValue::get(II->getOperand(1)->getType()),
10010 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010011 };
10012 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10013 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10014 }
10015 }
10016 break;
10017 case Intrinsic::umul_with_overflow:
10018 case Intrinsic::smul_with_overflow:
10019 // Canonicalize constants into the RHS.
10020 if (isa<Constant>(II->getOperand(1)) &&
10021 !isa<Constant>(II->getOperand(2))) {
10022 Value *LHS = II->getOperand(1);
10023 II->setOperand(1, II->getOperand(2));
10024 II->setOperand(2, LHS);
10025 return II;
10026 }
10027
10028 // X * undef -> undef
10029 if (isa<UndefValue>(II->getOperand(2)))
10030 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10031
10032 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10033 // X*0 -> {0, false}
10034 if (RHSI->isZero())
10035 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10036
10037 // X * 1 -> {X, false}
10038 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010039 Constant *V[] = {
10040 UndefValue::get(II->getOperand(1)->getType()),
10041 ConstantInt::getFalse(*Context)
10042 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010043 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010044 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010045 }
10046 }
10047 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010048 case Intrinsic::ppc_altivec_lvx:
10049 case Intrinsic::ppc_altivec_lvxl:
10050 case Intrinsic::x86_sse_loadu_ps:
10051 case Intrinsic::x86_sse2_loadu_pd:
10052 case Intrinsic::x86_sse2_loadu_dq:
10053 // Turn PPC lvx -> load if the pointer is known aligned.
10054 // Turn X86 loadups -> load if the pointer is known aligned.
10055 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010056 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10057 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010058 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010059 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010060 break;
10061 case Intrinsic::ppc_altivec_stvx:
10062 case Intrinsic::ppc_altivec_stvxl:
10063 // Turn stvx -> store if the pointer is known aligned.
10064 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10065 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010066 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010067 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010068 return new StoreInst(II->getOperand(1), Ptr);
10069 }
10070 break;
10071 case Intrinsic::x86_sse_storeu_ps:
10072 case Intrinsic::x86_sse2_storeu_pd:
10073 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010074 // Turn X86 storeu -> store if the pointer is known aligned.
10075 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10076 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010077 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010078 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010079 return new StoreInst(II->getOperand(2), Ptr);
10080 }
10081 break;
10082
10083 case Intrinsic::x86_sse_cvttss2si: {
10084 // These intrinsics only demands the 0th element of its input vector. If
10085 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010086 unsigned VWidth =
10087 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10088 APInt DemandedElts(VWidth, 1);
10089 APInt UndefElts(VWidth, 0);
10090 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010091 UndefElts)) {
10092 II->setOperand(1, V);
10093 return II;
10094 }
10095 break;
10096 }
10097
10098 case Intrinsic::ppc_altivec_vperm:
10099 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10100 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10101 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010102
Chris Lattner0521e3c2008-06-18 04:33:20 +000010103 // Check that all of the elements are integer constants or undefs.
10104 bool AllEltsOk = true;
10105 for (unsigned i = 0; i != 16; ++i) {
10106 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10107 !isa<UndefValue>(Mask->getOperand(i))) {
10108 AllEltsOk = false;
10109 break;
10110 }
10111 }
10112
10113 if (AllEltsOk) {
10114 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010115 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10116 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010117 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010118
Chris Lattner0521e3c2008-06-18 04:33:20 +000010119 // Only extract each element once.
10120 Value *ExtractedElts[32];
10121 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10122
Chris Lattnere2ed0572006-04-06 19:19:17 +000010123 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010124 if (isa<UndefValue>(Mask->getOperand(i)))
10125 continue;
10126 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10127 Idx &= 31; // Match the hardware behavior.
10128
10129 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010130 ExtractedElts[Idx] =
10131 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10132 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10133 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010134 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010135
Chris Lattner0521e3c2008-06-18 04:33:20 +000010136 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010137 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10138 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10139 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010140 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010141 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010142 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010143 }
10144 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010145
Chris Lattner0521e3c2008-06-18 04:33:20 +000010146 case Intrinsic::stackrestore: {
10147 // If the save is right next to the restore, remove the restore. This can
10148 // happen when variable allocas are DCE'd.
10149 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10150 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10151 BasicBlock::iterator BI = SS;
10152 if (&*++BI == II)
10153 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010154 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010155 }
10156
10157 // Scan down this block to see if there is another stack restore in the
10158 // same block without an intervening call/alloca.
10159 BasicBlock::iterator BI = II;
10160 TerminatorInst *TI = II->getParent()->getTerminator();
10161 bool CannotRemove = false;
10162 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010163 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010164 CannotRemove = true;
10165 break;
10166 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010167 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10168 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10169 // If there is a stackrestore below this one, remove this one.
10170 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10171 return EraseInstFromFunction(CI);
10172 // Otherwise, ignore the intrinsic.
10173 } else {
10174 // If we found a non-intrinsic call, we can't remove the stack
10175 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010176 CannotRemove = true;
10177 break;
10178 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010179 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010180 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010181
10182 // If the stack restore is in a return/unwind block and if there are no
10183 // allocas or calls between the restore and the return, nuke the restore.
10184 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10185 return EraseInstFromFunction(CI);
10186 break;
10187 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010188 }
10189
Chris Lattner8b0ea312006-01-13 20:11:04 +000010190 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010191}
10192
10193// InvokeInst simplification
10194//
10195Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010196 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010197}
10198
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010199/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10200/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010201static bool isSafeToEliminateVarargsCast(const CallSite CS,
10202 const CastInst * const CI,
10203 const TargetData * const TD,
10204 const int ix) {
10205 if (!CI->isLosslessCast())
10206 return false;
10207
10208 // The size of ByVal arguments is derived from the type, so we
10209 // can't change to a type with a different size. If the size were
10210 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010211 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010212 return true;
10213
10214 const Type* SrcTy =
10215 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10216 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10217 if (!SrcTy->isSized() || !DstTy->isSized())
10218 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010219 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010220 return false;
10221 return true;
10222}
10223
Chris Lattnera44d8a22003-10-07 22:32:43 +000010224// visitCallSite - Improvements for call and invoke instructions.
10225//
10226Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010227 bool Changed = false;
10228
10229 // If the callee is a constexpr cast of a function, attempt to move the cast
10230 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010231 if (transformConstExprCastCall(CS)) return 0;
10232
Chris Lattner6c266db2003-10-07 22:54:13 +000010233 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010234
Chris Lattner08b22ec2005-05-13 07:09:09 +000010235 if (Function *CalleeF = dyn_cast<Function>(Callee))
10236 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10237 Instruction *OldCall = CS.getInstruction();
10238 // If the call and callee calling conventions don't match, this call must
10239 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010240 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010241 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010242 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010243 // If OldCall dues not return void then replaceAllUsesWith undef.
10244 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010245 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010246 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010247 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10248 return EraseInstFromFunction(*OldCall);
10249 return 0;
10250 }
10251
Chris Lattner17be6352004-10-18 02:59:09 +000010252 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10253 // This instruction is not reachable, just remove it. We insert a store to
10254 // undef so that we know that this code is not reachable, despite the fact
10255 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010256 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010257 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010258 CS.getInstruction());
10259
Devang Patel228ebd02009-10-13 22:56:32 +000010260 // If CS dues not return void then replaceAllUsesWith undef.
10261 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010262 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010263 CS.getInstruction()->
10264 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010265
10266 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10267 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010268 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010269 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010270 }
Chris Lattner17be6352004-10-18 02:59:09 +000010271 return EraseInstFromFunction(*CS.getInstruction());
10272 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010273
Duncan Sandscdb6d922007-09-17 10:26:40 +000010274 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10275 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10276 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10277 return transformCallThroughTrampoline(CS);
10278
Chris Lattner6c266db2003-10-07 22:54:13 +000010279 const PointerType *PTy = cast<PointerType>(Callee->getType());
10280 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10281 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010282 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010283 // See if we can optimize any arguments passed through the varargs area of
10284 // the call.
10285 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010286 E = CS.arg_end(); I != E; ++I, ++ix) {
10287 CastInst *CI = dyn_cast<CastInst>(*I);
10288 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10289 *I = CI->getOperand(0);
10290 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010291 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010292 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010293 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010294
Duncan Sandsf0c33542007-12-19 21:13:37 +000010295 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010296 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010297 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010298 Changed = true;
10299 }
10300
Chris Lattner6c266db2003-10-07 22:54:13 +000010301 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010302}
10303
Chris Lattner9fe38862003-06-19 17:00:31 +000010304// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10305// attempt to move the cast to the arguments of the call/invoke.
10306//
10307bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10308 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10309 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010310 if (CE->getOpcode() != Instruction::BitCast ||
10311 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010312 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010313 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010314 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010315 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010316
10317 // Okay, this is a cast from a function to a different type. Unless doing so
10318 // would cause a type conversion of one of our arguments, change this call to
10319 // be a direct call with arguments casted to the appropriate types.
10320 //
10321 const FunctionType *FT = Callee->getFunctionType();
10322 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010323 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010324
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010325 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010326 return false; // TODO: Handle multiple return values.
10327
Chris Lattnerf78616b2004-01-14 06:06:08 +000010328 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010329 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010330 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010331 // Conversion is ok if changing from one pointer type to another or from
10332 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010333 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010334 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010335 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010336 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010337 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010338
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010339 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010340 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010341 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010342 return false; // Cannot transform this return value.
10343
Chris Lattner58d74912008-03-12 17:45:29 +000010344 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010345 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010346 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010347 return false; // Attribute not compatible with transformed value.
10348 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010349
Chris Lattnerf78616b2004-01-14 06:06:08 +000010350 // If the callsite is an invoke instruction, and the return value is used by
10351 // a PHI node in a successor, we cannot change the return type of the call
10352 // because there is no place to put the cast instruction (without breaking
10353 // the critical edge). Bail out in this case.
10354 if (!Caller->use_empty())
10355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10356 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10357 UI != E; ++UI)
10358 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10359 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010360 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010361 return false;
10362 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010363
10364 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10365 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010366
Chris Lattner9fe38862003-06-19 17:00:31 +000010367 CallSite::arg_iterator AI = CS.arg_begin();
10368 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10369 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010370 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010371
10372 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010373 return false; // Cannot transform this parameter value.
10374
Devang Patel19c87462008-09-26 22:53:05 +000010375 if (CallerPAL.getParamAttributes(i + 1)
10376 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010377 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010378
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010379 // Converting from one pointer type to another or between a pointer and an
10380 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010381 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010382 (TD && ((isa<PointerType>(ParamTy) ||
10383 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10384 (isa<PointerType>(ActTy) ||
10385 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010386 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010387 }
10388
10389 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010390 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010391 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010392
Chris Lattner58d74912008-03-12 17:45:29 +000010393 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10394 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010395 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010396 // won't be dropping them. Check that these extra arguments have attributes
10397 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010398 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10399 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010400 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010401 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010402 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010403 return false;
10404 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010405
Chris Lattner9fe38862003-06-19 17:00:31 +000010406 // Okay, we decided that this is a safe thing to do: go ahead and start
10407 // inserting cast instructions as necessary...
10408 std::vector<Value*> Args;
10409 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010410 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010411 attrVec.reserve(NumCommonArgs);
10412
10413 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010414 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010415
10416 // If the return value is not being used, the type may not be compatible
10417 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010418 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010419
10420 // Add the new return attributes.
10421 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010422 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010423
10424 AI = CS.arg_begin();
10425 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10426 const Type *ParamTy = FT->getParamType(i);
10427 if ((*AI)->getType() == ParamTy) {
10428 Args.push_back(*AI);
10429 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010430 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010431 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010432 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010433 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010434
10435 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010436 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010437 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010438 }
10439
10440 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010441 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010442 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010443 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010444
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010445 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010446 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010447 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010448 errs() << "WARNING: While resolving call to function '"
10449 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010450 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010451 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010452 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10453 const Type *PTy = getPromotedType((*AI)->getType());
10454 if (PTy != (*AI)->getType()) {
10455 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010456 Instruction::CastOps opcode =
10457 CastInst::getCastOpcode(*AI, false, PTy, false);
10458 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010459 } else {
10460 Args.push_back(*AI);
10461 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010462
Duncan Sandse1e520f2008-01-13 08:02:44 +000010463 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010464 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010465 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010466 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010467 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010468 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010469
Devang Patel19c87462008-09-26 22:53:05 +000010470 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10471 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10472
Devang Patel9674d152009-10-14 17:29:00 +000010473 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010474 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010475
Eric Christophera66297a2009-07-25 02:45:27 +000010476 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10477 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010478
Chris Lattner9fe38862003-06-19 17:00:31 +000010479 Instruction *NC;
10480 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010481 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010482 Args.begin(), Args.end(),
10483 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010484 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010485 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010486 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010487 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10488 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010489 CallInst *CI = cast<CallInst>(Caller);
10490 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010491 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010492 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010493 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010494 }
10495
Chris Lattner6934a042007-02-11 01:23:03 +000010496 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010497 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010498 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010499 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010500 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010501 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010502 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010503
10504 // If this is an invoke instruction, we should insert it after the first
10505 // non-phi, instruction in the normal successor block.
10506 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010507 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010508 InsertNewInstBefore(NC, *I);
10509 } else {
10510 // Otherwise, it's a call, just insert cast right after the call instr
10511 InsertNewInstBefore(NC, *Caller);
10512 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010513 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010514 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010515 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010516 }
10517 }
10518
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010519
Chris Lattner931f8f32009-08-31 05:17:58 +000010520 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010521 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010522
10523 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010524 return true;
10525}
10526
Duncan Sandscdb6d922007-09-17 10:26:40 +000010527// transformCallThroughTrampoline - Turn a call to a function created by the
10528// init_trampoline intrinsic into a direct call to the underlying function.
10529//
10530Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10531 Value *Callee = CS.getCalledValue();
10532 const PointerType *PTy = cast<PointerType>(Callee->getType());
10533 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010534 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010535
10536 // If the call already has the 'nest' attribute somewhere then give up -
10537 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010538 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010539 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010540
10541 IntrinsicInst *Tramp =
10542 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10543
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010544 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010545 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10546 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10547
Devang Patel05988662008-09-25 21:00:45 +000010548 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010549 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010550 unsigned NestIdx = 1;
10551 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010552 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010553
10554 // Look for a parameter marked with the 'nest' attribute.
10555 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10556 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010557 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010558 // Record the parameter type and any other attributes.
10559 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010560 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010561 break;
10562 }
10563
10564 if (NestTy) {
10565 Instruction *Caller = CS.getInstruction();
10566 std::vector<Value*> NewArgs;
10567 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10568
Devang Patel05988662008-09-25 21:00:45 +000010569 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010570 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010571
Duncan Sandscdb6d922007-09-17 10:26:40 +000010572 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010573 // mean appending it. Likewise for attributes.
10574
Devang Patel19c87462008-09-26 22:53:05 +000010575 // Add any result attributes.
10576 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010577 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010578
Duncan Sandscdb6d922007-09-17 10:26:40 +000010579 {
10580 unsigned Idx = 1;
10581 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10582 do {
10583 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010584 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010585 Value *NestVal = Tramp->getOperand(3);
10586 if (NestVal->getType() != NestTy)
10587 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10588 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010589 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010590 }
10591
10592 if (I == E)
10593 break;
10594
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010595 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010596 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010597 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010598 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010599 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010600
10601 ++Idx, ++I;
10602 } while (1);
10603 }
10604
Devang Patel19c87462008-09-26 22:53:05 +000010605 // Add any function attributes.
10606 if (Attributes Attr = Attrs.getFnAttributes())
10607 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10608
Duncan Sandscdb6d922007-09-17 10:26:40 +000010609 // The trampoline may have been bitcast to a bogus type (FTy).
10610 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010611 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010612
Duncan Sandscdb6d922007-09-17 10:26:40 +000010613 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010614 NewTypes.reserve(FTy->getNumParams()+1);
10615
Duncan Sandscdb6d922007-09-17 10:26:40 +000010616 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010617 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010618 {
10619 unsigned Idx = 1;
10620 FunctionType::param_iterator I = FTy->param_begin(),
10621 E = FTy->param_end();
10622
10623 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010624 if (Idx == NestIdx)
10625 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010626 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010627
10628 if (I == E)
10629 break;
10630
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010631 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010632 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010633
10634 ++Idx, ++I;
10635 } while (1);
10636 }
10637
10638 // Replace the trampoline call with a direct call. Let the generic
10639 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010640 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010641 FTy->isVarArg());
10642 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010643 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010644 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010645 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010646 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10647 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010648
10649 Instruction *NewCaller;
10650 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010651 NewCaller = InvokeInst::Create(NewCallee,
10652 II->getNormalDest(), II->getUnwindDest(),
10653 NewArgs.begin(), NewArgs.end(),
10654 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010655 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010656 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010657 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010658 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10659 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010660 if (cast<CallInst>(Caller)->isTailCall())
10661 cast<CallInst>(NewCaller)->setTailCall();
10662 cast<CallInst>(NewCaller)->
10663 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010664 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010665 }
Devang Patel9674d152009-10-14 17:29:00 +000010666 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010667 Caller->replaceAllUsesWith(NewCaller);
10668 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010669 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010670 return 0;
10671 }
10672 }
10673
10674 // Replace the trampoline call with a direct call. Since there is no 'nest'
10675 // parameter, there is no need to adjust the argument list. Let the generic
10676 // code sort out any function type mismatches.
10677 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010678 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010679 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010680 CS.setCalledFunction(NewCallee);
10681 return CS.getInstruction();
10682}
10683
Dan Gohman9ad29202009-09-16 16:50:24 +000010684/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10685/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000010686/// and a single binop.
10687Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10688 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010689 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010690 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010691 Value *LHSVal = FirstInst->getOperand(0);
10692 Value *RHSVal = FirstInst->getOperand(1);
10693
10694 const Type *LHSType = LHSVal->getType();
10695 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010696
Dan Gohman9ad29202009-09-16 16:50:24 +000010697 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010698 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010699 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010700 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010701 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010702 // types or GEP's with different index types.
10703 I->getOperand(0)->getType() != LHSType ||
10704 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010705 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010706
10707 // If they are CmpInst instructions, check their predicates
10708 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10709 if (cast<CmpInst>(I)->getPredicate() !=
10710 cast<CmpInst>(FirstInst)->getPredicate())
10711 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010712
10713 // Keep track of which operand needs a phi node.
10714 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10715 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010716 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010717
10718 // If both LHS and RHS would need a PHI, don't do this transformation,
10719 // because it would increase the number of PHIs entering the block,
10720 // which leads to higher register pressure. This is especially
10721 // bad when the PHIs are in the header of a loop.
10722 if (!LHSVal && !RHSVal)
10723 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010724
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010725 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010726
Chris Lattner7da52b22006-11-01 04:51:18 +000010727 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010728 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010729 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010730 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010731 NewLHS = PHINode::Create(LHSType,
10732 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010733 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10734 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010735 InsertNewInstBefore(NewLHS, PN);
10736 LHSVal = NewLHS;
10737 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010738
10739 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010740 NewRHS = PHINode::Create(RHSType,
10741 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010742 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10743 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010744 InsertNewInstBefore(NewRHS, PN);
10745 RHSVal = NewRHS;
10746 }
10747
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010748 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010749 if (NewLHS || NewRHS) {
10750 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10751 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10752 if (NewLHS) {
10753 Value *NewInLHS = InInst->getOperand(0);
10754 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10755 }
10756 if (NewRHS) {
10757 Value *NewInRHS = InInst->getOperand(1);
10758 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10759 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010760 }
10761 }
10762
Chris Lattner7da52b22006-11-01 04:51:18 +000010763 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010764 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010765 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010766 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010767 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010768}
10769
Chris Lattner05f18922008-12-01 02:34:36 +000010770Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10771 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10772
10773 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10774 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010775 // This is true if all GEP bases are allocas and if all indices into them are
10776 // constants.
10777 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010778
10779 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010780 // more than one phi, which leads to higher register pressure. This is
10781 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010782 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010783
Dan Gohman9ad29202009-09-16 16:50:24 +000010784 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010785 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10786 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10787 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10788 GEP->getNumOperands() != FirstInst->getNumOperands())
10789 return 0;
10790
Chris Lattner36d3e322009-02-21 00:46:50 +000010791 // Keep track of whether or not all GEPs are of alloca pointers.
10792 if (AllBasePointersAreAllocas &&
10793 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10794 !GEP->hasAllConstantIndices()))
10795 AllBasePointersAreAllocas = false;
10796
Chris Lattner05f18922008-12-01 02:34:36 +000010797 // Compare the operand lists.
10798 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10799 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10800 continue;
10801
10802 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10803 // if one of the PHIs has a constant for the index. The index may be
10804 // substantially cheaper to compute for the constants, so making it a
10805 // variable index could pessimize the path. This also handles the case
10806 // for struct indices, which must always be constant.
10807 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10808 isa<ConstantInt>(GEP->getOperand(op)))
10809 return 0;
10810
10811 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10812 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010813
10814 // If we already needed a PHI for an earlier operand, and another operand
10815 // also requires a PHI, we'd be introducing more PHIs than we're
10816 // eliminating, which increases register pressure on entry to the PHI's
10817 // block.
10818 if (NeededPhi)
10819 return 0;
10820
Chris Lattner05f18922008-12-01 02:34:36 +000010821 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010822 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010823 }
10824 }
10825
Chris Lattner36d3e322009-02-21 00:46:50 +000010826 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010827 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010828 // offset calculation, but all the predecessors will have to materialize the
10829 // stack address into a register anyway. We'd actually rather *clone* the
10830 // load up into the predecessors so that we have a load of a gep of an alloca,
10831 // which can usually all be folded into the load.
10832 if (AllBasePointersAreAllocas)
10833 return 0;
10834
Chris Lattner05f18922008-12-01 02:34:36 +000010835 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10836 // that is variable.
10837 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10838
10839 bool HasAnyPHIs = false;
10840 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10841 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10842 Value *FirstOp = FirstInst->getOperand(i);
10843 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10844 FirstOp->getName()+".pn");
10845 InsertNewInstBefore(NewPN, PN);
10846
10847 NewPN->reserveOperandSpace(e);
10848 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10849 OperandPhis[i] = NewPN;
10850 FixedOperands[i] = NewPN;
10851 HasAnyPHIs = true;
10852 }
10853
10854
10855 // Add all operands to the new PHIs.
10856 if (HasAnyPHIs) {
10857 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10858 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10859 BasicBlock *InBB = PN.getIncomingBlock(i);
10860
10861 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10862 if (PHINode *OpPhi = OperandPhis[op])
10863 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10864 }
10865 }
10866
10867 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010868 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10869 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10870 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010871 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10872 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010873}
10874
10875
Chris Lattner21550882009-02-23 05:56:17 +000010876/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10877/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010878/// obvious the value of the load is not changed from the point of the load to
10879/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010880///
10881/// Finally, it is safe, but not profitable, to sink a load targetting a
10882/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10883/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010884static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010885 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10886
10887 for (++BBI; BBI != E; ++BBI)
10888 if (BBI->mayWriteToMemory())
10889 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010890
10891 // Check for non-address taken alloca. If not address-taken already, it isn't
10892 // profitable to do this xform.
10893 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10894 bool isAddressTaken = false;
10895 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10896 UI != E; ++UI) {
10897 if (isa<LoadInst>(UI)) continue;
10898 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10899 // If storing TO the alloca, then the address isn't taken.
10900 if (SI->getOperand(1) == AI) continue;
10901 }
10902 isAddressTaken = true;
10903 break;
10904 }
10905
Chris Lattner36d3e322009-02-21 00:46:50 +000010906 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010907 return false;
10908 }
10909
Chris Lattner36d3e322009-02-21 00:46:50 +000010910 // If this load is a load from a GEP with a constant offset from an alloca,
10911 // then we don't want to sink it. In its present form, it will be
10912 // load [constant stack offset]. Sinking it will cause us to have to
10913 // materialize the stack addresses in each predecessor in a register only to
10914 // do a shared load from register in the successor.
10915 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10916 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10917 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10918 return false;
10919
Chris Lattner76c73142006-11-01 07:13:54 +000010920 return true;
10921}
10922
Chris Lattner751a3622009-11-01 20:04:24 +000010923Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10924 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10925
10926 // When processing loads, we need to propagate two bits of information to the
10927 // sunk load: whether it is volatile, and what its alignment is. We currently
10928 // don't sink loads when some have their alignment specified and some don't.
10929 // visitLoadInst will propagate an alignment onto the load when TD is around,
10930 // and if TD isn't around, we can't handle the mixed case.
10931 bool isVolatile = FirstLI->isVolatile();
10932 unsigned LoadAlignment = FirstLI->getAlignment();
10933
10934 // We can't sink the load if the loaded value could be modified between the
10935 // load and the PHI.
10936 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10937 !isSafeAndProfitableToSinkLoad(FirstLI))
10938 return 0;
10939
10940 // If the PHI is of volatile loads and the load block has multiple
10941 // successors, sinking it would remove a load of the volatile value from
10942 // the path through the other successor.
10943 if (isVolatile &&
10944 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10945 return 0;
10946
10947 // Check to see if all arguments are the same operation.
10948 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10949 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10950 if (!LI || !LI->hasOneUse())
10951 return 0;
10952
10953 // We can't sink the load if the loaded value could be modified between
10954 // the load and the PHI.
10955 if (LI->isVolatile() != isVolatile ||
10956 LI->getParent() != PN.getIncomingBlock(i) ||
10957 !isSafeAndProfitableToSinkLoad(LI))
10958 return 0;
10959
10960 // If some of the loads have an alignment specified but not all of them,
10961 // we can't do the transformation.
10962 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10963 return 0;
10964
Chris Lattnera664bb72009-11-01 20:07:07 +000010965 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000010966
10967 // If the PHI is of volatile loads and the load block has multiple
10968 // successors, sinking it would remove a load of the volatile value from
10969 // the path through the other successor.
10970 if (isVolatile &&
10971 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10972 return 0;
10973 }
10974
10975 // Okay, they are all the same operation. Create a new PHI node of the
10976 // correct type, and PHI together all of the LHS's of the instructions.
10977 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10978 PN.getName()+".in");
10979 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10980
10981 Value *InVal = FirstLI->getOperand(0);
10982 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10983
10984 // Add all operands to the new PHI.
10985 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10986 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10987 if (NewInVal != InVal)
10988 InVal = 0;
10989 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10990 }
10991
10992 Value *PhiVal;
10993 if (InVal) {
10994 // The new PHI unions all of the same values together. This is really
10995 // common, so we handle it intelligently here for compile-time speed.
10996 PhiVal = InVal;
10997 delete NewPN;
10998 } else {
10999 InsertNewInstBefore(NewPN, PN);
11000 PhiVal = NewPN;
11001 }
11002
11003 // If this was a volatile load that we are merging, make sure to loop through
11004 // and mark all the input loads as non-volatile. If we don't do this, we will
11005 // insert a new volatile load and the old ones will not be deletable.
11006 if (isVolatile)
11007 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11008 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11009
11010 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11011}
11012
Chris Lattner9fe38862003-06-19 17:00:31 +000011013
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011014
11015/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11016/// operator and they all are only used by the PHI, PHI together their
11017/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011018Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11019 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11020
Chris Lattner751a3622009-11-01 20:04:24 +000011021 if (isa<GetElementPtrInst>(FirstInst))
11022 return FoldPHIArgGEPIntoPHI(PN);
11023 if (isa<LoadInst>(FirstInst))
11024 return FoldPHIArgLoadIntoPHI(PN);
11025
Chris Lattnerbac32862004-11-14 19:13:23 +000011026 // Scan the instruction, looking for input operations that can be folded away.
11027 // If all input operands to the phi are the same instruction (e.g. a cast from
11028 // the same type or "+42") we can pull the operation through the PHI, reducing
11029 // code size and simplifying code.
11030 Constant *ConstantOp = 0;
11031 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011032
Chris Lattnerbac32862004-11-14 19:13:23 +000011033 if (isa<CastInst>(FirstInst)) {
11034 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011035
11036 // Be careful about transforming integer PHIs. We don't want to pessimize
11037 // the code by turning an i32 into an i1293.
11038 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011039 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011040 return 0;
11041 }
Reid Spencer832254e2007-02-02 02:16:23 +000011042 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011043 // Can fold binop, compare or shift here if the RHS is a constant,
11044 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011045 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011046 if (ConstantOp == 0)
11047 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011048 } else {
11049 return 0; // Cannot fold this operation.
11050 }
11051
11052 // Check to see if all arguments are the same operation.
11053 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011054 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11055 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011056 return 0;
11057 if (CastSrcTy) {
11058 if (I->getOperand(0)->getType() != CastSrcTy)
11059 return 0; // Cast operation must match.
11060 } else if (I->getOperand(1) != ConstantOp) {
11061 return 0;
11062 }
11063 }
11064
11065 // Okay, they are all the same operation. Create a new PHI node of the
11066 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011067 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11068 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011069 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011070
11071 Value *InVal = FirstInst->getOperand(0);
11072 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011073
11074 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011075 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11076 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11077 if (NewInVal != InVal)
11078 InVal = 0;
11079 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11080 }
11081
11082 Value *PhiVal;
11083 if (InVal) {
11084 // The new PHI unions all of the same values together. This is really
11085 // common, so we handle it intelligently here for compile-time speed.
11086 PhiVal = InVal;
11087 delete NewPN;
11088 } else {
11089 InsertNewInstBefore(NewPN, PN);
11090 PhiVal = NewPN;
11091 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011092
Chris Lattnerbac32862004-11-14 19:13:23 +000011093 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011094 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011095 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011096
Chris Lattner54545ac2008-04-29 17:13:43 +000011097 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011098 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011099
Chris Lattner751a3622009-11-01 20:04:24 +000011100 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11101 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11102 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011103}
Chris Lattnera1be5662002-05-02 17:06:02 +000011104
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011105/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11106/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011107static bool DeadPHICycle(PHINode *PN,
11108 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011109 if (PN->use_empty()) return true;
11110 if (!PN->hasOneUse()) return false;
11111
11112 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011113 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011114 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011115
11116 // Don't scan crazily complex things.
11117 if (PotentiallyDeadPHIs.size() == 16)
11118 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011119
11120 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11121 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011122
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011123 return false;
11124}
11125
Chris Lattnercf5008a2007-11-06 21:52:06 +000011126/// PHIsEqualValue - Return true if this phi node is always equal to
11127/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11128/// z = some value; x = phi (y, z); y = phi (x, z)
11129static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11130 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11131 // See if we already saw this PHI node.
11132 if (!ValueEqualPHIs.insert(PN))
11133 return true;
11134
11135 // Don't scan crazily complex things.
11136 if (ValueEqualPHIs.size() == 16)
11137 return false;
11138
11139 // Scan the operands to see if they are either phi nodes or are equal to
11140 // the value.
11141 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11142 Value *Op = PN->getIncomingValue(i);
11143 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11144 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11145 return false;
11146 } else if (Op != NonPhiInVal)
11147 return false;
11148 }
11149
11150 return true;
11151}
11152
11153
Chris Lattner9956c052009-11-08 19:23:30 +000011154namespace {
11155struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011156 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011157 unsigned Shift; // The amount shifted.
11158 Instruction *Inst; // The trunc instruction.
11159
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011160 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11161 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011162
11163 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011164 if (PHIId < RHS.PHIId) return true;
11165 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011166 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011167 if (Shift > RHS.Shift) return false;
11168 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011169 RHS.Inst->getType()->getPrimitiveSizeInBits();
11170 }
11171};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011172
11173struct LoweredPHIRecord {
11174 PHINode *PN; // The PHI that was lowered.
11175 unsigned Shift; // The amount shifted.
11176 unsigned Width; // The width extracted.
11177
11178 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11179 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11180
11181 // Ctor form used by DenseMap.
11182 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11183 : PN(pn), Shift(Sh), Width(0) {}
11184};
11185}
11186
11187namespace llvm {
11188 template<>
11189 struct DenseMapInfo<LoweredPHIRecord> {
11190 static inline LoweredPHIRecord getEmptyKey() {
11191 return LoweredPHIRecord(0, 0);
11192 }
11193 static inline LoweredPHIRecord getTombstoneKey() {
11194 return LoweredPHIRecord(0, 1);
11195 }
11196 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11197 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11198 (Val.Width>>3);
11199 }
11200 static bool isEqual(const LoweredPHIRecord &LHS,
11201 const LoweredPHIRecord &RHS) {
11202 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11203 LHS.Width == RHS.Width;
11204 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011205 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011206 template <>
11207 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011208}
11209
11210
11211/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11212/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11213/// so, we split the PHI into the various pieces being extracted. This sort of
11214/// thing is introduced when SROA promotes an aggregate to large integer values.
11215///
11216/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11217/// inttoptr. We should produce new PHIs in the right type.
11218///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011219Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11220 // PHIUsers - Keep track of all of the truncated values extracted from a set
11221 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011222 SmallVector<PHIUsageRecord, 16> PHIUsers;
11223
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011224 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11225 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11226 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11227 // check the uses of (to ensure they are all extracts).
11228 SmallVector<PHINode*, 8> PHIsToSlice;
11229 SmallPtrSet<PHINode*, 8> PHIsInspected;
11230
11231 PHIsToSlice.push_back(&FirstPhi);
11232 PHIsInspected.insert(&FirstPhi);
11233
11234 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11235 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011236
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011237 // Scan the input list of the PHI. If any input is an invoke, and if the
11238 // input is defined in the predecessor, then we won't be split the critical
11239 // edge which is required to insert a truncate. Because of this, we have to
11240 // bail out.
11241 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11242 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11243 if (II == 0) continue;
11244 if (II->getParent() != PN->getIncomingBlock(i))
11245 continue;
11246
11247 // If we have a phi, and if it's directly in the predecessor, then we have
11248 // a critical edge where we need to put the truncate. Since we can't
11249 // split the edge in instcombine, we have to bail out.
11250 return 0;
11251 }
11252
11253
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011254 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11255 UI != E; ++UI) {
11256 Instruction *User = cast<Instruction>(*UI);
11257
11258 // If the user is a PHI, inspect its uses recursively.
11259 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11260 if (PHIsInspected.insert(UserPN))
11261 PHIsToSlice.push_back(UserPN);
11262 continue;
11263 }
11264
11265 // Truncates are always ok.
11266 if (isa<TruncInst>(User)) {
11267 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11268 continue;
11269 }
11270
11271 // Otherwise it must be a lshr which can only be used by one trunc.
11272 if (User->getOpcode() != Instruction::LShr ||
11273 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11274 !isa<ConstantInt>(User->getOperand(1)))
11275 return 0;
11276
11277 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11278 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011279 }
Chris Lattner9956c052009-11-08 19:23:30 +000011280 }
11281
11282 // If we have no users, they must be all self uses, just nuke the PHI.
11283 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011284 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011285
11286 // If this phi node is transformable, create new PHIs for all the pieces
11287 // extracted out of it. First, sort the users by their offset and size.
11288 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11289
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011290 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11291 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11292 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11293 );
Chris Lattner9956c052009-11-08 19:23:30 +000011294
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011295 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11296 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011297 DenseMap<BasicBlock*, Value*> PredValues;
11298
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011299 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11300 // introduce redundant PHIs.
11301 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11302
11303 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11304 unsigned PHIId = PHIUsers[UserI].PHIId;
11305 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011306 unsigned Offset = PHIUsers[UserI].Shift;
11307 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011308
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011309 PHINode *EltPHI;
11310
11311 // If we've already lowered a user like this, reuse the previously lowered
11312 // value.
11313 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011314
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011315 // Otherwise, Create the new PHI node for this user.
11316 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11317 assert(EltPHI->getType() != PN->getType() &&
11318 "Truncate didn't shrink phi?");
11319
11320 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11321 BasicBlock *Pred = PN->getIncomingBlock(i);
11322 Value *&PredVal = PredValues[Pred];
11323
11324 // If we already have a value for this predecessor, reuse it.
11325 if (PredVal) {
11326 EltPHI->addIncoming(PredVal, Pred);
11327 continue;
11328 }
Chris Lattner9956c052009-11-08 19:23:30 +000011329
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011330 // Handle the PHI self-reuse case.
11331 Value *InVal = PN->getIncomingValue(i);
11332 if (InVal == PN) {
11333 PredVal = EltPHI;
11334 EltPHI->addIncoming(PredVal, Pred);
11335 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011336 }
11337
11338 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011339 // If the incoming value was a PHI, and if it was one of the PHIs we
11340 // already rewrote it, just use the lowered value.
11341 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11342 PredVal = Res;
11343 EltPHI->addIncoming(PredVal, Pred);
11344 continue;
11345 }
11346 }
11347
11348 // Otherwise, do an extract in the predecessor.
11349 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11350 Value *Res = InVal;
11351 if (Offset)
11352 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11353 Offset), "extract");
11354 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11355 PredVal = Res;
11356 EltPHI->addIncoming(Res, Pred);
11357
11358 // If the incoming value was a PHI, and if it was one of the PHIs we are
11359 // rewriting, we will ultimately delete the code we inserted. This
11360 // means we need to revisit that PHI to make sure we extract out the
11361 // needed piece.
11362 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11363 if (PHIsInspected.count(OldInVal)) {
11364 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11365 OldInVal)-PHIsToSlice.begin();
11366 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11367 cast<Instruction>(Res)));
11368 ++UserE;
11369 }
Chris Lattner9956c052009-11-08 19:23:30 +000011370 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011371 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011372
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011373 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11374 << *EltPHI << '\n');
11375 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011376 }
Chris Lattner9956c052009-11-08 19:23:30 +000011377
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011378 // Replace the use of this piece with the PHI node.
11379 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011380 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011381
11382 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11383 // with undefs.
11384 Value *Undef = UndefValue::get(FirstPhi.getType());
11385 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11386 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11387 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011388}
11389
Chris Lattner473945d2002-05-06 18:06:38 +000011390// PHINode simplification
11391//
Chris Lattner7e708292002-06-25 16:13:24 +000011392Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011393 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011394 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011395
Owen Anderson7e057142006-07-10 22:03:18 +000011396 if (Value *V = PN.hasConstantValue())
11397 return ReplaceInstUsesWith(PN, V);
11398
Owen Anderson7e057142006-07-10 22:03:18 +000011399 // If all PHI operands are the same operation, pull them through the PHI,
11400 // reducing code size.
11401 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011402 isa<Instruction>(PN.getIncomingValue(1)) &&
11403 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11404 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11405 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11406 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011407 PN.getIncomingValue(0)->hasOneUse())
11408 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11409 return Result;
11410
11411 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11412 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11413 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011414 if (PN.hasOneUse()) {
11415 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11416 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011417 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011418 PotentiallyDeadPHIs.insert(&PN);
11419 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011420 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011421 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011422
11423 // If this phi has a single use, and if that use just computes a value for
11424 // the next iteration of a loop, delete the phi. This occurs with unused
11425 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11426 // common case here is good because the only other things that catch this
11427 // are induction variable analysis (sometimes) and ADCE, which is only run
11428 // late.
11429 if (PHIUser->hasOneUse() &&
11430 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11431 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011432 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011433 }
11434 }
Owen Anderson7e057142006-07-10 22:03:18 +000011435
Chris Lattnercf5008a2007-11-06 21:52:06 +000011436 // We sometimes end up with phi cycles that non-obviously end up being the
11437 // same value, for example:
11438 // z = some value; x = phi (y, z); y = phi (x, z)
11439 // where the phi nodes don't necessarily need to be in the same block. Do a
11440 // quick check to see if the PHI node only contains a single non-phi value, if
11441 // so, scan to see if the phi cycle is actually equal to that value.
11442 {
11443 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11444 // Scan for the first non-phi operand.
11445 while (InValNo != NumOperandVals &&
11446 isa<PHINode>(PN.getIncomingValue(InValNo)))
11447 ++InValNo;
11448
11449 if (InValNo != NumOperandVals) {
11450 Value *NonPhiInVal = PN.getOperand(InValNo);
11451
11452 // Scan the rest of the operands to see if there are any conflicts, if so
11453 // there is no need to recursively scan other phis.
11454 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11455 Value *OpVal = PN.getIncomingValue(InValNo);
11456 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11457 break;
11458 }
11459
11460 // If we scanned over all operands, then we have one unique value plus
11461 // phi values. Scan PHI nodes to see if they all merge in each other or
11462 // the value.
11463 if (InValNo == NumOperandVals) {
11464 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11465 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11466 return ReplaceInstUsesWith(PN, NonPhiInVal);
11467 }
11468 }
11469 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011470
Dan Gohman5b097012009-10-31 14:22:52 +000011471 // If there are multiple PHIs, sort their operands so that they all list
11472 // the blocks in the same order. This will help identical PHIs be eliminated
11473 // by other passes. Other passes shouldn't depend on this for correctness
11474 // however.
11475 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11476 if (&PN != FirstPN)
11477 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011478 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011479 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11480 if (BBA != BBB) {
11481 Value *VA = PN.getIncomingValue(i);
11482 unsigned j = PN.getBasicBlockIndex(BBB);
11483 Value *VB = PN.getIncomingValue(j);
11484 PN.setIncomingBlock(i, BBB);
11485 PN.setIncomingValue(i, VB);
11486 PN.setIncomingBlock(j, BBA);
11487 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011488 // NOTE: Instcombine normally would want us to "return &PN" if we
11489 // modified any of the operands of an instruction. However, since we
11490 // aren't adding or removing uses (just rearranging them) we don't do
11491 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011492 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011493 }
11494
Chris Lattner9956c052009-11-08 19:23:30 +000011495 // If this is an integer PHI and we know that it has an illegal type, see if
11496 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11497 // PHI into the various pieces being extracted. This sort of thing is
11498 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011499 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011500 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11501 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11502 return Res;
11503
Chris Lattner60921c92003-12-19 05:58:40 +000011504 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011505}
11506
Chris Lattner7e708292002-06-25 16:13:24 +000011507Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011508 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11509
11510 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11511 return ReplaceInstUsesWith(GEP, V);
11512
Chris Lattner620ce142004-05-07 22:09:22 +000011513 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011514
Chris Lattnere87597f2004-10-16 18:11:37 +000011515 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011516 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011517
Chris Lattner28977af2004-04-05 01:30:19 +000011518 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011519 if (TD) {
11520 bool MadeChange = false;
11521 unsigned PtrSize = TD->getPointerSizeInBits();
11522
11523 gep_type_iterator GTI = gep_type_begin(GEP);
11524 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11525 I != E; ++I, ++GTI) {
11526 if (!isa<SequentialType>(*GTI)) continue;
11527
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011528 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011529 // to what we need. If narrower, sign-extend it to what we need. This
11530 // explicit cast can make subsequent optimizations more obvious.
11531 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011532 if (OpBits == PtrSize)
11533 continue;
11534
Chris Lattner2345d1d2009-08-30 20:01:10 +000011535 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011536 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011537 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011538 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011539 }
Chris Lattner28977af2004-04-05 01:30:19 +000011540
Chris Lattner90ac28c2002-08-02 19:29:35 +000011541 // Combine Indices - If the source pointer to this getelementptr instruction
11542 // is a getelementptr instruction, combine the indices of the two
11543 // getelementptr instructions into a single instruction.
11544 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011545 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011546 // Note that if our source is a gep chain itself that we wait for that
11547 // chain to be resolved before we perform this transformation. This
11548 // avoids us creating a TON of code in some cases.
11549 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011550 if (GetElementPtrInst *SrcGEP =
11551 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11552 if (SrcGEP->getNumOperands() == 2)
11553 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011554
Chris Lattner72588fc2007-02-15 22:48:32 +000011555 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011556
11557 // Find out whether the last index in the source GEP is a sequential idx.
11558 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011559 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11560 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011561 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011562
Chris Lattner90ac28c2002-08-02 19:29:35 +000011563 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011564 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011565 // Replace: gep (gep %P, long B), long A, ...
11566 // With: T = long A+B; gep %P, T, ...
11567 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011568 Value *Sum;
11569 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11570 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011571 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011572 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011573 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011574 Sum = SO1;
11575 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011576 // If they aren't the same type, then the input hasn't been processed
11577 // by the loop above yet (which canonicalizes sequential index types to
11578 // intptr_t). Just avoid transforming this until the input has been
11579 // normalized.
11580 if (SO1->getType() != GO1->getType())
11581 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011582 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011583 }
Chris Lattner620ce142004-05-07 22:09:22 +000011584
Chris Lattnerab984842009-08-30 05:30:55 +000011585 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011586 if (Src->getNumOperands() == 2) {
11587 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011588 GEP.setOperand(1, Sum);
11589 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011590 }
Chris Lattnerab984842009-08-30 05:30:55 +000011591 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011592 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011593 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011594 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011595 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011596 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011597 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011598 Indices.append(Src->op_begin()+1, Src->op_end());
11599 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011600 }
11601
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011602 if (!Indices.empty())
11603 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11604 Src->isInBounds()) ?
11605 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11606 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011607 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011608 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011609 }
11610
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011611 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11612 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011613 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011614
Chris Lattner2de23192009-08-30 20:38:21 +000011615 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11616 // want to change the gep until the bitcasts are eliminated.
11617 if (getBitCastOperand(X)) {
11618 Worklist.AddValue(PtrOp);
11619 return 0;
11620 }
11621
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011622 bool HasZeroPointerIndex = false;
11623 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11624 HasZeroPointerIndex = C->isZero();
11625
Chris Lattner963f4ba2009-08-30 20:36:46 +000011626 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11627 // into : GEP [10 x i8]* X, i32 0, ...
11628 //
11629 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11630 // into : GEP i8* X, ...
11631 //
11632 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011633 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011634 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11635 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011636 if (const ArrayType *CATy =
11637 dyn_cast<ArrayType>(CPTy->getElementType())) {
11638 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11639 if (CATy->getElementType() == XTy->getElementType()) {
11640 // -> GEP i8* X, ...
11641 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011642 return cast<GEPOperator>(&GEP)->isInBounds() ?
11643 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11644 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011645 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11646 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011647 }
11648
11649 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011650 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011651 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011652 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011653 // At this point, we know that the cast source type is a pointer
11654 // to an array of the same type as the destination pointer
11655 // array. Because the array type is never stepped over (there
11656 // is a leading zero) we can fold the cast into this GEP.
11657 GEP.setOperand(0, X);
11658 return &GEP;
11659 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011660 }
11661 }
Chris Lattnereed48272005-09-13 00:40:14 +000011662 } else if (GEP.getNumOperands() == 2) {
11663 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011664 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11665 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011666 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11667 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011668 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011669 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11670 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011671 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011672 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011673 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011674 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11675 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011676 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011677 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011678 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011679 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011680
11681 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011682 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011683 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011684 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011685
Owen Anderson1d0be152009-08-13 21:58:54 +000011686 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011687 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011688 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011689
11690 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11691 // allow either a mul, shift, or constant here.
11692 Value *NewIdx = 0;
11693 ConstantInt *Scale = 0;
11694 if (ArrayEltSize == 1) {
11695 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011696 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011697 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011698 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011699 Scale = CI;
11700 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11701 if (Inst->getOpcode() == Instruction::Shl &&
11702 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011703 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11704 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011705 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011706 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011707 NewIdx = Inst->getOperand(0);
11708 } else if (Inst->getOpcode() == Instruction::Mul &&
11709 isa<ConstantInt>(Inst->getOperand(1))) {
11710 Scale = cast<ConstantInt>(Inst->getOperand(1));
11711 NewIdx = Inst->getOperand(0);
11712 }
11713 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011714
Chris Lattner7835cdd2005-09-13 18:36:04 +000011715 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011716 // out, perform the transformation. Note, we don't know whether Scale is
11717 // signed or not. We'll use unsigned version of division/modulo
11718 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011719 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011720 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011721 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011722 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011723 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011724 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11725 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011726 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011727 }
11728
11729 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011730 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011731 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011732 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011733 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11734 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11735 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011736 // The NewGEP must be pointer typed, so must the old one -> BitCast
11737 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011738 }
11739 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011740 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011741 }
Chris Lattner58407792009-01-09 04:53:57 +000011742
Chris Lattner46cd5a12009-01-09 05:44:56 +000011743 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011744 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011745 /// Y = gep X, <...constant indices...>
11746 /// into a gep of the original struct. This is important for SROA and alias
11747 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011748 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011749 if (TD &&
11750 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011751 // Determine how much the GEP moves the pointer. We are guaranteed to get
11752 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011753 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011754 int64_t Offset = OffsetV->getSExtValue();
11755
11756 // If this GEP instruction doesn't move the pointer, just replace the GEP
11757 // with a bitcast of the real input to the dest type.
11758 if (Offset == 0) {
11759 // If the bitcast is of an allocation, and the allocation will be
11760 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011761 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011762 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011763 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11764 if (Instruction *I = visitBitCast(*BCI)) {
11765 if (I != BCI) {
11766 I->takeName(BCI);
11767 BCI->getParent()->getInstList().insert(BCI, I);
11768 ReplaceInstUsesWith(*BCI, I);
11769 }
11770 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011771 }
Chris Lattner58407792009-01-09 04:53:57 +000011772 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011773 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011774 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011775
11776 // Otherwise, if the offset is non-zero, we need to find out if there is a
11777 // field at Offset in 'A's type. If so, we can pull the cast through the
11778 // GEP.
11779 SmallVector<Value*, 8> NewIndices;
11780 const Type *InTy =
11781 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011782 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011783 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11784 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11785 NewIndices.end()) :
11786 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11787 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011788
11789 if (NGEP->getType() == GEP.getType())
11790 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011791 NGEP->takeName(&GEP);
11792 return new BitCastInst(NGEP, GEP.getType());
11793 }
Chris Lattner58407792009-01-09 04:53:57 +000011794 }
11795 }
11796
Chris Lattner8a2a3112001-12-14 16:52:21 +000011797 return 0;
11798}
11799
Victor Hernandez7b929da2009-10-23 21:09:37 +000011800Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000011801 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011802 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011803 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11804 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011805 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011806 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011807 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011808 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011809
Chris Lattner0864acf2002-11-04 16:18:53 +000011810 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011811 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011812 //
11813 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011814 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011815
11816 // Now that I is pointing to the first non-allocation-inst in the block,
11817 // insert our getelementptr instruction...
11818 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011819 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011820 Value *Idx[2];
11821 Idx[0] = NullIdx;
11822 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011823 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11824 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011825
11826 // Now make everything use the getelementptr instead of the original
11827 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011828 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011829 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011830 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011831 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011832 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011833
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011834 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011835 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011836 // Note that we only do this for alloca's, because malloc should allocate
11837 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011838 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011839 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011840
11841 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11842 if (AI.getAlignment() == 0)
11843 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11844 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011845
Chris Lattner0864acf2002-11-04 16:18:53 +000011846 return 0;
11847}
11848
Victor Hernandez66284e02009-10-24 04:23:03 +000011849Instruction *InstCombiner::visitFree(Instruction &FI) {
11850 Value *Op = FI.getOperand(1);
11851
11852 // free undef -> unreachable.
11853 if (isa<UndefValue>(Op)) {
11854 // Insert a new store to null because we cannot modify the CFG here.
11855 new StoreInst(ConstantInt::getTrue(*Context),
11856 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11857 return EraseInstFromFunction(FI);
11858 }
11859
11860 // If we have 'free null' delete the instruction. This can happen in stl code
11861 // when lots of inlining happens.
11862 if (isa<ConstantPointerNull>(Op))
11863 return EraseInstFromFunction(FI);
11864
Victor Hernandez046e78c2009-10-26 23:43:48 +000011865 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011866 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011867 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11868 if (Op->hasOneUse() && CI->hasOneUse()) {
11869 EraseInstFromFunction(FI);
11870 EraseInstFromFunction(*CI);
11871 return EraseInstFromFunction(*cast<Instruction>(Op));
11872 }
11873 } else {
11874 // Op is a call to malloc
11875 if (Op->hasOneUse()) {
11876 EraseInstFromFunction(FI);
11877 return EraseInstFromFunction(*cast<Instruction>(Op));
11878 }
11879 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011880 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011881
11882 return 0;
11883}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011884
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011885/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011886static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011887 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011888 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011889 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011890 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011891
Mon P Wang6753f952009-02-07 22:19:29 +000011892 const PointerType *DestTy = cast<PointerType>(CI->getType());
11893 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011894 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011895
11896 // If the address spaces don't match, don't eliminate the cast.
11897 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11898 return 0;
11899
Chris Lattnerb89e0712004-07-13 01:49:43 +000011900 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011901
Reid Spencer42230162007-01-22 05:51:25 +000011902 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011903 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011904 // If the source is an array, the code below will not succeed. Check to
11905 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11906 // constants.
11907 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11908 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11909 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011910 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011911 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11912 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011913 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011914 SrcTy = cast<PointerType>(CastOp->getType());
11915 SrcPTy = SrcTy->getElementType();
11916 }
11917
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011918 if (IC.getTargetData() &&
11919 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011920 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011921 // Do not allow turning this into a load of an integer, which is then
11922 // casted to a pointer, this pessimizes pointer analysis a lot.
11923 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011924 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11925 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011926
Chris Lattnerf9527852005-01-31 04:50:46 +000011927 // Okay, we are casting from one integer or pointer type to another of
11928 // the same size. Instead of casting the pointer before the load, cast
11929 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011930 Value *NewLoad =
11931 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011932 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011933 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011934 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011935 }
11936 }
11937 return 0;
11938}
11939
Chris Lattner833b8a42003-06-26 05:06:25 +000011940Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11941 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011942
Dan Gohman9941f742007-07-20 16:34:21 +000011943 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011944 if (TD) {
11945 unsigned KnownAlign =
11946 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11947 if (KnownAlign >
11948 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11949 LI.getAlignment()))
11950 LI.setAlignment(KnownAlign);
11951 }
Dan Gohman9941f742007-07-20 16:34:21 +000011952
Chris Lattner963f4ba2009-08-30 20:36:46 +000011953 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011954 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011955 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011956 return Res;
11957
11958 // None of the following transforms are legal for volatile loads.
11959 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011960
Dan Gohman2276a7b2008-10-15 23:19:35 +000011961 // Do really simple store-to-load forwarding and load CSE, to catch cases
11962 // where there are several consequtive memory accesses to the same location,
11963 // separated by a few arithmetic operations.
11964 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011965 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11966 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011967
Chris Lattner878e4942009-10-22 06:25:11 +000011968 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011969 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11970 const Value *GEPI0 = GEPI->getOperand(0);
11971 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011972 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011973 // Insert a new store to null instruction before the load to indicate
11974 // that this code is not reachable. We do this instead of inserting
11975 // an unreachable instruction directly because we cannot modify the
11976 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011977 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011978 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011979 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011980 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011981 }
Chris Lattner37366c12005-05-01 04:24:53 +000011982
Chris Lattner878e4942009-10-22 06:25:11 +000011983 // load null/undef -> unreachable
11984 // TODO: Consider a target hook for valid address spaces for this xform.
11985 if (isa<UndefValue>(Op) ||
11986 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11987 // Insert a new store to null instruction before the load to indicate that
11988 // this code is not reachable. We do this instead of inserting an
11989 // unreachable instruction directly because we cannot modify the CFG.
11990 new StoreInst(UndefValue::get(LI.getType()),
11991 Constant::getNullValue(Op->getType()), &LI);
11992 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011993 }
Chris Lattner878e4942009-10-22 06:25:11 +000011994
11995 // Instcombine load (constantexpr_cast global) -> cast (load global)
11996 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11997 if (CE->isCast())
11998 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11999 return Res;
12000
Chris Lattner37366c12005-05-01 04:24:53 +000012001 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012002 // Change select and PHI nodes to select values instead of addresses: this
12003 // helps alias analysis out a lot, allows many others simplifications, and
12004 // exposes redundancy in the code.
12005 //
12006 // Note that we cannot do the transformation unless we know that the
12007 // introduced loads cannot trap! Something like this is valid as long as
12008 // the condition is always false: load (select bool %C, int* null, int* %G),
12009 // but it would not be valid if we transformed it to load from null
12010 // unconditionally.
12011 //
12012 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12013 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012014 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12015 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012016 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12017 SI->getOperand(1)->getName()+".val");
12018 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12019 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012020 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012021 }
12022
Chris Lattner684fe212004-09-23 15:46:00 +000012023 // load (select (cond, null, P)) -> load P
12024 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12025 if (C->isNullValue()) {
12026 LI.setOperand(0, SI->getOperand(2));
12027 return &LI;
12028 }
12029
12030 // load (select (cond, P, null)) -> load P
12031 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12032 if (C->isNullValue()) {
12033 LI.setOperand(0, SI->getOperand(1));
12034 return &LI;
12035 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012036 }
12037 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012038 return 0;
12039}
12040
Reid Spencer55af2b52007-01-19 21:20:31 +000012041/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012042/// when possible. This makes it generally easy to do alias analysis and/or
12043/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012044static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12045 User *CI = cast<User>(SI.getOperand(1));
12046 Value *CastOp = CI->getOperand(0);
12047
12048 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012049 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12050 if (SrcTy == 0) return 0;
12051
12052 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012053
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012054 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12055 return 0;
12056
Chris Lattner3914f722009-01-24 01:00:13 +000012057 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12058 /// to its first element. This allows us to handle things like:
12059 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12060 /// on 32-bit hosts.
12061 SmallVector<Value*, 4> NewGEPIndices;
12062
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012063 // If the source is an array, the code below will not succeed. Check to
12064 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12065 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012066 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12067 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000012068 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012069 NewGEPIndices.push_back(Zero);
12070
12071 while (1) {
12072 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012073 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012074 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012075 NewGEPIndices.push_back(Zero);
12076 SrcPTy = STy->getElementType(0);
12077 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12078 NewGEPIndices.push_back(Zero);
12079 SrcPTy = ATy->getElementType();
12080 } else {
12081 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012082 }
Chris Lattner3914f722009-01-24 01:00:13 +000012083 }
12084
Owen Andersondebcb012009-07-29 22:17:13 +000012085 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012086 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012087
12088 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12089 return 0;
12090
Chris Lattner71759c42009-01-16 20:12:52 +000012091 // If the pointers point into different address spaces or if they point to
12092 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012093 if (!IC.getTargetData() ||
12094 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012095 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012096 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12097 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012098 return 0;
12099
12100 // Okay, we are casting from one integer or pointer type to another of
12101 // the same size. Instead of casting the pointer before
12102 // the store, cast the value to be stored.
12103 Value *NewCast;
12104 Value *SIOp0 = SI.getOperand(0);
12105 Instruction::CastOps opcode = Instruction::BitCast;
12106 const Type* CastSrcTy = SIOp0->getType();
12107 const Type* CastDstTy = SrcPTy;
12108 if (isa<PointerType>(CastDstTy)) {
12109 if (CastSrcTy->isInteger())
12110 opcode = Instruction::IntToPtr;
12111 } else if (isa<IntegerType>(CastDstTy)) {
12112 if (isa<PointerType>(SIOp0->getType()))
12113 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012114 }
Chris Lattner3914f722009-01-24 01:00:13 +000012115
12116 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12117 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012118 if (!NewGEPIndices.empty())
12119 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12120 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012121
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012122 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12123 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012124 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012125}
12126
Chris Lattner4aebaee2008-11-27 08:56:30 +000012127/// equivalentAddressValues - Test if A and B will obviously have the same
12128/// value. This includes recognizing that %t0 and %t1 will have the same
12129/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012130/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012131/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012132/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012133/// %t2 = load i32* %t1
12134///
12135static bool equivalentAddressValues(Value *A, Value *B) {
12136 // Test if the values are trivially equivalent.
12137 if (A == B) return true;
12138
12139 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012140 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12141 // its only used to compare two uses within the same basic block, which
12142 // means that they'll always either have the same value or one of them
12143 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012144 if (isa<BinaryOperator>(A) ||
12145 isa<CastInst>(A) ||
12146 isa<PHINode>(A) ||
12147 isa<GetElementPtrInst>(A))
12148 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012149 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012150 return true;
12151
12152 // Otherwise they may not be equivalent.
12153 return false;
12154}
12155
Dale Johannesen4945c652009-03-03 21:26:39 +000012156// If this instruction has two uses, one of which is a llvm.dbg.declare,
12157// return the llvm.dbg.declare.
12158DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12159 if (!V->hasNUses(2))
12160 return 0;
12161 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12162 UI != E; ++UI) {
12163 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12164 return DI;
12165 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12166 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12167 return DI;
12168 }
12169 }
12170 return 0;
12171}
12172
Chris Lattner2f503e62005-01-31 05:36:43 +000012173Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12174 Value *Val = SI.getOperand(0);
12175 Value *Ptr = SI.getOperand(1);
12176
Chris Lattner836692d2007-01-15 06:51:56 +000012177 // If the RHS is an alloca with a single use, zapify the store, making the
12178 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012179 // If the RHS is an alloca with a two uses, the other one being a
12180 // llvm.dbg.declare, zapify the store and the declare, making the
12181 // alloca dead. We must do this to prevent declare's from affecting
12182 // codegen.
12183 if (!SI.isVolatile()) {
12184 if (Ptr->hasOneUse()) {
12185 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012186 EraseInstFromFunction(SI);
12187 ++NumCombined;
12188 return 0;
12189 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012190 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12191 if (isa<AllocaInst>(GEP->getOperand(0))) {
12192 if (GEP->getOperand(0)->hasOneUse()) {
12193 EraseInstFromFunction(SI);
12194 ++NumCombined;
12195 return 0;
12196 }
12197 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12198 EraseInstFromFunction(*DI);
12199 EraseInstFromFunction(SI);
12200 ++NumCombined;
12201 return 0;
12202 }
12203 }
12204 }
12205 }
12206 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12207 EraseInstFromFunction(*DI);
12208 EraseInstFromFunction(SI);
12209 ++NumCombined;
12210 return 0;
12211 }
Chris Lattner836692d2007-01-15 06:51:56 +000012212 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012213
Dan Gohman9941f742007-07-20 16:34:21 +000012214 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012215 if (TD) {
12216 unsigned KnownAlign =
12217 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12218 if (KnownAlign >
12219 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12220 SI.getAlignment()))
12221 SI.setAlignment(KnownAlign);
12222 }
Dan Gohman9941f742007-07-20 16:34:21 +000012223
Dale Johannesenacb51a32009-03-03 01:43:03 +000012224 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012225 // stores to the same location, separated by a few arithmetic operations. This
12226 // situation often occurs with bitfield accesses.
12227 BasicBlock::iterator BBI = &SI;
12228 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12229 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012230 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012231 // Don't count debug info directives, lest they affect codegen,
12232 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12233 // It is necessary for correctness to skip those that feed into a
12234 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012235 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012236 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012237 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012238 continue;
12239 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012240
12241 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12242 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012243 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12244 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012245 ++NumDeadStore;
12246 ++BBI;
12247 EraseInstFromFunction(*PrevSI);
12248 continue;
12249 }
12250 break;
12251 }
12252
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012253 // If this is a load, we have to stop. However, if the loaded value is from
12254 // the pointer we're loading and is producing the pointer we're storing,
12255 // then *this* store is dead (X = load P; store X -> P).
12256 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012257 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12258 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012259 EraseInstFromFunction(SI);
12260 ++NumCombined;
12261 return 0;
12262 }
12263 // Otherwise, this is a load from some other location. Stores before it
12264 // may not be dead.
12265 break;
12266 }
12267
Chris Lattner9ca96412006-02-08 03:25:32 +000012268 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012269 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012270 break;
12271 }
12272
12273
12274 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012275
12276 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012277 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012278 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012279 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012280 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012281 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012282 ++NumCombined;
12283 }
12284 return 0; // Do not modify these!
12285 }
12286
12287 // store undef, Ptr -> noop
12288 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012289 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012290 ++NumCombined;
12291 return 0;
12292 }
12293
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012294 // If the pointer destination is a cast, see if we can fold the cast into the
12295 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012296 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012297 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12298 return Res;
12299 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012300 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012301 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12302 return Res;
12303
Chris Lattner408902b2005-09-12 23:23:25 +000012304
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012305 // If this store is the last instruction in the basic block (possibly
12306 // excepting debug info instructions and the pointer bitcasts that feed
12307 // into them), and if the block ends with an unconditional branch, try
12308 // to move it to the successor block.
12309 BBI = &SI;
12310 do {
12311 ++BBI;
12312 } while (isa<DbgInfoIntrinsic>(BBI) ||
12313 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012314 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012315 if (BI->isUnconditional())
12316 if (SimplifyStoreAtEndOfBlock(SI))
12317 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012318
Chris Lattner2f503e62005-01-31 05:36:43 +000012319 return 0;
12320}
12321
Chris Lattner3284d1f2007-04-15 00:07:55 +000012322/// SimplifyStoreAtEndOfBlock - Turn things like:
12323/// if () { *P = v1; } else { *P = v2 }
12324/// into a phi node with a store in the successor.
12325///
Chris Lattner31755a02007-04-15 01:02:18 +000012326/// Simplify things like:
12327/// *P = v1; if () { *P = v2; }
12328/// into a phi node with a store in the successor.
12329///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012330bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12331 BasicBlock *StoreBB = SI.getParent();
12332
12333 // Check to see if the successor block has exactly two incoming edges. If
12334 // so, see if the other predecessor contains a store to the same location.
12335 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012336 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012337
12338 // Determine whether Dest has exactly two predecessors and, if so, compute
12339 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012340 pred_iterator PI = pred_begin(DestBB);
12341 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012342 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012343 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012344 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012345 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012346 return false;
12347
12348 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012349 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012350 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012351 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012352 }
Chris Lattner31755a02007-04-15 01:02:18 +000012353 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012354 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012355
12356 // Bail out if all the relevant blocks aren't distinct (this can happen,
12357 // for example, if SI is in an infinite loop)
12358 if (StoreBB == DestBB || OtherBB == DestBB)
12359 return false;
12360
Chris Lattner31755a02007-04-15 01:02:18 +000012361 // Verify that the other block ends in a branch and is not otherwise empty.
12362 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012363 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012364 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012365 return false;
12366
Chris Lattner31755a02007-04-15 01:02:18 +000012367 // If the other block ends in an unconditional branch, check for the 'if then
12368 // else' case. there is an instruction before the branch.
12369 StoreInst *OtherStore = 0;
12370 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012371 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012372 // Skip over debugging info.
12373 while (isa<DbgInfoIntrinsic>(BBI) ||
12374 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12375 if (BBI==OtherBB->begin())
12376 return false;
12377 --BBI;
12378 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012379 // If this isn't a store, isn't a store to the same location, or if the
12380 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012381 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012382 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12383 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012384 return false;
12385 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012386 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012387 // destinations is StoreBB, then we have the if/then case.
12388 if (OtherBr->getSuccessor(0) != StoreBB &&
12389 OtherBr->getSuccessor(1) != StoreBB)
12390 return false;
12391
12392 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012393 // if/then triangle. See if there is a store to the same ptr as SI that
12394 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012395 for (;; --BBI) {
12396 // Check to see if we find the matching store.
12397 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012398 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12399 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012400 return false;
12401 break;
12402 }
Eli Friedman6903a242008-06-13 22:02:12 +000012403 // If we find something that may be using or overwriting the stored
12404 // value, or if we run out of instructions, we can't do the xform.
12405 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012406 BBI == OtherBB->begin())
12407 return false;
12408 }
12409
12410 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012411 // make sure nothing reads or overwrites the stored value in
12412 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012413 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12414 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012415 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012416 return false;
12417 }
12418 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012419
Chris Lattner31755a02007-04-15 01:02:18 +000012420 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012421 Value *MergedVal = OtherStore->getOperand(0);
12422 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012423 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012424 PN->reserveOperandSpace(2);
12425 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012426 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12427 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012428 }
12429
12430 // Advance to a place where it is safe to insert the new store and
12431 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012432 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012433 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012434 OtherStore->isVolatile(),
12435 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012436
12437 // Nuke the old stores.
12438 EraseInstFromFunction(SI);
12439 EraseInstFromFunction(*OtherStore);
12440 ++NumCombined;
12441 return true;
12442}
12443
Chris Lattner2f503e62005-01-31 05:36:43 +000012444
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012445Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12446 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012447 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012448 BasicBlock *TrueDest;
12449 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012450 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012451 !isa<Constant>(X)) {
12452 // Swap Destinations and condition...
12453 BI.setCondition(X);
12454 BI.setSuccessor(0, FalseDest);
12455 BI.setSuccessor(1, TrueDest);
12456 return &BI;
12457 }
12458
Reid Spencere4d87aa2006-12-23 06:05:41 +000012459 // Cannonicalize fcmp_one -> fcmp_oeq
12460 FCmpInst::Predicate FPred; Value *Y;
12461 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012462 TrueDest, FalseDest)) &&
12463 BI.getCondition()->hasOneUse())
12464 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12465 FPred == FCmpInst::FCMP_OGE) {
12466 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12467 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12468
12469 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012470 BI.setSuccessor(0, FalseDest);
12471 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012472 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012473 return &BI;
12474 }
12475
12476 // Cannonicalize icmp_ne -> icmp_eq
12477 ICmpInst::Predicate IPred;
12478 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012479 TrueDest, FalseDest)) &&
12480 BI.getCondition()->hasOneUse())
12481 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12482 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12483 IPred == ICmpInst::ICMP_SGE) {
12484 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12485 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12486 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012487 BI.setSuccessor(0, FalseDest);
12488 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012489 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012490 return &BI;
12491 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012492
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012493 return 0;
12494}
Chris Lattner0864acf2002-11-04 16:18:53 +000012495
Chris Lattner46238a62004-07-03 00:26:11 +000012496Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12497 Value *Cond = SI.getCondition();
12498 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12499 if (I->getOpcode() == Instruction::Add)
12500 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12501 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12502 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012503 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012504 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012505 AddRHS));
12506 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012507 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012508 return &SI;
12509 }
12510 }
12511 return 0;
12512}
12513
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012514Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012515 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012516
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012517 if (!EV.hasIndices())
12518 return ReplaceInstUsesWith(EV, Agg);
12519
12520 if (Constant *C = dyn_cast<Constant>(Agg)) {
12521 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012522 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012523
12524 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012525 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012526
12527 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12528 // Extract the element indexed by the first index out of the constant
12529 Value *V = C->getOperand(*EV.idx_begin());
12530 if (EV.getNumIndices() > 1)
12531 // Extract the remaining indices out of the constant indexed by the
12532 // first index
12533 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12534 else
12535 return ReplaceInstUsesWith(EV, V);
12536 }
12537 return 0; // Can't handle other constants
12538 }
12539 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12540 // We're extracting from an insertvalue instruction, compare the indices
12541 const unsigned *exti, *exte, *insi, *inse;
12542 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12543 exte = EV.idx_end(), inse = IV->idx_end();
12544 exti != exte && insi != inse;
12545 ++exti, ++insi) {
12546 if (*insi != *exti)
12547 // The insert and extract both reference distinctly different elements.
12548 // This means the extract is not influenced by the insert, and we can
12549 // replace the aggregate operand of the extract with the aggregate
12550 // operand of the insert. i.e., replace
12551 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12552 // %E = extractvalue { i32, { i32 } } %I, 0
12553 // with
12554 // %E = extractvalue { i32, { i32 } } %A, 0
12555 return ExtractValueInst::Create(IV->getAggregateOperand(),
12556 EV.idx_begin(), EV.idx_end());
12557 }
12558 if (exti == exte && insi == inse)
12559 // Both iterators are at the end: Index lists are identical. Replace
12560 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12561 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12562 // with "i32 42"
12563 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12564 if (exti == exte) {
12565 // The extract list is a prefix of the insert list. i.e. replace
12566 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12567 // %E = extractvalue { i32, { i32 } } %I, 1
12568 // with
12569 // %X = extractvalue { i32, { i32 } } %A, 1
12570 // %E = insertvalue { i32 } %X, i32 42, 0
12571 // by switching the order of the insert and extract (though the
12572 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012573 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12574 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012575 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12576 insi, inse);
12577 }
12578 if (insi == inse)
12579 // The insert list is a prefix of the extract list
12580 // We can simply remove the common indices from the extract and make it
12581 // operate on the inserted value instead of the insertvalue result.
12582 // i.e., replace
12583 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12584 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12585 // with
12586 // %E extractvalue { i32 } { i32 42 }, 0
12587 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12588 exti, exte);
12589 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012590 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12591 // We're extracting from an intrinsic, see if we're the only user, which
12592 // allows us to simplify multiple result intrinsics to simpler things that
12593 // just get one value..
12594 if (II->hasOneUse()) {
12595 // Check if we're grabbing the overflow bit or the result of a 'with
12596 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12597 // and replace it with a traditional binary instruction.
12598 switch (II->getIntrinsicID()) {
12599 case Intrinsic::uadd_with_overflow:
12600 case Intrinsic::sadd_with_overflow:
12601 if (*EV.idx_begin() == 0) { // Normal result.
12602 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12603 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12604 EraseInstFromFunction(*II);
12605 return BinaryOperator::CreateAdd(LHS, RHS);
12606 }
12607 break;
12608 case Intrinsic::usub_with_overflow:
12609 case Intrinsic::ssub_with_overflow:
12610 if (*EV.idx_begin() == 0) { // Normal result.
12611 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12612 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12613 EraseInstFromFunction(*II);
12614 return BinaryOperator::CreateSub(LHS, RHS);
12615 }
12616 break;
12617 case Intrinsic::umul_with_overflow:
12618 case Intrinsic::smul_with_overflow:
12619 if (*EV.idx_begin() == 0) { // Normal result.
12620 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12621 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12622 EraseInstFromFunction(*II);
12623 return BinaryOperator::CreateMul(LHS, RHS);
12624 }
12625 break;
12626 default:
12627 break;
12628 }
12629 }
12630 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012631 // Can't simplify extracts from other values. Note that nested extracts are
12632 // already simplified implicitely by the above (extract ( extract (insert) )
12633 // will be translated into extract ( insert ( extract ) ) first and then just
12634 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012635 return 0;
12636}
12637
Chris Lattner220b0cf2006-03-05 00:22:33 +000012638/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12639/// is to leave as a vector operation.
12640static bool CheapToScalarize(Value *V, bool isConstant) {
12641 if (isa<ConstantAggregateZero>(V))
12642 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012643 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012644 if (isConstant) return true;
12645 // If all elts are the same, we can extract.
12646 Constant *Op0 = C->getOperand(0);
12647 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12648 if (C->getOperand(i) != Op0)
12649 return false;
12650 return true;
12651 }
12652 Instruction *I = dyn_cast<Instruction>(V);
12653 if (!I) return false;
12654
12655 // Insert element gets simplified to the inserted element or is deleted if
12656 // this is constant idx extract element and its a constant idx insertelt.
12657 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12658 isa<ConstantInt>(I->getOperand(2)))
12659 return true;
12660 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12661 return true;
12662 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12663 if (BO->hasOneUse() &&
12664 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12665 CheapToScalarize(BO->getOperand(1), isConstant)))
12666 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012667 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12668 if (CI->hasOneUse() &&
12669 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12670 CheapToScalarize(CI->getOperand(1), isConstant)))
12671 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012672
12673 return false;
12674}
12675
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012676/// Read and decode a shufflevector mask.
12677///
12678/// It turns undef elements into values that are larger than the number of
12679/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012680static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12681 unsigned NElts = SVI->getType()->getNumElements();
12682 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12683 return std::vector<unsigned>(NElts, 0);
12684 if (isa<UndefValue>(SVI->getOperand(2)))
12685 return std::vector<unsigned>(NElts, 2*NElts);
12686
12687 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012688 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012689 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12690 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012691 Result.push_back(NElts*2); // undef -> 8
12692 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012693 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012694 return Result;
12695}
12696
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012697/// FindScalarElement - Given a vector and an element number, see if the scalar
12698/// value is already around as a register, for example if it were inserted then
12699/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012700static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012701 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012702 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12703 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012704 unsigned Width = PTy->getNumElements();
12705 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012706 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012707
12708 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012709 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012710 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012711 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012712 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012713 return CP->getOperand(EltNo);
12714 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12715 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012716 if (!isa<ConstantInt>(III->getOperand(2)))
12717 return 0;
12718 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012719
12720 // If this is an insert to the element we are looking for, return the
12721 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012722 if (EltNo == IIElt)
12723 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012724
12725 // Otherwise, the insertelement doesn't modify the value, recurse on its
12726 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012727 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012728 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012729 unsigned LHSWidth =
12730 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012731 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012732 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012733 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012734 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012735 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012736 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012737 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012738 }
12739
12740 // Otherwise, we don't know.
12741 return 0;
12742}
12743
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012744Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012745 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012746 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012747 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012748
Dan Gohman07a96762007-07-16 14:29:03 +000012749 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012750 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012751 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012752
Reid Spencer9d6565a2007-02-15 02:26:10 +000012753 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012754 // If vector val is constant with all elements the same, replace EI with
12755 // that element. When the elements are not identical, we cannot replace yet
12756 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012757 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012758 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012759 if (C->getOperand(i) != op0) {
12760 op0 = 0;
12761 break;
12762 }
12763 if (op0)
12764 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012765 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012766
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012767 // If extracting a specified index from the vector, see if we can recursively
12768 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012769 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012770 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012771 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012772
12773 // If this is extracting an invalid index, turn this into undef, to avoid
12774 // crashing the code below.
12775 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012776 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012777
Chris Lattner867b99f2006-10-05 06:55:50 +000012778 // This instruction only demands the single element from the input vector.
12779 // If the input vector has a single use, simplify it based on this use
12780 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012781 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012782 APInt UndefElts(VectorWidth, 0);
12783 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012784 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012785 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012786 EI.setOperand(0, V);
12787 return &EI;
12788 }
12789 }
12790
Owen Andersond672ecb2009-07-03 00:17:18 +000012791 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012792 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012793
12794 // If the this extractelement is directly using a bitcast from a vector of
12795 // the same number of elements, see if we can find the source element from
12796 // it. In this case, we will end up needing to bitcast the scalars.
12797 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12798 if (const VectorType *VT =
12799 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12800 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012801 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12802 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012803 return new BitCastInst(Elt, EI.getType());
12804 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012805 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012806
Chris Lattner73fa49d2006-05-25 22:53:38 +000012807 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012808 // Push extractelement into predecessor operation if legal and
12809 // profitable to do so
12810 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12811 if (I->hasOneUse() &&
12812 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12813 Value *newEI0 =
12814 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12815 EI.getName()+".lhs");
12816 Value *newEI1 =
12817 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12818 EI.getName()+".rhs");
12819 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012820 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012821 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012822 // Extracting the inserted element?
12823 if (IE->getOperand(2) == EI.getOperand(1))
12824 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12825 // If the inserted and extracted elements are constants, they must not
12826 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012827 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012828 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012829 EI.setOperand(0, IE->getOperand(0));
12830 return &EI;
12831 }
12832 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12833 // If this is extracting an element from a shufflevector, figure out where
12834 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012835 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12836 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012837 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012838 unsigned LHSWidth =
12839 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12840
12841 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012842 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012843 else if (SrcIdx < LHSWidth*2) {
12844 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012845 Src = SVI->getOperand(1);
12846 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012847 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012848 }
Eric Christophera3500da2009-07-25 02:28:41 +000012849 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012850 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12851 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012852 }
12853 }
Eli Friedman2451a642009-07-18 23:06:53 +000012854 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012855 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012856 return 0;
12857}
12858
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012859/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12860/// elements from either LHS or RHS, return the shuffle mask and true.
12861/// Otherwise, return false.
12862static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012863 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012864 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012865 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12866 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012867 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012868
12869 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012870 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012871 return true;
12872 } else if (V == LHS) {
12873 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012874 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012875 return true;
12876 } else if (V == RHS) {
12877 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012878 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012879 return true;
12880 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12881 // If this is an insert of an extract from some other vector, include it.
12882 Value *VecOp = IEI->getOperand(0);
12883 Value *ScalarOp = IEI->getOperand(1);
12884 Value *IdxOp = IEI->getOperand(2);
12885
Chris Lattnerd929f062006-04-27 21:14:21 +000012886 if (!isa<ConstantInt>(IdxOp))
12887 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012888 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012889
12890 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12891 // Okay, we can handle this if the vector we are insertinting into is
12892 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012893 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012894 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012895 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012896 return true;
12897 }
12898 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12899 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012900 EI->getOperand(0)->getType() == V->getType()) {
12901 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012902 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012903
12904 // This must be extracting from either LHS or RHS.
12905 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12906 // Okay, we can handle this if the vector we are insertinting into is
12907 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012908 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012909 // If so, update the mask to reflect the inserted value.
12910 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012911 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012912 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012913 } else {
12914 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012915 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012916 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012917
12918 }
12919 return true;
12920 }
12921 }
12922 }
12923 }
12924 }
12925 // TODO: Handle shufflevector here!
12926
12927 return false;
12928}
12929
12930/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12931/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12932/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012933static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012934 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012935 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012936 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012937 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012938 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012939
12940 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012941 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012942 return V;
12943 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012944 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012945 return V;
12946 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12947 // If this is an insert of an extract from some other vector, include it.
12948 Value *VecOp = IEI->getOperand(0);
12949 Value *ScalarOp = IEI->getOperand(1);
12950 Value *IdxOp = IEI->getOperand(2);
12951
12952 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12953 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12954 EI->getOperand(0)->getType() == V->getType()) {
12955 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012956 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12957 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012958
12959 // Either the extracted from or inserted into vector must be RHSVec,
12960 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012961 if (EI->getOperand(0) == RHS || RHS == 0) {
12962 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012963 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012964 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012965 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012966 return V;
12967 }
12968
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012969 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012970 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12971 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012972 // Everything but the extracted element is replaced with the RHS.
12973 for (unsigned i = 0; i != NumElts; ++i) {
12974 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012975 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012976 }
12977 return V;
12978 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012979
12980 // If this insertelement is a chain that comes from exactly these two
12981 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012982 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12983 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012984 return EI->getOperand(0);
12985
Chris Lattnerefb47352006-04-15 01:39:45 +000012986 }
12987 }
12988 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012989 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012990
12991 // Otherwise, can't do anything fancy. Return an identity vector.
12992 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012993 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012994 return V;
12995}
12996
12997Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12998 Value *VecOp = IE.getOperand(0);
12999 Value *ScalarOp = IE.getOperand(1);
13000 Value *IdxOp = IE.getOperand(2);
13001
Chris Lattner599ded12007-04-09 01:11:16 +000013002 // Inserting an undef or into an undefined place, remove this.
13003 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13004 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013005
Chris Lattnerefb47352006-04-15 01:39:45 +000013006 // If the inserted element was extracted from some other vector, and if the
13007 // indexes are constant, try to turn this into a shufflevector operation.
13008 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13009 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13010 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013011 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013012 unsigned ExtractedIdx =
13013 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013014 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013015
13016 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13017 return ReplaceInstUsesWith(IE, VecOp);
13018
13019 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013020 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013021
13022 // If we are extracting a value from a vector, then inserting it right
13023 // back into the same place, just use the input vector.
13024 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13025 return ReplaceInstUsesWith(IE, VecOp);
13026
Chris Lattnerefb47352006-04-15 01:39:45 +000013027 // If this insertelement isn't used by some other insertelement, turn it
13028 // (and any insertelements it points to), into one big shuffle.
13029 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13030 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013031 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000013032 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013033 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013034 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013035 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013036 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013037 }
13038 }
13039 }
13040
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013041 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13042 APInt UndefElts(VWidth, 0);
13043 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13044 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13045 return &IE;
13046
Chris Lattnerefb47352006-04-15 01:39:45 +000013047 return 0;
13048}
13049
13050
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013051Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13052 Value *LHS = SVI.getOperand(0);
13053 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013054 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013055
13056 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013057
Chris Lattner867b99f2006-10-05 06:55:50 +000013058 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013059 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013060 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013061
Dan Gohman488fbfc2008-09-09 18:11:14 +000013062 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013063
13064 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13065 return 0;
13066
Evan Cheng388df622009-02-03 10:05:09 +000013067 APInt UndefElts(VWidth, 0);
13068 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13069 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013070 LHS = SVI.getOperand(0);
13071 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013072 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013073 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013074
Chris Lattner863bcff2006-05-25 23:48:38 +000013075 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13076 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13077 if (LHS == RHS || isa<UndefValue>(LHS)) {
13078 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013079 // shuffle(undef,undef,mask) -> undef.
13080 return ReplaceInstUsesWith(SVI, LHS);
13081 }
13082
Chris Lattner863bcff2006-05-25 23:48:38 +000013083 // Remap any references to RHS to use LHS.
13084 std::vector<Constant*> Elts;
13085 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013086 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000013087 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013088 else {
13089 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013090 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013091 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013092 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000013093 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013094 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000013095 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013096 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013097 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013098 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013099 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013100 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013101 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013102 LHS = SVI.getOperand(0);
13103 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013104 MadeChange = true;
13105 }
13106
Chris Lattner7b2e27922006-05-26 00:29:06 +000013107 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013108 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013109
Chris Lattner863bcff2006-05-25 23:48:38 +000013110 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13111 if (Mask[i] >= e*2) continue; // Ignore undef values.
13112 // Is this an identity shuffle of the LHS value?
13113 isLHSID &= (Mask[i] == i);
13114
13115 // Is this an identity shuffle of the RHS value?
13116 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013117 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013118
Chris Lattner863bcff2006-05-25 23:48:38 +000013119 // Eliminate identity shuffles.
13120 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13121 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013122
Chris Lattner7b2e27922006-05-26 00:29:06 +000013123 // If the LHS is a shufflevector itself, see if we can combine it with this
13124 // one without producing an unusual shuffle. Here we are really conservative:
13125 // we are absolutely afraid of producing a shuffle mask not in the input
13126 // program, because the code gen may not be smart enough to turn a merged
13127 // shuffle into two specific shuffles: it may produce worse code. As such,
13128 // we only merge two shuffles if the result is one of the two input shuffle
13129 // masks. In this case, merging the shuffles just removes one instruction,
13130 // which we know is safe. This is good for things like turning:
13131 // (splat(splat)) -> splat.
13132 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13133 if (isa<UndefValue>(RHS)) {
13134 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13135
David Greenef941d292009-11-16 21:52:23 +000013136 if (LHSMask.size() == Mask.size()) {
13137 std::vector<unsigned> NewMask;
13138 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013139 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013140 NewMask.push_back(2*e);
13141 else
13142 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013143
David Greenef941d292009-11-16 21:52:23 +000013144 // If the result mask is equal to the src shuffle or this
13145 // shuffle mask, do the replacement.
13146 if (NewMask == LHSMask || NewMask == Mask) {
13147 unsigned LHSInNElts =
13148 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13149 getNumElements();
13150 std::vector<Constant*> Elts;
13151 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13152 if (NewMask[i] >= LHSInNElts*2) {
13153 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13154 } else {
13155 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13156 NewMask[i]));
13157 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013158 }
David Greenef941d292009-11-16 21:52:23 +000013159 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13160 LHSSVI->getOperand(1),
13161 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013162 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013163 }
13164 }
13165 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013166
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013167 return MadeChange ? &SVI : 0;
13168}
13169
13170
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013171
Chris Lattnerea1c4542004-12-08 23:43:58 +000013172
13173/// TryToSinkInstruction - Try to move the specified instruction from its
13174/// current block into the beginning of DestBlock, which can only happen if it's
13175/// safe to move the instruction past all of the instructions between it and the
13176/// end of its block.
13177static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13178 assert(I->hasOneUse() && "Invariants didn't hold!");
13179
Chris Lattner108e9022005-10-27 17:13:11 +000013180 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013181 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013182 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013183
Chris Lattnerea1c4542004-12-08 23:43:58 +000013184 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013185 if (isa<AllocaInst>(I) && I->getParent() ==
13186 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013187 return false;
13188
Chris Lattner96a52a62004-12-09 07:14:34 +000013189 // We can only sink load instructions if there is nothing between the load and
13190 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013191 if (I->mayReadFromMemory()) {
13192 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013193 Scan != E; ++Scan)
13194 if (Scan->mayWriteToMemory())
13195 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013196 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013197
Dan Gohman02dea8b2008-05-23 21:05:58 +000013198 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013199
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013200 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013201 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013202 ++NumSunkInst;
13203 return true;
13204}
13205
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013206
13207/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13208/// all reachable code to the worklist.
13209///
13210/// This has a couple of tricks to make the code faster and more powerful. In
13211/// particular, we constant fold and DCE instructions as we go, to avoid adding
13212/// them to the worklist (this significantly speeds up instcombine on code where
13213/// many instructions are dead or constant). Additionally, if we find a branch
13214/// whose condition is a known constant, we only visit the reachable successors.
13215///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013216static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013217 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013218 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013219 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013220 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013221 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013222 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013223
13224 std::vector<Instruction*> InstrsForInstCombineWorklist;
13225 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013226
Chris Lattner2ee743b2009-10-15 04:59:28 +000013227 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13228
Chris Lattner2c7718a2007-03-23 19:17:18 +000013229 while (!Worklist.empty()) {
13230 BB = Worklist.back();
13231 Worklist.pop_back();
13232
13233 // We have now visited this block! If we've already been here, ignore it.
13234 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013235
Chris Lattner2c7718a2007-03-23 19:17:18 +000013236 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13237 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013238
Chris Lattner2c7718a2007-03-23 19:17:18 +000013239 // DCE instruction if trivially dead.
13240 if (isInstructionTriviallyDead(Inst)) {
13241 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013242 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013243 Inst->eraseFromParent();
13244 continue;
13245 }
13246
13247 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013248 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013249 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013250 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13251 << *Inst << '\n');
13252 Inst->replaceAllUsesWith(C);
13253 ++NumConstProp;
13254 Inst->eraseFromParent();
13255 continue;
13256 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013257
13258
13259
13260 if (TD) {
13261 // See if we can constant fold its operands.
13262 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13263 i != e; ++i) {
13264 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13265 if (CE == 0) continue;
13266
13267 // If we already folded this constant, don't try again.
13268 if (!FoldedConstants.insert(CE))
13269 continue;
13270
Chris Lattner7b550cc2009-11-06 04:27:31 +000013271 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013272 if (NewC && NewC != CE) {
13273 *i = NewC;
13274 MadeIRChange = true;
13275 }
13276 }
13277 }
13278
Devang Patel7fe1dec2008-11-19 18:56:50 +000013279
Chris Lattner67f7d542009-10-12 03:58:40 +000013280 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013281 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013282
13283 // Recursively visit successors. If this is a branch or switch on a
13284 // constant, only visit the reachable successor.
13285 TerminatorInst *TI = BB->getTerminator();
13286 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13287 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13288 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013289 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013290 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013291 continue;
13292 }
13293 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13294 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13295 // See if this is an explicit destination.
13296 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13297 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013298 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013299 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013300 continue;
13301 }
13302
13303 // Otherwise it is the default destination.
13304 Worklist.push_back(SI->getSuccessor(0));
13305 continue;
13306 }
13307 }
13308
13309 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13310 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013311 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013312
13313 // Once we've found all of the instructions to add to instcombine's worklist,
13314 // add them in reverse order. This way instcombine will visit from the top
13315 // of the function down. This jives well with the way that it adds all uses
13316 // of instructions to the worklist after doing a transformation, thus avoiding
13317 // some N^2 behavior in pathological cases.
13318 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13319 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013320
13321 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013322}
13323
Chris Lattnerec9c3582007-03-03 02:04:50 +000013324bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013325 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013326
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013327 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13328 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013329
Chris Lattnerb3d59702005-07-07 20:40:38 +000013330 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013331 // Do a depth-first traversal of the function, populate the worklist with
13332 // the reachable instructions. Ignore blocks that are not reachable. Keep
13333 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013334 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013335 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013336
Chris Lattnerb3d59702005-07-07 20:40:38 +000013337 // Do a quick scan over the function. If we find any blocks that are
13338 // unreachable, remove any instructions inside of them. This prevents
13339 // the instcombine code from having to deal with some bad special cases.
13340 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13341 if (!Visited.count(BB)) {
13342 Instruction *Term = BB->getTerminator();
13343 while (Term != BB->begin()) { // Remove instrs bottom-up
13344 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013345
Chris Lattnerbdff5482009-08-23 04:37:46 +000013346 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013347 // A debug intrinsic shouldn't force another iteration if we weren't
13348 // going to do one without it.
13349 if (!isa<DbgInfoIntrinsic>(I)) {
13350 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013351 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013352 }
Devang Patel228ebd02009-10-13 22:56:32 +000013353
Devang Patel228ebd02009-10-13 22:56:32 +000013354 // If I is not void type then replaceAllUsesWith undef.
13355 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013356 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013357 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013358 I->eraseFromParent();
13359 }
13360 }
13361 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013362
Chris Lattner873ff012009-08-30 05:55:36 +000013363 while (!Worklist.isEmpty()) {
13364 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013365 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013366
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013367 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013368 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013369 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013370 EraseInstFromFunction(*I);
13371 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013372 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013373 continue;
13374 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013375
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013376 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013377 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013378 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013379 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013380
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013381 // Add operands to the worklist.
13382 ReplaceInstUsesWith(*I, C);
13383 ++NumConstProp;
13384 EraseInstFromFunction(*I);
13385 MadeIRChange = true;
13386 continue;
13387 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013388
Chris Lattnerea1c4542004-12-08 23:43:58 +000013389 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013390 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013391 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013392 Instruction *UserInst = cast<Instruction>(I->use_back());
13393 BasicBlock *UserParent;
13394
13395 // Get the block the use occurs in.
13396 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13397 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13398 else
13399 UserParent = UserInst->getParent();
13400
Chris Lattnerea1c4542004-12-08 23:43:58 +000013401 if (UserParent != BB) {
13402 bool UserIsSuccessor = false;
13403 // See if the user is one of our successors.
13404 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13405 if (*SI == UserParent) {
13406 UserIsSuccessor = true;
13407 break;
13408 }
13409
13410 // If the user is one of our immediate successors, and if that successor
13411 // only has us as a predecessors (we'd have to split the critical edge
13412 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013413 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013414 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013415 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013416 }
13417 }
13418
Chris Lattner74381062009-08-30 07:44:24 +000013419 // Now that we have an instruction, try combining it to simplify it.
13420 Builder->SetInsertPoint(I->getParent(), I);
13421
Reid Spencera9b81012007-03-26 17:44:01 +000013422#ifndef NDEBUG
13423 std::string OrigI;
13424#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013425 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013426 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13427
Chris Lattner90ac28c2002-08-02 19:29:35 +000013428 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013429 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013430 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013431 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013432 DEBUG(errs() << "IC: Old = " << *I << '\n'
13433 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013434
Chris Lattnerf523d062004-06-09 05:08:07 +000013435 // Everything uses the new instruction now.
13436 I->replaceAllUsesWith(Result);
13437
13438 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013439 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013440 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013441
Chris Lattner6934a042007-02-11 01:23:03 +000013442 // Move the name to the new instruction first.
13443 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013444
13445 // Insert the new instruction into the basic block...
13446 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013447 BasicBlock::iterator InsertPos = I;
13448
13449 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13450 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13451 ++InsertPos;
13452
13453 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013454
Chris Lattner7a1e9242009-08-30 06:13:40 +000013455 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013456 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013457#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013458 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13459 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013460#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013461
Chris Lattner90ac28c2002-08-02 19:29:35 +000013462 // If the instruction was modified, it's possible that it is now dead.
13463 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013464 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013465 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013466 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013467 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013468 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013469 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013470 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013471 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013472 }
13473 }
13474
Chris Lattner873ff012009-08-30 05:55:36 +000013475 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013476 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013477}
13478
Chris Lattnerec9c3582007-03-03 02:04:50 +000013479
13480bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013481 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013482 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013483 TD = getAnalysisIfAvailable<TargetData>();
13484
Chris Lattner74381062009-08-30 07:44:24 +000013485
13486 /// Builder - This is an IRBuilder that automatically inserts new
13487 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013488 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013489 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013490 InstCombineIRInserter(Worklist));
13491 Builder = &TheBuilder;
13492
Chris Lattnerec9c3582007-03-03 02:04:50 +000013493 bool EverMadeChange = false;
13494
13495 // Iterate while there is work to do.
13496 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013497 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013498 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013499
13500 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013501 return EverMadeChange;
13502}
13503
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013504FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013505 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013506}