blob: 4e24d755c26ee18fa61738241f87786b54cb42b0 [file] [log] [blame]
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Andersonab6ec2e2007-07-24 17:55:58 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions. It also performs simple dead load elimination.
12//
John Criswell073e4d12009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman5afc2742008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Andersonab6ec2e2007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
Chandler Carruth89c45a12016-03-11 08:50:55 +000018#include "llvm/Transforms/Scalar/GVN.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000019#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/DepthFirstIterator.h"
21#include "llvm/ADT/Hashing.h"
Benjamin Kramer3f085ba2014-05-13 21:06:40 +000022#include "llvm/ADT/MapVector.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000023#include "llvm/ADT/PointerIntPair.h"
Tim Northovereb161122015-01-09 19:19:56 +000024#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000025#include "llvm/ADT/STLExtras.h"
Shuxin Yang3168ab32013-11-11 22:00:23 +000026#include "llvm/ADT/SetVector.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000027#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000028#include "llvm/ADT/SmallVector.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000029#include "llvm/ADT/Statistic.h"
Owen Anderson09b83ba2007-10-18 19:39:33 +000030#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000031#include "llvm/Analysis/AssumptionCache.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000032#include "llvm/Analysis/CFG.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000033#include "llvm/Analysis/GlobalsModRef.h"
Duncan Sands246b71c2010-11-12 21:10:24 +000034#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000035#include "llvm/Analysis/LoopInfo.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000036#include "llvm/Analysis/MemoryBuiltins.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000037#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Adam Nemet0965da22017-10-09 23:19:02 +000038#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Chris Lattner972e6d82009-12-09 01:59:31 +000039#include "llvm/Analysis/PHITransAddr.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000040#include "llvm/Analysis/TargetLibraryInfo.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000041#include "llvm/IR/Attributes.h"
42#include "llvm/IR/BasicBlock.h"
43#include "llvm/IR/CallSite.h"
44#include "llvm/IR/Constant.h"
45#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/DataLayout.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000047#include "llvm/IR/DebugLoc.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000048#include "llvm/IR/Dominators.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000049#include "llvm/IR/Function.h"
50#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000057#include "llvm/IR/Module.h"
58#include "llvm/IR/Operator.h"
59#include "llvm/IR/PassManager.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000060#include "llvm/IR/PatternMatch.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000061#include "llvm/IR/Type.h"
62#include "llvm/IR/Use.h"
63#include "llvm/IR/Value.h"
64#include "llvm/Pass.h"
65#include "llvm/Support/Casting.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000066#include "llvm/Support/CommandLine.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000067#include "llvm/Support/Compiler.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000068#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000069#include "llvm/Support/raw_ostream.h"
Chris Lattnere28618d2010-11-30 22:25:26 +000070#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Rafael Espindolaea46c322014-08-15 15:46:38 +000071#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere28618d2010-11-30 22:25:26 +000072#include "llvm/Transforms/Utils/SSAUpdater.h"
Daniel Berlin5ac91792017-03-10 04:54:10 +000073#include "llvm/Transforms/Utils/VNCoercion.h"
Eugene Zelenko8002c502017-09-13 21:43:53 +000074#include <algorithm>
75#include <cassert>
76#include <cstdint>
77#include <utility>
Shuxin Yang1d8d7e42013-05-09 18:34:27 +000078#include <vector>
Eugene Zelenko8002c502017-09-13 21:43:53 +000079
Owen Andersonab6ec2e2007-07-24 17:55:58 +000080using namespace llvm;
Chandler Carruth89c45a12016-03-11 08:50:55 +000081using namespace llvm::gvn;
Daniel Berlin5ac91792017-03-10 04:54:10 +000082using namespace llvm::VNCoercion;
Duncan Sandsf4f47cc2011-10-05 14:28:49 +000083using namespace PatternMatch;
Owen Andersonab6ec2e2007-07-24 17:55:58 +000084
Chandler Carruth964daaa2014-04-22 02:55:47 +000085#define DEBUG_TYPE "gvn"
86
Bill Wendling3c793442008-12-22 22:14:07 +000087STATISTIC(NumGVNInstr, "Number of instructions deleted");
88STATISTIC(NumGVNLoad, "Number of loads deleted");
89STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson53d546e2008-07-15 16:28:06 +000090STATISTIC(NumGVNBlocks, "Number of blocks merged");
Duncan Sandsf4f47cc2011-10-05 14:28:49 +000091STATISTIC(NumGVNSimpl, "Number of instructions simplified");
92STATISTIC(NumGVNEqProp, "Number of equalities propagated");
Bill Wendling3c793442008-12-22 22:14:07 +000093STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattner168be762008-03-22 04:13:49 +000094
Evan Cheng9598f932008-06-20 01:01:07 +000095static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonaddbe3e2008-07-17 19:41:00 +000096 cl::init(true), cl::Hidden);
Dan Gohmana8f8a852009-06-15 18:30:15 +000097static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersone780d662008-06-19 19:57:25 +000098
Mon P Wang6120cfb2012-04-27 18:09:28 +000099// Maximum allowed recursion depth.
David Blaikie84e4b392012-04-27 19:30:32 +0000100static cl::opt<uint32_t>
Mon P Wang6120cfb2012-04-27 18:09:28 +0000101MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
102 cl::desc("Max recurse depth (default = 1000)"));
103
Chandler Carruthace8c8f2016-03-11 16:25:19 +0000104struct llvm::GVN::Expression {
Chandler Carruth77763772016-03-10 00:58:20 +0000105 uint32_t opcode;
106 Type *type;
Eugene Zelenko8002c502017-09-13 21:43:53 +0000107 bool commutative = false;
Chandler Carruth77763772016-03-10 00:58:20 +0000108 SmallVector<uint32_t, 4> varargs;
109
Eugene Zelenko8002c502017-09-13 21:43:53 +0000110 Expression(uint32_t o = ~2U) : opcode(o) {}
Chandler Carruth77763772016-03-10 00:58:20 +0000111
112 bool operator==(const Expression &other) const {
113 if (opcode != other.opcode)
114 return false;
115 if (opcode == ~0U || opcode == ~1U)
116 return true;
117 if (type != other.type)
118 return false;
119 if (varargs != other.varargs)
120 return false;
121 return true;
122 }
123
124 friend hash_code hash_value(const Expression &Value) {
125 return hash_combine(
126 Value.opcode, Value.type,
127 hash_combine_range(Value.varargs.begin(), Value.varargs.end()));
128 }
129};
130
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000131namespace llvm {
Eugene Zelenko8002c502017-09-13 21:43:53 +0000132
Chandler Carruthace8c8f2016-03-11 16:25:19 +0000133template <> struct DenseMapInfo<GVN::Expression> {
134 static inline GVN::Expression getEmptyKey() { return ~0U; }
Chandler Carruthace8c8f2016-03-11 16:25:19 +0000135 static inline GVN::Expression getTombstoneKey() { return ~1U; }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000136
Benjamin Kramer1afc1de2016-06-17 20:41:14 +0000137 static unsigned getHashValue(const GVN::Expression &e) {
Chandler Carruthe134d1a2012-03-05 11:29:54 +0000138 using llvm::hash_value;
Eugene Zelenko8002c502017-09-13 21:43:53 +0000139
Chandler Carruthe134d1a2012-03-05 11:29:54 +0000140 return static_cast<unsigned>(hash_value(e));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000141 }
Eugene Zelenko8002c502017-09-13 21:43:53 +0000142
Chandler Carruthace8c8f2016-03-11 16:25:19 +0000143 static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS) {
Chris Lattner0625bd62007-09-17 18:34:04 +0000144 return LHS == RHS;
145 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000146};
Eugene Zelenko8002c502017-09-13 21:43:53 +0000147
148} // end namespace llvm
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000149
Chandler Carruth89c45a12016-03-11 08:50:55 +0000150/// Represents a particular available value that we know how to materialize.
151/// Materialization of an AvailableValue never fails. An AvailableValue is
152/// implicitly associated with a rematerialization point which is the
153/// location of the instruction from which it was formed.
154struct llvm::gvn::AvailableValue {
155 enum ValType {
Davide Italianod15477b2016-10-21 01:37:02 +0000156 SimpleVal, // A simple offsetted value that is accessed.
157 LoadVal, // A value produced by a load.
158 MemIntrin, // A memory intrinsic which is loaded from.
159 UndefVal // A UndefValue representing a value from dead block (which
160 // is not yet physically removed from the CFG).
Chandler Carruth89c45a12016-03-11 08:50:55 +0000161 };
162
163 /// V - The value that is live out of the block.
Davide Italianod15477b2016-10-21 01:37:02 +0000164 PointerIntPair<Value *, 2, ValType> Val;
Chandler Carruth89c45a12016-03-11 08:50:55 +0000165
166 /// Offset - The byte offset in Val that is interesting for the load query.
167 unsigned Offset;
168
169 static AvailableValue get(Value *V, unsigned Offset = 0) {
170 AvailableValue Res;
Davide Italianod15477b2016-10-21 01:37:02 +0000171 Res.Val.setPointer(V);
172 Res.Val.setInt(SimpleVal);
Chandler Carruth89c45a12016-03-11 08:50:55 +0000173 Res.Offset = Offset;
174 return Res;
175 }
176
177 static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
178 AvailableValue Res;
Davide Italianod15477b2016-10-21 01:37:02 +0000179 Res.Val.setPointer(MI);
180 Res.Val.setInt(MemIntrin);
Chandler Carruth89c45a12016-03-11 08:50:55 +0000181 Res.Offset = Offset;
182 return Res;
183 }
184
185 static AvailableValue getLoad(LoadInst *LI, unsigned Offset = 0) {
186 AvailableValue Res;
Davide Italianod15477b2016-10-21 01:37:02 +0000187 Res.Val.setPointer(LI);
188 Res.Val.setInt(LoadVal);
Chandler Carruth89c45a12016-03-11 08:50:55 +0000189 Res.Offset = Offset;
190 return Res;
191 }
192
193 static AvailableValue getUndef() {
194 AvailableValue Res;
Davide Italianod15477b2016-10-21 01:37:02 +0000195 Res.Val.setPointer(nullptr);
196 Res.Val.setInt(UndefVal);
Chandler Carruth89c45a12016-03-11 08:50:55 +0000197 Res.Offset = 0;
198 return Res;
199 }
200
Davide Italianod15477b2016-10-21 01:37:02 +0000201 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
202 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
203 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
204 bool isUndefValue() const { return Val.getInt() == UndefVal; }
Chandler Carruth89c45a12016-03-11 08:50:55 +0000205
206 Value *getSimpleValue() const {
207 assert(isSimpleValue() && "Wrong accessor");
Davide Italianod15477b2016-10-21 01:37:02 +0000208 return Val.getPointer();
Chandler Carruth89c45a12016-03-11 08:50:55 +0000209 }
210
211 LoadInst *getCoercedLoadValue() const {
212 assert(isCoercedLoadValue() && "Wrong accessor");
Davide Italianod15477b2016-10-21 01:37:02 +0000213 return cast<LoadInst>(Val.getPointer());
Chandler Carruth89c45a12016-03-11 08:50:55 +0000214 }
215
216 MemIntrinsic *getMemIntrinValue() const {
217 assert(isMemIntrinValue() && "Wrong accessor");
Davide Italianod15477b2016-10-21 01:37:02 +0000218 return cast<MemIntrinsic>(Val.getPointer());
Chandler Carruth89c45a12016-03-11 08:50:55 +0000219 }
220
221 /// Emit code at the specified insertion point to adjust the value defined
222 /// here to the specified type. This handles various coercion cases.
223 Value *MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt,
224 GVN &gvn) const;
225};
226
227/// Represents an AvailableValue which can be rematerialized at the end of
228/// the associated BasicBlock.
229struct llvm::gvn::AvailableValueInBlock {
230 /// BB - The basic block in question.
231 BasicBlock *BB;
232
233 /// AV - The actual available value
234 AvailableValue AV;
235
236 static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) {
237 AvailableValueInBlock Res;
238 Res.BB = BB;
239 Res.AV = std::move(AV);
240 return Res;
241 }
242
243 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
244 unsigned Offset = 0) {
245 return get(BB, AvailableValue::get(V, Offset));
246 }
Eugene Zelenko8002c502017-09-13 21:43:53 +0000247
Chandler Carruth89c45a12016-03-11 08:50:55 +0000248 static AvailableValueInBlock getUndef(BasicBlock *BB) {
249 return get(BB, AvailableValue::getUndef());
250 }
251
252 /// Emit code at the end of this block to adjust the value defined here to
253 /// the specified type. This handles various coercion cases.
254 Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const {
255 return AV.MaterializeAdjustedValue(LI, BB->getTerminator(), gvn);
256 }
257};
258
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000259//===----------------------------------------------------------------------===//
260// ValueTable Internal Functions
261//===----------------------------------------------------------------------===//
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000262
Chad Rosier712b7d72016-04-28 16:00:15 +0000263GVN::Expression GVN::ValueTable::createExpr(Instruction *I) {
Owen Anderson3a33d0c2011-01-03 19:00:11 +0000264 Expression e;
265 e.type = I->getType();
266 e.opcode = I->getOpcode();
267 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
268 OI != OE; ++OI)
Chad Rosier712b7d72016-04-28 16:00:15 +0000269 e.varargs.push_back(lookupOrAdd(*OI));
Duncan Sands926d1012012-02-24 15:16:31 +0000270 if (I->isCommutative()) {
271 // Ensure that commutative instructions that only differ by a permutation
272 // of their operands get the same value number by sorting the operand value
273 // numbers. Since all commutative instructions have two operands it is more
274 // efficient to sort by hand rather than using, say, std::sort.
275 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
276 if (e.varargs[0] > e.varargs[1])
277 std::swap(e.varargs[0], e.varargs[1]);
Wei Mi55c05e12017-07-28 15:47:25 +0000278 e.commutative = true;
Duncan Sands926d1012012-02-24 15:16:31 +0000279 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000280
Lang Hames29cd98f2011-07-08 01:50:54 +0000281 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
Duncan Sands926d1012012-02-24 15:16:31 +0000282 // Sort the operand value numbers so x<y and y>x get the same value number.
283 CmpInst::Predicate Predicate = C->getPredicate();
284 if (e.varargs[0] > e.varargs[1]) {
285 std::swap(e.varargs[0], e.varargs[1]);
286 Predicate = CmpInst::getSwappedPredicate(Predicate);
287 }
288 e.opcode = (C->getOpcode() << 8) | Predicate;
Wei Mi55c05e12017-07-28 15:47:25 +0000289 e.commutative = true;
Owen Anderson3a33d0c2011-01-03 19:00:11 +0000290 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
291 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
292 II != IE; ++II)
293 e.varargs.push_back(*II);
Erik Verbruggene2d43712014-03-11 09:36:48 +0000294 }
295
296 return e;
297}
298
Chad Rosier712b7d72016-04-28 16:00:15 +0000299GVN::Expression GVN::ValueTable::createCmpExpr(unsigned Opcode,
300 CmpInst::Predicate Predicate,
301 Value *LHS, Value *RHS) {
Duncan Sands27f45952012-02-27 08:14:30 +0000302 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
303 "Not a comparison!");
304 Expression e;
305 e.type = CmpInst::makeCmpResultType(LHS->getType());
Chad Rosier712b7d72016-04-28 16:00:15 +0000306 e.varargs.push_back(lookupOrAdd(LHS));
307 e.varargs.push_back(lookupOrAdd(RHS));
Duncan Sands27f45952012-02-27 08:14:30 +0000308
309 // Sort the operand value numbers so x<y and y>x get the same value number.
310 if (e.varargs[0] > e.varargs[1]) {
311 std::swap(e.varargs[0], e.varargs[1]);
312 Predicate = CmpInst::getSwappedPredicate(Predicate);
313 }
314 e.opcode = (Opcode << 8) | Predicate;
Wei Mi55c05e12017-07-28 15:47:25 +0000315 e.commutative = true;
Duncan Sands27f45952012-02-27 08:14:30 +0000316 return e;
317}
318
Chad Rosier712b7d72016-04-28 16:00:15 +0000319GVN::Expression GVN::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) {
Craig Toppere73658d2014-04-28 04:05:08 +0000320 assert(EI && "Not an ExtractValueInst?");
Erik Verbruggen2074ebd2014-03-28 14:42:34 +0000321 Expression e;
322 e.type = EI->getType();
323 e.opcode = 0;
324
325 IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
Craig Topperf40110f2014-04-25 05:29:35 +0000326 if (I != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
Erik Verbruggen2074ebd2014-03-28 14:42:34 +0000327 // EI might be an extract from one of our recognised intrinsics. If it
328 // is we'll synthesize a semantically equivalent expression instead on
329 // an extract value expression.
330 switch (I->getIntrinsicID()) {
331 case Intrinsic::sadd_with_overflow:
332 case Intrinsic::uadd_with_overflow:
333 e.opcode = Instruction::Add;
334 break;
335 case Intrinsic::ssub_with_overflow:
336 case Intrinsic::usub_with_overflow:
337 e.opcode = Instruction::Sub;
338 break;
339 case Intrinsic::smul_with_overflow:
340 case Intrinsic::umul_with_overflow:
341 e.opcode = Instruction::Mul;
342 break;
343 default:
344 break;
345 }
346
347 if (e.opcode != 0) {
348 // Intrinsic recognized. Grab its args to finish building the expression.
349 assert(I->getNumArgOperands() == 2 &&
350 "Expect two args for recognised intrinsics.");
Chad Rosier712b7d72016-04-28 16:00:15 +0000351 e.varargs.push_back(lookupOrAdd(I->getArgOperand(0)));
352 e.varargs.push_back(lookupOrAdd(I->getArgOperand(1)));
Erik Verbruggen2074ebd2014-03-28 14:42:34 +0000353 return e;
354 }
355 }
356
357 // Not a recognised intrinsic. Fall back to producing an extract value
358 // expression.
359 e.opcode = EI->getOpcode();
360 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
361 OI != OE; ++OI)
Chad Rosier712b7d72016-04-28 16:00:15 +0000362 e.varargs.push_back(lookupOrAdd(*OI));
Erik Verbruggen2074ebd2014-03-28 14:42:34 +0000363
364 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
365 II != IE; ++II)
366 e.varargs.push_back(*II);
367
368 return e;
369}
370
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000371//===----------------------------------------------------------------------===//
372// ValueTable External Functions
373//===----------------------------------------------------------------------===//
374
Eugene Zelenko8002c502017-09-13 21:43:53 +0000375GVN::ValueTable::ValueTable() = default;
Benjamin Kramer26b25932016-10-20 13:09:12 +0000376GVN::ValueTable::ValueTable(const ValueTable &) = default;
377GVN::ValueTable::ValueTable(ValueTable &&) = default;
378GVN::ValueTable::~ValueTable() = default;
Chandler Carruth89c45a12016-03-11 08:50:55 +0000379
Owen Anderson6a903bc2008-06-18 21:41:49 +0000380/// add - Insert a value into the table with a specified value number.
Chandler Carruth89c45a12016-03-11 08:50:55 +0000381void GVN::ValueTable::add(Value *V, uint32_t num) {
Owen Anderson6a903bc2008-06-18 21:41:49 +0000382 valueNumbering.insert(std::make_pair(V, num));
Wei Mi55c05e12017-07-28 15:47:25 +0000383 if (PHINode *PN = dyn_cast<PHINode>(V))
384 NumberingPhi[num] = PN;
Owen Anderson6a903bc2008-06-18 21:41:49 +0000385}
386
Chad Rosier712b7d72016-04-28 16:00:15 +0000387uint32_t GVN::ValueTable::lookupOrAddCall(CallInst *C) {
Owen Anderson168ad692009-10-19 22:14:22 +0000388 if (AA->doesNotAccessMemory(C)) {
Chad Rosier712b7d72016-04-28 16:00:15 +0000389 Expression exp = createExpr(C);
Wei Mi55c05e12017-07-28 15:47:25 +0000390 uint32_t e = assignExpNewValueNum(exp).first;
Owen Anderson168ad692009-10-19 22:14:22 +0000391 valueNumbering[C] = e;
392 return e;
393 } else if (AA->onlyReadsMemory(C)) {
Chad Rosier712b7d72016-04-28 16:00:15 +0000394 Expression exp = createExpr(C);
Wei Mi55c05e12017-07-28 15:47:25 +0000395 auto ValNum = assignExpNewValueNum(exp);
396 if (ValNum.second) {
397 valueNumbering[C] = ValNum.first;
398 return ValNum.first;
Owen Anderson168ad692009-10-19 22:14:22 +0000399 }
Dan Gohman81132462009-11-14 02:27:51 +0000400 if (!MD) {
Wei Mi55c05e12017-07-28 15:47:25 +0000401 uint32_t e = assignExpNewValueNum(exp).first;
Dan Gohman81132462009-11-14 02:27:51 +0000402 valueNumbering[C] = e;
403 return e;
404 }
Owen Anderson168ad692009-10-19 22:14:22 +0000405
406 MemDepResult local_dep = MD->getDependency(C);
407
408 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
409 valueNumbering[C] = nextValueNumber;
410 return nextValueNumber++;
411 }
412
413 if (local_dep.isDef()) {
414 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
415
Gabor Greiff628ecd2010-06-30 09:17:53 +0000416 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Anderson168ad692009-10-19 22:14:22 +0000417 valueNumbering[C] = nextValueNumber;
418 return nextValueNumber++;
419 }
420
Gabor Greif2d958d42010-06-24 10:17:17 +0000421 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
Chad Rosier712b7d72016-04-28 16:00:15 +0000422 uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
423 uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i));
Owen Anderson168ad692009-10-19 22:14:22 +0000424 if (c_vn != cd_vn) {
425 valueNumbering[C] = nextValueNumber;
426 return nextValueNumber++;
427 }
428 }
429
Chad Rosier712b7d72016-04-28 16:00:15 +0000430 uint32_t v = lookupOrAdd(local_cdep);
Owen Anderson168ad692009-10-19 22:14:22 +0000431 valueNumbering[C] = v;
432 return v;
433 }
434
435 // Non-local case.
Chandler Carruth61440d22016-03-10 00:55:30 +0000436 const MemoryDependenceResults::NonLocalDepInfo &deps =
Owen Anderson168ad692009-10-19 22:14:22 +0000437 MD->getNonLocalCallDependency(CallSite(C));
Eli Friedman7d58bc72011-06-15 00:47:34 +0000438 // FIXME: Move the checking logic to MemDep!
Craig Topperf40110f2014-04-25 05:29:35 +0000439 CallInst* cdep = nullptr;
Owen Anderson168ad692009-10-19 22:14:22 +0000440
441 // Check to see if we have a single dominating call instruction that is
442 // identical to C.
443 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
Chris Lattner0c315472009-12-09 07:08:01 +0000444 const NonLocalDepEntry *I = &deps[i];
Chris Lattner0c315472009-12-09 07:08:01 +0000445 if (I->getResult().isNonLocal())
Owen Anderson168ad692009-10-19 22:14:22 +0000446 continue;
447
Eli Friedman7d58bc72011-06-15 00:47:34 +0000448 // We don't handle non-definitions. If we already have a call, reject
Owen Anderson168ad692009-10-19 22:14:22 +0000449 // instruction dependencies.
Craig Topperf40110f2014-04-25 05:29:35 +0000450 if (!I->getResult().isDef() || cdep != nullptr) {
451 cdep = nullptr;
Owen Anderson168ad692009-10-19 22:14:22 +0000452 break;
453 }
454
Chris Lattner0c315472009-12-09 07:08:01 +0000455 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
Owen Anderson168ad692009-10-19 22:14:22 +0000456 // FIXME: All duplicated with non-local case.
Chris Lattner0c315472009-12-09 07:08:01 +0000457 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
Owen Anderson168ad692009-10-19 22:14:22 +0000458 cdep = NonLocalDepCall;
459 continue;
460 }
461
Craig Topperf40110f2014-04-25 05:29:35 +0000462 cdep = nullptr;
Owen Anderson168ad692009-10-19 22:14:22 +0000463 break;
464 }
465
466 if (!cdep) {
467 valueNumbering[C] = nextValueNumber;
468 return nextValueNumber++;
469 }
470
Gabor Greiff628ecd2010-06-30 09:17:53 +0000471 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Anderson168ad692009-10-19 22:14:22 +0000472 valueNumbering[C] = nextValueNumber;
473 return nextValueNumber++;
474 }
Gabor Greif2d958d42010-06-24 10:17:17 +0000475 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
Chad Rosier712b7d72016-04-28 16:00:15 +0000476 uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
477 uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i));
Owen Anderson168ad692009-10-19 22:14:22 +0000478 if (c_vn != cd_vn) {
479 valueNumbering[C] = nextValueNumber;
480 return nextValueNumber++;
481 }
482 }
483
Chad Rosier712b7d72016-04-28 16:00:15 +0000484 uint32_t v = lookupOrAdd(cdep);
Owen Anderson168ad692009-10-19 22:14:22 +0000485 valueNumbering[C] = v;
486 return v;
Owen Anderson168ad692009-10-19 22:14:22 +0000487 } else {
488 valueNumbering[C] = nextValueNumber;
489 return nextValueNumber++;
490 }
491}
492
Weiming Zhaob69babd2015-11-19 02:45:18 +0000493/// Returns true if a value number exists for the specified value.
Chandler Carruth89c45a12016-03-11 08:50:55 +0000494bool GVN::ValueTable::exists(Value *V) const { return valueNumbering.count(V) != 0; }
Weiming Zhaob69babd2015-11-19 02:45:18 +0000495
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000496/// lookup_or_add - Returns the value number for the specified value, assigning
497/// it a new number if it did not have one before.
Chad Rosier712b7d72016-04-28 16:00:15 +0000498uint32_t GVN::ValueTable::lookupOrAdd(Value *V) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000499 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
500 if (VI != valueNumbering.end())
501 return VI->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000502
Owen Anderson168ad692009-10-19 22:14:22 +0000503 if (!isa<Instruction>(V)) {
Owen Anderson1059b5b2009-10-19 21:14:57 +0000504 valueNumbering[V] = nextValueNumber;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000505 return nextValueNumber++;
506 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000507
Owen Anderson168ad692009-10-19 22:14:22 +0000508 Instruction* I = cast<Instruction>(V);
509 Expression exp;
510 switch (I->getOpcode()) {
Erik Verbruggen2074ebd2014-03-28 14:42:34 +0000511 case Instruction::Call:
Chad Rosier712b7d72016-04-28 16:00:15 +0000512 return lookupOrAddCall(cast<CallInst>(I));
Owen Anderson168ad692009-10-19 22:14:22 +0000513 case Instruction::Add:
514 case Instruction::FAdd:
515 case Instruction::Sub:
516 case Instruction::FSub:
517 case Instruction::Mul:
518 case Instruction::FMul:
519 case Instruction::UDiv:
520 case Instruction::SDiv:
521 case Instruction::FDiv:
522 case Instruction::URem:
523 case Instruction::SRem:
524 case Instruction::FRem:
525 case Instruction::Shl:
526 case Instruction::LShr:
527 case Instruction::AShr:
528 case Instruction::And:
Nick Lewycky12d825d2012-09-09 23:41:11 +0000529 case Instruction::Or:
Owen Anderson168ad692009-10-19 22:14:22 +0000530 case Instruction::Xor:
Owen Anderson168ad692009-10-19 22:14:22 +0000531 case Instruction::ICmp:
532 case Instruction::FCmp:
Owen Anderson168ad692009-10-19 22:14:22 +0000533 case Instruction::Trunc:
534 case Instruction::ZExt:
535 case Instruction::SExt:
536 case Instruction::FPToUI:
537 case Instruction::FPToSI:
538 case Instruction::UIToFP:
539 case Instruction::SIToFP:
540 case Instruction::FPTrunc:
541 case Instruction::FPExt:
542 case Instruction::PtrToInt:
543 case Instruction::IntToPtr:
544 case Instruction::BitCast:
Owen Anderson168ad692009-10-19 22:14:22 +0000545 case Instruction::Select:
Owen Anderson168ad692009-10-19 22:14:22 +0000546 case Instruction::ExtractElement:
Owen Anderson168ad692009-10-19 22:14:22 +0000547 case Instruction::InsertElement:
Owen Anderson168ad692009-10-19 22:14:22 +0000548 case Instruction::ShuffleVector:
Owen Anderson168ad692009-10-19 22:14:22 +0000549 case Instruction::InsertValue:
Owen Anderson168ad692009-10-19 22:14:22 +0000550 case Instruction::GetElementPtr:
Chad Rosier712b7d72016-04-28 16:00:15 +0000551 exp = createExpr(I);
Lang Hames29cd98f2011-07-08 01:50:54 +0000552 break;
Erik Verbruggen2074ebd2014-03-28 14:42:34 +0000553 case Instruction::ExtractValue:
Chad Rosier712b7d72016-04-28 16:00:15 +0000554 exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
Erik Verbruggen2074ebd2014-03-28 14:42:34 +0000555 break;
Wei Mi55c05e12017-07-28 15:47:25 +0000556 case Instruction::PHI:
557 valueNumbering[V] = nextValueNumber;
558 NumberingPhi[nextValueNumber] = cast<PHINode>(V);
559 return nextValueNumber++;
Owen Anderson168ad692009-10-19 22:14:22 +0000560 default:
561 valueNumbering[V] = nextValueNumber;
562 return nextValueNumber++;
563 }
564
Wei Mi55c05e12017-07-28 15:47:25 +0000565 uint32_t e = assignExpNewValueNum(exp).first;
Owen Anderson168ad692009-10-19 22:14:22 +0000566 valueNumbering[V] = e;
567 return e;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000568}
569
Sanjay Patelcee38612015-02-24 22:43:06 +0000570/// Returns the value number of the specified value. Fails if
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000571/// the value has not yet been numbered.
Wei Mi55c05e12017-07-28 15:47:25 +0000572uint32_t GVN::ValueTable::lookup(Value *V, bool Verify) const {
Jeffrey Yasskinb40d3f72009-11-10 01:02:17 +0000573 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
Wei Mi55c05e12017-07-28 15:47:25 +0000574 if (Verify) {
575 assert(VI != valueNumbering.end() && "Value not numbered?");
576 return VI->second;
577 }
578 return (VI != valueNumbering.end()) ? VI->second : 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000579}
580
Sanjay Patelcee38612015-02-24 22:43:06 +0000581/// Returns the value number of the given comparison,
Duncan Sands27f45952012-02-27 08:14:30 +0000582/// assigning it a new number if it did not have one before. Useful when
583/// we deduced the result of a comparison, but don't immediately have an
584/// instruction realizing that comparison to hand.
Chad Rosier712b7d72016-04-28 16:00:15 +0000585uint32_t GVN::ValueTable::lookupOrAddCmp(unsigned Opcode,
586 CmpInst::Predicate Predicate,
587 Value *LHS, Value *RHS) {
588 Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
Wei Mi55c05e12017-07-28 15:47:25 +0000589 return assignExpNewValueNum(exp).first;
Duncan Sands27f45952012-02-27 08:14:30 +0000590}
591
Sanjay Patelcee38612015-02-24 22:43:06 +0000592/// Remove all entries from the ValueTable.
Chandler Carruth89c45a12016-03-11 08:50:55 +0000593void GVN::ValueTable::clear() {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000594 valueNumbering.clear();
595 expressionNumbering.clear();
Wei Mi55c05e12017-07-28 15:47:25 +0000596 NumberingPhi.clear();
597 PhiTranslateTable.clear();
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000598 nextValueNumber = 1;
Wei Mi55c05e12017-07-28 15:47:25 +0000599 Expressions.clear();
600 ExprIdx.clear();
601 nextExprNumber = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000602}
603
Sanjay Patelcee38612015-02-24 22:43:06 +0000604/// Remove a value from the value numbering.
Chandler Carruth89c45a12016-03-11 08:50:55 +0000605void GVN::ValueTable::erase(Value *V) {
Wei Mi55c05e12017-07-28 15:47:25 +0000606 uint32_t Num = valueNumbering.lookup(V);
Owen Anderson10ffa862007-07-31 23:27:13 +0000607 valueNumbering.erase(V);
Wei Mi55c05e12017-07-28 15:47:25 +0000608 // If V is PHINode, V <--> value number is an one-to-one mapping.
609 if (isa<PHINode>(V))
610 NumberingPhi.erase(Num);
Owen Anderson10ffa862007-07-31 23:27:13 +0000611}
612
Bill Wendling6b18a392008-12-22 21:36:08 +0000613/// verifyRemoved - Verify that the value is removed from all internal data
614/// structures.
Chandler Carruth89c45a12016-03-11 08:50:55 +0000615void GVN::ValueTable::verifyRemoved(const Value *V) const {
Jeffrey Yasskinb40d3f72009-11-10 01:02:17 +0000616 for (DenseMap<Value*, uint32_t>::const_iterator
Bill Wendling6b18a392008-12-22 21:36:08 +0000617 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
618 assert(I->first != V && "Inst still occurs in value numbering map!");
619 }
620}
621
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000622//===----------------------------------------------------------------------===//
Bill Wendling456e8852008-12-22 22:32:22 +0000623// GVN Pass
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000624//===----------------------------------------------------------------------===//
625
Sean Silva36e0d012016-08-09 00:28:15 +0000626PreservedAnalyses GVN::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruth3bc9c7f2016-03-11 13:26:47 +0000627 // FIXME: The order of evaluation of these 'getResult' calls is very
628 // significant! Re-ordering these variables will cause GVN when run alone to
629 // be less effective! We should fix memdep and basic-aa to not exhibit this
630 // behavior, but until then don't change the order here.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000631 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Chandler Carruth3bc9c7f2016-03-11 13:26:47 +0000632 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
633 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
634 auto &AA = AM.getResult<AAManager>(F);
635 auto &MemDep = AM.getResult<MemoryDependenceAnalysis>(F);
Adam Nemetfeafcd92016-12-01 03:56:43 +0000636 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
Adam Nemet4d2a6e52016-12-01 16:40:32 +0000637 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000638 bool Changed = runImpl(F, AC, DT, TLI, AA, &MemDep, LI, &ORE);
Davide Italianofea0a4c2016-06-06 20:01:50 +0000639 if (!Changed)
640 return PreservedAnalyses::all();
641 PreservedAnalyses PA;
642 PA.preserve<DominatorTreeAnalysis>();
643 PA.preserve<GlobalsAA>();
Davide Italiano116464a2017-01-31 21:53:18 +0000644 PA.preserve<TargetLibraryAnalysis>();
Davide Italianofea0a4c2016-06-06 20:01:50 +0000645 return PA;
Dan Gohman81132462009-11-14 02:27:51 +0000646}
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000647
Matthias Braun8c209aa2017-01-28 02:02:38 +0000648#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sam Clegg705f7982017-06-21 22:19:17 +0000649LLVM_DUMP_METHOD void GVN::dump(DenseMap<uint32_t, Value*>& d) const {
Dan Gohman57e80862009-12-18 03:25:51 +0000650 errs() << "{\n";
Owen Anderson6a903bc2008-06-18 21:41:49 +0000651 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson5e5599b2007-07-25 19:57:03 +0000652 E = d.end(); I != E; ++I) {
Dan Gohman57e80862009-12-18 03:25:51 +0000653 errs() << I->first << "\n";
Owen Anderson5e5599b2007-07-25 19:57:03 +0000654 I->second->dump();
655 }
Dan Gohman57e80862009-12-18 03:25:51 +0000656 errs() << "}\n";
Owen Anderson5e5599b2007-07-25 19:57:03 +0000657}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000658#endif
Owen Anderson5e5599b2007-07-25 19:57:03 +0000659
Sanjay Patelcee38612015-02-24 22:43:06 +0000660/// Return true if we can prove that the value
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000661/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000662/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
663/// map is actually a tri-state map with the following values:
664/// 0) we know the block *is not* fully available.
665/// 1) we know the block *is* fully available.
666/// 2) we do not know whether the block is fully available or not, but we are
667/// currently speculating that it will be.
668/// 3) we are speculating for this block and have used that to speculate for
669/// other blocks.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000670static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Mon P Wang6120cfb2012-04-27 18:09:28 +0000671 DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
672 uint32_t RecurseDepth) {
673 if (RecurseDepth > MaxRecurseDepth)
674 return false;
675
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000676 // Optimistically assume that the block is fully available and check to see
677 // if we already know about this block in one lookup.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000678 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000679 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000680
681 // If the entry already existed for this block, return the precomputed value.
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000682 if (!IV.second) {
683 // If this is a speculative "available" value, mark it as being used for
684 // speculation of other blocks.
685 if (IV.first->second == 2)
686 IV.first->second = 3;
687 return IV.first->second != 0;
688 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000689
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000690 // Otherwise, see if it is fully available in all predecessors.
691 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000692
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000693 // If this block has no predecessors, it isn't live-in here.
694 if (PI == PE)
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000695 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000696
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000697 for (; PI != PE; ++PI)
698 // If the value isn't fully available in one of our predecessors, then it
699 // isn't fully available in this block either. Undo our previous
700 // optimistic assumption and bail out.
Mon P Wang6120cfb2012-04-27 18:09:28 +0000701 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000702 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000703
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000704 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000705
Sanjay Patelcee38612015-02-24 22:43:06 +0000706// If we get here, we found out that this is not, after
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000707// all, a fully-available block. We have a problem if we speculated on this and
708// used the speculation to mark other blocks as available.
709SpeculationFailure:
710 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000711
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000712 // If we didn't speculate on this, just return with it set to false.
713 if (BBVal == 2) {
714 BBVal = 0;
715 return false;
716 }
717
718 // If we did speculate on this value, we could have blocks set to 1 that are
719 // incorrect. Walk the (transitive) successors of this block and mark them as
720 // 0 if set to one.
721 SmallVector<BasicBlock*, 32> BBWorklist;
722 BBWorklist.push_back(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000723
Dan Gohman28943872010-01-05 16:27:25 +0000724 do {
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000725 BasicBlock *Entry = BBWorklist.pop_back_val();
726 // Note that this sets blocks to 0 (unavailable) if they happen to not
727 // already be in FullyAvailableBlocks. This is safe.
728 char &EntryVal = FullyAvailableBlocks[Entry];
729 if (EntryVal == 0) continue; // Already unavailable.
730
731 // Mark as unavailable.
732 EntryVal = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000733
Benjamin Kramer3c29c072014-02-10 14:17:42 +0000734 BBWorklist.append(succ_begin(Entry), succ_end(Entry));
Dan Gohman28943872010-01-05 16:27:25 +0000735 } while (!BBWorklist.empty());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000736
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000737 return false;
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000738}
739
Sanjay Patelcee38612015-02-24 22:43:06 +0000740/// Given a set of loads specified by ValuesPerBlock,
Chris Lattnerb6c65fa2009-10-10 23:50:30 +0000741/// construct SSA form, allowing us to eliminate LI. This returns the value
742/// that should be used at LI's definition site.
Nadav Rotem465834c2012-07-24 10:51:42 +0000743static Value *ConstructSSAForLoadSet(LoadInst *LI,
Chris Lattnerb6c65fa2009-10-10 23:50:30 +0000744 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
Chris Lattnerf81f7892011-04-28 16:36:48 +0000745 GVN &gvn) {
Chris Lattnerbf200182009-12-21 23:15:48 +0000746 // Check for the fully redundant, dominating load case. In this case, we can
747 // just use the dominating value directly.
Nadav Rotem465834c2012-07-24 10:51:42 +0000748 if (ValuesPerBlock.size() == 1 &&
Chris Lattnerf81f7892011-04-28 16:36:48 +0000749 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
Shuxin Yang3168ab32013-11-11 22:00:23 +0000750 LI->getParent())) {
Philip Reames8e785a42016-01-26 23:43:16 +0000751 assert(!ValuesPerBlock[0].AV.isUndefValue() &&
752 "Dead BB dominate this block");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000753 return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
Shuxin Yang3168ab32013-11-11 22:00:23 +0000754 }
Chris Lattnerbf200182009-12-21 23:15:48 +0000755
756 // Otherwise, we have to construct SSA form.
Chris Lattnerb6c65fa2009-10-10 23:50:30 +0000757 SmallVector<PHINode*, 8> NewPHIs;
758 SSAUpdater SSAUpdate(&NewPHIs);
Duncan Sands67781492010-09-02 08:14:03 +0000759 SSAUpdate.Initialize(LI->getType(), LI->getName());
Nadav Rotem465834c2012-07-24 10:51:42 +0000760
Craig Toppere471cf32015-11-28 08:23:04 +0000761 for (const AvailableValueInBlock &AV : ValuesPerBlock) {
Chris Lattner93236ba2009-12-06 04:54:31 +0000762 BasicBlock *BB = AV.BB;
Nadav Rotem465834c2012-07-24 10:51:42 +0000763
Chris Lattnerb6c65fa2009-10-10 23:50:30 +0000764 if (SSAUpdate.HasValueForBlock(BB))
765 continue;
Chris Lattner93236ba2009-12-06 04:54:31 +0000766
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000767 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000768 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000769
Chris Lattnerb6c65fa2009-10-10 23:50:30 +0000770 // Perform PHI construction.
Chandler Carruth9f2bf1af2015-07-18 03:26:46 +0000771 return SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000772}
773
Philip Reames8e785a42016-01-26 23:43:16 +0000774Value *AvailableValue::MaterializeAdjustedValue(LoadInst *LI,
775 Instruction *InsertPt,
776 GVN &gvn) const {
Shuxin Yang637b9be2013-05-03 19:17:26 +0000777 Value *Res;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000778 Type *LoadTy = LI->getType();
779 const DataLayout &DL = LI->getModule()->getDataLayout();
Davide Italianod15477b2016-10-21 01:37:02 +0000780 if (isSimpleValue()) {
Shuxin Yang637b9be2013-05-03 19:17:26 +0000781 Res = getSimpleValue();
782 if (Res->getType() != LoadTy) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000783 Res = getStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000784
Shuxin Yang637b9be2013-05-03 19:17:26 +0000785 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
786 << *getSimpleValue() << '\n'
787 << *Res << '\n' << "\n\n\n");
788 }
789 } else if (isCoercedLoadValue()) {
790 LoadInst *Load = getCoercedLoadValue();
791 if (Load->getType() == LoadTy && Offset == 0) {
792 Res = Load;
793 } else {
Daniel Berlin12883b12017-03-20 16:08:29 +0000794 Res = getLoadValueForLoad(Load, Offset, LoadTy, InsertPt, DL);
Daniel Berlin5ac91792017-03-10 04:54:10 +0000795 // We would like to use gvn.markInstructionForDeletion here, but we can't
796 // because the load is already memoized into the leader map table that GVN
797 // tracks. It is potentially possible to remove the load from the table,
798 // but then there all of the operations based on it would need to be
799 // rehashed. Just leave the dead load around.
800 gvn.getMemDep().removeInstruction(Load);
Shuxin Yang637b9be2013-05-03 19:17:26 +0000801 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
802 << *getCoercedLoadValue() << '\n'
Daniel Berlin5ac91792017-03-10 04:54:10 +0000803 << *Res << '\n'
804 << "\n\n\n");
Shuxin Yang637b9be2013-05-03 19:17:26 +0000805 }
Shuxin Yang3168ab32013-11-11 22:00:23 +0000806 } else if (isMemIntrinValue()) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000807 Res = getMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
Philip Reames8e785a42016-01-26 23:43:16 +0000808 InsertPt, DL);
Shuxin Yang637b9be2013-05-03 19:17:26 +0000809 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
810 << " " << *getMemIntrinValue() << '\n'
811 << *Res << '\n' << "\n\n\n");
Shuxin Yang3168ab32013-11-11 22:00:23 +0000812 } else {
813 assert(isUndefValue() && "Should be UndefVal");
814 DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
815 return UndefValue::get(LoadTy);
Shuxin Yang637b9be2013-05-03 19:17:26 +0000816 }
Philip Reames8e785a42016-01-26 23:43:16 +0000817 assert(Res && "failed to materialize?");
Shuxin Yang637b9be2013-05-03 19:17:26 +0000818 return Res;
819}
820
Gabor Greifce6dd882010-04-09 10:57:00 +0000821static bool isLifetimeStart(const Instruction *Inst) {
822 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
Owen Andersonb9878ee2009-12-02 07:35:19 +0000823 return II->getIntrinsicID() == Intrinsic::lifetime_start;
Chris Lattnerc4680252009-12-02 06:44:58 +0000824 return false;
825}
826
Adam Nemet4ddb8c02016-12-01 17:34:50 +0000827/// \brief Try to locate the three instruction involved in a missed
828/// load-elimination case that is due to an intervening store.
829static void reportMayClobberedLoad(LoadInst *LI, MemDepResult DepInfo,
830 DominatorTree *DT,
831 OptimizationRemarkEmitter *ORE) {
832 using namespace ore;
Eugene Zelenko8002c502017-09-13 21:43:53 +0000833
Adam Nemet4ddb8c02016-12-01 17:34:50 +0000834 User *OtherAccess = nullptr;
835
836 OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", LI);
837 R << "load of type " << NV("Type", LI->getType()) << " not eliminated"
838 << setExtraArgs();
839
840 for (auto *U : LI->getPointerOperand()->users())
841 if (U != LI && (isa<LoadInst>(U) || isa<StoreInst>(U)) &&
842 DT->dominates(cast<Instruction>(U), LI)) {
843 // FIXME: for now give up if there are multiple memory accesses that
844 // dominate the load. We need further analysis to decide which one is
845 // that we're forwarding from.
846 if (OtherAccess)
847 OtherAccess = nullptr;
848 else
849 OtherAccess = U;
850 }
851
852 if (OtherAccess)
853 R << " in favor of " << NV("OtherAccess", OtherAccess);
854
855 R << " because it is clobbered by " << NV("ClobberedBy", DepInfo.getInst());
856
857 ORE->emit(R);
858}
859
Philip Reames96fccc22016-02-12 19:24:57 +0000860bool GVN::AnalyzeLoadAvailability(LoadInst *LI, MemDepResult DepInfo,
861 Value *Address, AvailableValue &Res) {
Philip Reames96fccc22016-02-12 19:24:57 +0000862 assert((DepInfo.isDef() || DepInfo.isClobber()) &&
863 "expected a local dependence");
Philip Reamesae8997f2016-05-06 18:17:13 +0000864 assert(LI->isUnordered() && "rules below are incorrect for ordered access");
Philip Reames96fccc22016-02-12 19:24:57 +0000865
866 const DataLayout &DL = LI->getModule()->getDataLayout();
Chad Rosier712b7d72016-04-28 16:00:15 +0000867
Philip Reames96fccc22016-02-12 19:24:57 +0000868 if (DepInfo.isClobber()) {
869 // If the dependence is to a store that writes to a superset of the bits
870 // read by the load, we can extract the bits we need for the load from the
871 // stored value.
872 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
Philip Reamesae8997f2016-05-06 18:17:13 +0000873 // Can't forward from non-atomic to atomic without violating memory model.
874 if (Address && LI->isAtomic() <= DepSI->isAtomic()) {
Philip Reames96fccc22016-02-12 19:24:57 +0000875 int Offset =
Daniel Berlincd07a0f2017-03-11 00:51:01 +0000876 analyzeLoadFromClobberingStore(LI->getType(), Address, DepSI, DL);
Philip Reames96fccc22016-02-12 19:24:57 +0000877 if (Offset != -1) {
878 Res = AvailableValue::get(DepSI->getValueOperand(), Offset);
879 return true;
880 }
881 }
882 }
883
884 // Check to see if we have something like this:
885 // load i32* P
886 // load i8* (P+1)
887 // if we have this, replace the later with an extraction from the former.
888 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
889 // If this is a clobber and L is the first instruction in its block, then
890 // we have the first instruction in the entry block.
Philip Reamesae8997f2016-05-06 18:17:13 +0000891 // Can't forward from non-atomic to atomic without violating memory model.
892 if (DepLI != LI && Address && LI->isAtomic() <= DepLI->isAtomic()) {
Philip Reames96fccc22016-02-12 19:24:57 +0000893 int Offset =
Daniel Berlin5ac91792017-03-10 04:54:10 +0000894 analyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
Chad Rosier712b7d72016-04-28 16:00:15 +0000895
Philip Reames96fccc22016-02-12 19:24:57 +0000896 if (Offset != -1) {
897 Res = AvailableValue::getLoad(DepLI, Offset);
898 return true;
899 }
900 }
901 }
902
903 // If the clobbering value is a memset/memcpy/memmove, see if we can
904 // forward a value on from it.
905 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
Philip Reamesae8997f2016-05-06 18:17:13 +0000906 if (Address && !LI->isAtomic()) {
Daniel Berlin5ac91792017-03-10 04:54:10 +0000907 int Offset = analyzeLoadFromClobberingMemInst(LI->getType(), Address,
Philip Reames96fccc22016-02-12 19:24:57 +0000908 DepMI, DL);
909 if (Offset != -1) {
910 Res = AvailableValue::getMI(DepMI, Offset);
911 return true;
912 }
913 }
914 }
915 // Nothing known about this clobber, have to be conservative
916 DEBUG(
917 // fast print dep, using operator<< on instruction is too slow.
918 dbgs() << "GVN: load ";
919 LI->printAsOperand(dbgs());
920 Instruction *I = DepInfo.getInst();
921 dbgs() << " is clobbered by " << *I << '\n';
922 );
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000923 if (ORE->allowExtraAnalysis(DEBUG_TYPE))
Adam Nemet4ddb8c02016-12-01 17:34:50 +0000924 reportMayClobberedLoad(LI, DepInfo, DT, ORE);
925
Philip Reames96fccc22016-02-12 19:24:57 +0000926 return false;
927 }
928 assert(DepInfo.isDef() && "follows from above");
929
930 Instruction *DepInst = DepInfo.getInst();
Chad Rosier712b7d72016-04-28 16:00:15 +0000931
Philip Reames96fccc22016-02-12 19:24:57 +0000932 // Loading the allocation -> undef.
933 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
934 // Loading immediately after lifetime begin -> undef.
935 isLifetimeStart(DepInst)) {
936 Res = AvailableValue::get(UndefValue::get(LI->getType()));
937 return true;
938 }
Chad Rosier712b7d72016-04-28 16:00:15 +0000939
Philip Reames96fccc22016-02-12 19:24:57 +0000940 // Loading from calloc (which zero initializes memory) -> zero
941 if (isCallocLikeFn(DepInst, TLI)) {
942 Res = AvailableValue::get(Constant::getNullValue(LI->getType()));
943 return true;
944 }
Chad Rosier712b7d72016-04-28 16:00:15 +0000945
Philip Reames96fccc22016-02-12 19:24:57 +0000946 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
947 // Reject loads and stores that are to the same address but are of
948 // different types if we have to. If the stored value is larger or equal to
949 // the loaded value, we can reuse it.
950 if (S->getValueOperand()->getType() != LI->getType() &&
Daniel Berlin5ac91792017-03-10 04:54:10 +0000951 !canCoerceMustAliasedValueToLoad(S->getValueOperand(),
Philip Reames96fccc22016-02-12 19:24:57 +0000952 LI->getType(), DL))
953 return false;
Chad Rosier712b7d72016-04-28 16:00:15 +0000954
Philip Reamesae8997f2016-05-06 18:17:13 +0000955 // Can't forward from non-atomic to atomic without violating memory model.
956 if (S->isAtomic() < LI->isAtomic())
957 return false;
958
Philip Reames96fccc22016-02-12 19:24:57 +0000959 Res = AvailableValue::get(S->getValueOperand());
960 return true;
961 }
Chad Rosier712b7d72016-04-28 16:00:15 +0000962
Philip Reames96fccc22016-02-12 19:24:57 +0000963 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
964 // If the types mismatch and we can't handle it, reject reuse of the load.
965 // If the stored value is larger or equal to the loaded value, we can reuse
Chad Rosier712b7d72016-04-28 16:00:15 +0000966 // it.
Philip Reames96fccc22016-02-12 19:24:57 +0000967 if (LD->getType() != LI->getType() &&
Daniel Berlin5ac91792017-03-10 04:54:10 +0000968 !canCoerceMustAliasedValueToLoad(LD, LI->getType(), DL))
Philip Reames96fccc22016-02-12 19:24:57 +0000969 return false;
970
Philip Reamesae8997f2016-05-06 18:17:13 +0000971 // Can't forward from non-atomic to atomic without violating memory model.
972 if (LD->isAtomic() < LI->isAtomic())
973 return false;
974
Philip Reames96fccc22016-02-12 19:24:57 +0000975 Res = AvailableValue::getLoad(LD);
976 return true;
977 }
978
979 // Unknown def - must be conservative
980 DEBUG(
981 // fast print dep, using operator<< on instruction is too slow.
982 dbgs() << "GVN: load ";
983 LI->printAsOperand(dbgs());
984 dbgs() << " has unknown def " << *DepInst << '\n';
985 );
986 return false;
987}
988
Chad Rosier712b7d72016-04-28 16:00:15 +0000989void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
Shuxin Yang637b9be2013-05-03 19:17:26 +0000990 AvailValInBlkVect &ValuesPerBlock,
991 UnavailBlkVect &UnavailableBlocks) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000992 // Filter out useless results (non-locals, etc). Keep track of the blocks
993 // where we have a value available in repl, also keep track of whether we see
994 // dependencies that produce an unknown value for the load (such as a call
995 // that could potentially clobber the load).
Shuxin Yang637b9be2013-05-03 19:17:26 +0000996 unsigned NumDeps = Deps.size();
Bill Wendling8a333122012-01-31 06:57:53 +0000997 for (unsigned i = 0, e = NumDeps; i != e; ++i) {
Chris Lattner0c315472009-12-09 07:08:01 +0000998 BasicBlock *DepBB = Deps[i].getBB();
999 MemDepResult DepInfo = Deps[i].getResult();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001000
Shuxin Yang3168ab32013-11-11 22:00:23 +00001001 if (DeadBlocks.count(DepBB)) {
1002 // Dead dependent mem-op disguise as a load evaluating the same value
1003 // as the load in question.
1004 ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
1005 continue;
1006 }
1007
Davide Italianod15477b2016-10-21 01:37:02 +00001008 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
Eli Friedman7d58bc72011-06-15 00:47:34 +00001009 UnavailableBlocks.push_back(DepBB);
1010 continue;
1011 }
1012
Philip Reames96fccc22016-02-12 19:24:57 +00001013 // The address being loaded in this non-local block may not be the same as
1014 // the pointer operand of the load if PHI translation occurs. Make sure
1015 // to consider the right address.
1016 Value *Address = Deps[i].getAddress();
Nadav Rotem465834c2012-07-24 10:51:42 +00001017
Philip Reames96fccc22016-02-12 19:24:57 +00001018 AvailableValue AV;
Davide Italianod15477b2016-10-21 01:37:02 +00001019 if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) {
Philip Reames96fccc22016-02-12 19:24:57 +00001020 // subtlety: because we know this was a non-local dependency, we know
1021 // it's safe to materialize anywhere between the instruction within
1022 // DepInfo and the end of it's block.
Davide Italianod15477b2016-10-21 01:37:02 +00001023 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1024 std::move(AV)));
Philip Reames96fccc22016-02-12 19:24:57 +00001025 } else {
Chris Lattner0e3d6332008-12-05 21:04:20 +00001026 UnavailableBlocks.push_back(DepBB);
Chris Lattner0e3d6332008-12-05 21:04:20 +00001027 }
Chris Lattner2876a642008-03-21 21:14:38 +00001028 }
Philip Reames96fccc22016-02-12 19:24:57 +00001029
1030 assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1031 "post condition violation");
Shuxin Yang637b9be2013-05-03 19:17:26 +00001032}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001033
Chad Rosier712b7d72016-04-28 16:00:15 +00001034bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
Shuxin Yang637b9be2013-05-03 19:17:26 +00001035 UnavailBlkVect &UnavailableBlocks) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001036 // Okay, we have *some* definitions of the value. This means that the value
1037 // is available in some of our (transitive) predecessors. Lets think about
1038 // doing PRE of this load. This will involve inserting a new load into the
1039 // predecessor when it's not available. We could do this in general, but
1040 // prefer to not increase code size. As such, we only do this when we know
1041 // that we only have to insert *one* load (which means we're basically moving
1042 // the load, not inserting a new one).
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001043
Craig Toppere471cf32015-11-28 08:23:04 +00001044 SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(),
1045 UnavailableBlocks.end());
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001046
Bill Wendling8bbcbed2011-08-17 21:32:02 +00001047 // Let's find the first basic block with more than one predecessor. Walk
1048 // backwards through predecessors if needed.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001049 BasicBlock *LoadBB = LI->getParent();
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001050 BasicBlock *TmpBB = LoadBB;
1051
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001052 while (TmpBB->getSinglePredecessor()) {
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001053 TmpBB = TmpBB->getSinglePredecessor();
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001054 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1055 return false;
1056 if (Blockers.count(TmpBB))
1057 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001058
Owen Andersonb590a922010-09-25 05:26:18 +00001059 // If any of these blocks has more than one successor (i.e. if the edge we
Nadav Rotem465834c2012-07-24 10:51:42 +00001060 // just traversed was critical), then there are other paths through this
1061 // block along which the load may not be anticipated. Hoisting the load
Owen Andersonb590a922010-09-25 05:26:18 +00001062 // above this block would be adding the load to execution paths along
1063 // which it was not previously executed.
Dale Johannesen81b64632009-06-17 20:48:23 +00001064 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
Owen Andersonb590a922010-09-25 05:26:18 +00001065 return false;
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001066 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001067
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001068 assert(TmpBB);
1069 LoadBB = TmpBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001070
Bob Wilsond517b522010-02-01 21:17:14 +00001071 // Check to see how many predecessors have the loaded value fully
1072 // available.
Benjamin Kramer3f085ba2014-05-13 21:06:40 +00001073 MapVector<BasicBlock *, Value *> PredLoads;
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001074 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Craig Toppere471cf32015-11-28 08:23:04 +00001075 for (const AvailableValueInBlock &AV : ValuesPerBlock)
1076 FullyAvailableBlocks[AV.BB] = true;
1077 for (BasicBlock *UnavailableBB : UnavailableBlocks)
1078 FullyAvailableBlocks[UnavailableBB] = false;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001079
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001080 SmallVector<BasicBlock *, 4> CriticalEdgePred;
Craig Toppere471cf32015-11-28 08:23:04 +00001081 for (BasicBlock *Pred : predecessors(LoadBB)) {
Andrew Kaylor0615a0e2015-11-23 19:51:41 +00001082 // If any predecessor block is an EH pad that does not allow non-PHI
1083 // instructions before the terminator, we can't PRE the load.
1084 if (Pred->getTerminator()->isEHPad()) {
1085 DEBUG(dbgs()
1086 << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
1087 << Pred->getName() << "': " << *LI << '\n');
1088 return false;
1089 }
1090
Mon P Wang6120cfb2012-04-27 18:09:28 +00001091 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001092 continue;
Bob Wilsond517b522010-02-01 21:17:14 +00001093 }
Bob Wilson92cdb6e2010-02-16 19:51:59 +00001094
Bob Wilsond517b522010-02-01 21:17:14 +00001095 if (Pred->getTerminator()->getNumSuccessors() != 1) {
Bob Wilson92cdb6e2010-02-16 19:51:59 +00001096 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1097 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1098 << Pred->getName() << "': " << *LI << '\n');
1099 return false;
1100 }
Bill Wendling8bbcbed2011-08-17 21:32:02 +00001101
David Majnemereb518bd2015-08-04 08:21:40 +00001102 if (LoadBB->isEHPad()) {
Bill Wendling8bbcbed2011-08-17 21:32:02 +00001103 DEBUG(dbgs()
David Majnemereb518bd2015-08-04 08:21:40 +00001104 << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
Bill Wendling8bbcbed2011-08-17 21:32:02 +00001105 << Pred->getName() << "': " << *LI << '\n');
1106 return false;
1107 }
1108
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001109 CriticalEdgePred.push_back(Pred);
Benjamin Kramer3f085ba2014-05-13 21:06:40 +00001110 } else {
1111 // Only add the predecessors that will not be split for now.
1112 PredLoads[Pred] = nullptr;
Bob Wilsond517b522010-02-01 21:17:14 +00001113 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001114 }
Bill Wendling8bbcbed2011-08-17 21:32:02 +00001115
Bob Wilsond517b522010-02-01 21:17:14 +00001116 // Decide whether PRE is profitable for this load.
Benjamin Kramer3f085ba2014-05-13 21:06:40 +00001117 unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
Bob Wilsond517b522010-02-01 21:17:14 +00001118 assert(NumUnavailablePreds != 0 &&
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001119 "Fully available value should already be eliminated!");
Nadav Rotem465834c2012-07-24 10:51:42 +00001120
Owen Anderson13a642d2010-10-01 20:02:55 +00001121 // If this load is unavailable in multiple predecessors, reject it.
1122 // FIXME: If we could restructure the CFG, we could make a common pred with
1123 // all the preds that don't have an available LI and insert a new load into
1124 // that one block.
1125 if (NumUnavailablePreds != 1)
Bob Wilsond517b522010-02-01 21:17:14 +00001126 return false;
Bob Wilsond517b522010-02-01 21:17:14 +00001127
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001128 // Split critical edges, and update the unavailable predecessors accordingly.
Benjamin Kramerd97f95e2014-05-13 21:06:36 +00001129 for (BasicBlock *OrigPred : CriticalEdgePred) {
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001130 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
Benjamin Kramer3f085ba2014-05-13 21:06:40 +00001131 assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
Craig Topperf40110f2014-04-25 05:29:35 +00001132 PredLoads[NewPred] = nullptr;
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001133 DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1134 << LoadBB->getName() << '\n');
1135 }
1136
Bob Wilsond517b522010-02-01 21:17:14 +00001137 // Check if the load can safely be moved to all the unavailable predecessors.
1138 bool CanDoPRE = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001139 const DataLayout &DL = LI->getModule()->getDataLayout();
Chris Lattner44da5bd2009-11-28 15:39:14 +00001140 SmallVector<Instruction*, 8> NewInsts;
Benjamin Kramerd97f95e2014-05-13 21:06:36 +00001141 for (auto &PredLoad : PredLoads) {
1142 BasicBlock *UnavailablePred = PredLoad.first;
Bob Wilsond517b522010-02-01 21:17:14 +00001143
1144 // Do PHI translation to get its value in the predecessor if necessary. The
1145 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1146
1147 // If all preds have a single successor, then we know it is safe to insert
1148 // the load on the pred (?!?), so we can insert code to materialize the
1149 // pointer if it is not available.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001150 PHITransAddr Address(LI->getPointerOperand(), DL, AC);
Craig Topperf40110f2014-04-25 05:29:35 +00001151 Value *LoadPtr = nullptr;
Shuxin Yangaf2c3dd2013-05-02 21:14:31 +00001152 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1153 *DT, NewInsts);
Bob Wilsond517b522010-02-01 21:17:14 +00001154
1155 // If we couldn't find or insert a computation of this phi translated value,
1156 // we fail PRE.
Craig Topperf40110f2014-04-25 05:29:35 +00001157 if (!LoadPtr) {
Bob Wilsond517b522010-02-01 21:17:14 +00001158 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
Dan Gohmand2099112010-11-10 19:03:33 +00001159 << *LI->getPointerOperand() << "\n");
Bob Wilsond517b522010-02-01 21:17:14 +00001160 CanDoPRE = false;
1161 break;
1162 }
1163
Benjamin Kramerd97f95e2014-05-13 21:06:36 +00001164 PredLoad.second = LoadPtr;
Chris Lattner972e6d82009-12-09 01:59:31 +00001165 }
1166
Bob Wilsond517b522010-02-01 21:17:14 +00001167 if (!CanDoPRE) {
Chris Lattner193ce7c2011-01-11 08:19:16 +00001168 while (!NewInsts.empty()) {
1169 Instruction *I = NewInsts.pop_back_val();
1170 if (MD) MD->removeInstruction(I);
1171 I->eraseFromParent();
1172 }
Benjamin Kramerd97f95e2014-05-13 21:06:36 +00001173 // HINT: Don't revert the edge-splitting as following transformation may
1174 // also need to split these critical edges.
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001175 return !CriticalEdgePred.empty();
Chris Lattner32140312009-11-28 16:08:18 +00001176 }
Dale Johannesen81b64632009-06-17 20:48:23 +00001177
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001178 // Okay, we can eliminate this load by inserting a reload in the predecessor
1179 // and using PHI construction to get the value in the other predecessors, do
1180 // it.
David Greene2e6efc42010-01-05 01:27:17 +00001181 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Chris Lattner32140312009-11-28 16:08:18 +00001182 DEBUG(if (!NewInsts.empty())
David Greene2e6efc42010-01-05 01:27:17 +00001183 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
Chris Lattner32140312009-11-28 16:08:18 +00001184 << *NewInsts.back() << '\n');
Nadav Rotem465834c2012-07-24 10:51:42 +00001185
Bob Wilsond517b522010-02-01 21:17:14 +00001186 // Assign value numbers to the new instructions.
Craig Toppere471cf32015-11-28 08:23:04 +00001187 for (Instruction *I : NewInsts) {
Wolfgang Piebce13e712017-01-04 23:58:26 +00001188 // Instructions that have been inserted in predecessor(s) to materialize
1189 // the load address do not retain their original debug locations. Doing
1190 // so could lead to confusing (but correct) source attributions.
1191 // FIXME: How do we retain source locations without causing poor debugging
1192 // behavior?
1193 I->setDebugLoc(DebugLoc());
1194
Nadav Rotem465834c2012-07-24 10:51:42 +00001195 // FIXME: We really _ought_ to insert these value numbers into their
Bob Wilsond517b522010-02-01 21:17:14 +00001196 // parent's availability map. However, in doing so, we risk getting into
1197 // ordering issues. If a block hasn't been processed yet, we would be
1198 // marking a value as AVAIL-IN, which isn't what we intend.
Chad Rosier712b7d72016-04-28 16:00:15 +00001199 VN.lookupOrAdd(I);
Bob Wilsond517b522010-02-01 21:17:14 +00001200 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001201
Benjamin Kramerd97f95e2014-05-13 21:06:36 +00001202 for (const auto &PredLoad : PredLoads) {
1203 BasicBlock *UnavailablePred = PredLoad.first;
1204 Value *LoadPtr = PredLoad.second;
Bob Wilsond517b522010-02-01 21:17:14 +00001205
Philip Reames4a3c3b62016-05-06 21:43:51 +00001206 auto *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre",
1207 LI->isVolatile(), LI->getAlignment(),
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001208 LI->getOrdering(), LI->getSyncScopeID(),
Philip Reames4a3c3b62016-05-06 21:43:51 +00001209 UnavailablePred->getTerminator());
Weiming Zhao984f1dc2017-07-19 01:27:24 +00001210 NewLoad->setDebugLoc(LI->getDebugLoc());
Dan Gohman4467aa52010-12-15 23:53:55 +00001211
Hal Finkelcc39b672014-07-24 12:16:19 +00001212 // Transfer the old load's AA tags to the new load.
1213 AAMDNodes Tags;
1214 LI->getAAMetadata(Tags);
1215 if (Tags)
1216 NewLoad->setAAMetadata(Tags);
Bob Wilsond517b522010-02-01 21:17:14 +00001217
Philip Reamesb6e8fe32015-11-17 00:15:09 +00001218 if (auto *MD = LI->getMetadata(LLVMContext::MD_invariant_load))
1219 NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001220 if (auto *InvGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group))
1221 NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
Sanjoy Das6fff9dc2016-05-27 19:03:10 +00001222 if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range))
1223 NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001224
Wolfgang Piebce13e712017-01-04 23:58:26 +00001225 // We do not propagate the old load's debug location, because the new
1226 // load now lives in a different BB, and we want to avoid a jumpy line
1227 // table.
1228 // FIXME: How do we retain source locations without causing poor debugging
1229 // behavior?
Devang Patelc5933f22011-05-17 19:43:38 +00001230
Bob Wilsond517b522010-02-01 21:17:14 +00001231 // Add the newly created load.
1232 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1233 NewLoad));
Bob Wilson923261b2010-02-23 05:55:00 +00001234 MD->invalidateCachedPointerInfo(LoadPtr);
1235 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
Bob Wilsond517b522010-02-01 21:17:14 +00001236 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001237
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001238 // Perform PHI construction.
Chris Lattnerf81f7892011-04-28 16:36:48 +00001239 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001240 LI->replaceAllUsesWith(V);
1241 if (isa<PHINode>(V))
1242 V->takeName(LI);
Alexey Samsonov89645df2015-06-10 17:37:38 +00001243 if (Instruction *I = dyn_cast<Instruction>(V))
1244 I->setDebugLoc(LI->getDebugLoc());
Craig Topper95d23472017-07-09 07:04:00 +00001245 if (V->getType()->isPtrOrPtrVectorTy())
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001246 MD->invalidateCachedPointerInfo(V);
Chris Lattnerf81f7892011-04-28 16:36:48 +00001247 markInstructionForDeletion(LI);
Adam Nemet4d2a6e52016-12-01 16:40:32 +00001248 ORE->emit(OptimizationRemark(DEBUG_TYPE, "LoadPRE", LI)
1249 << "load eliminated by PRE");
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001250 ++NumPRELoad;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001251 return true;
1252}
1253
Adam Nemet8b5fba82016-12-01 17:34:44 +00001254static void reportLoadElim(LoadInst *LI, Value *AvailableValue,
1255 OptimizationRemarkEmitter *ORE) {
1256 using namespace ore;
Eugene Zelenko8002c502017-09-13 21:43:53 +00001257
Adam Nemet4d2a6e52016-12-01 16:40:32 +00001258 ORE->emit(OptimizationRemark(DEBUG_TYPE, "LoadElim", LI)
Adam Nemet8b5fba82016-12-01 17:34:44 +00001259 << "load of type " << NV("Type", LI->getType()) << " eliminated"
1260 << setExtraArgs() << " in favor of "
1261 << NV("InfavorOfValue", AvailableValue));
Adam Nemet4d2a6e52016-12-01 16:40:32 +00001262}
1263
Sanjay Patelcee38612015-02-24 22:43:06 +00001264/// Attempt to eliminate a load whose dependencies are
Shuxin Yang637b9be2013-05-03 19:17:26 +00001265/// non-local by performing PHI construction.
1266bool GVN::processNonLocalLoad(LoadInst *LI) {
Mike Aizatskyc7810ba2015-11-18 20:43:00 +00001267 // non-local speculations are not allowed under asan.
1268 if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeAddress))
1269 return false;
1270
Shuxin Yang637b9be2013-05-03 19:17:26 +00001271 // Step 1: Find the non-local dependencies of the load.
1272 LoadDepVect Deps;
Philip Reames567feb92015-01-09 00:04:22 +00001273 MD->getNonLocalPointerDependency(LI, Deps);
Shuxin Yang637b9be2013-05-03 19:17:26 +00001274
1275 // If we had to process more than one hundred blocks to find the
1276 // dependencies, this load isn't worth worrying about. Optimizing
1277 // it will be too expensive.
1278 unsigned NumDeps = Deps.size();
1279 if (NumDeps > 100)
1280 return false;
1281
1282 // If we had a phi translation failure, we'll have a single entry which is a
1283 // clobber in the current block. Reject this early.
1284 if (NumDeps == 1 &&
1285 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1286 DEBUG(
1287 dbgs() << "GVN: non-local load ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001288 LI->printAsOperand(dbgs());
Shuxin Yang637b9be2013-05-03 19:17:26 +00001289 dbgs() << " has unknown dependencies\n";
1290 );
1291 return false;
1292 }
1293
Tim Northovereb161122015-01-09 19:19:56 +00001294 // If this load follows a GEP, see if we can PRE the indices before analyzing.
1295 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
1296 for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
1297 OE = GEP->idx_end();
1298 OI != OE; ++OI)
1299 if (Instruction *I = dyn_cast<Instruction>(OI->get()))
1300 performScalarPRE(I);
1301 }
1302
Shuxin Yang637b9be2013-05-03 19:17:26 +00001303 // Step 2: Analyze the availability of the load
1304 AvailValInBlkVect ValuesPerBlock;
1305 UnavailBlkVect UnavailableBlocks;
1306 AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1307
1308 // If we have no predecessors that produce a known value for this load, exit
1309 // early.
1310 if (ValuesPerBlock.empty())
1311 return false;
1312
1313 // Step 3: Eliminate fully redundancy.
1314 //
1315 // If all of the instructions we depend on produce a known value for this
1316 // load, then it is fully redundant and we can use PHI insertion to compute
1317 // its value. Insert PHIs and remove the fully redundant value now.
1318 if (UnavailableBlocks.empty()) {
1319 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1320
1321 // Perform PHI construction.
1322 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1323 LI->replaceAllUsesWith(V);
1324
1325 if (isa<PHINode>(V))
1326 V->takeName(LI);
Alexey Samsonov89645df2015-06-10 17:37:38 +00001327 if (Instruction *I = dyn_cast<Instruction>(V))
Andrea Di Biagioae578012016-12-07 12:31:36 +00001328 // If instruction I has debug info, then we should not update it.
1329 // Also, if I has a null DebugLoc, then it is still potentially incorrect
1330 // to propagate LI's DebugLoc because LI may not post-dominate I.
Taewook Oh75acec82017-01-31 20:57:13 +00001331 if (LI->getDebugLoc() && LI->getParent() == I->getParent())
Adrian Prantla317cd22015-08-20 18:23:56 +00001332 I->setDebugLoc(LI->getDebugLoc());
Craig Topper95d23472017-07-09 07:04:00 +00001333 if (V->getType()->isPtrOrPtrVectorTy())
Shuxin Yang637b9be2013-05-03 19:17:26 +00001334 MD->invalidateCachedPointerInfo(V);
1335 markInstructionForDeletion(LI);
1336 ++NumGVNLoad;
Adam Nemet8b5fba82016-12-01 17:34:44 +00001337 reportLoadElim(LI, V, ORE);
Shuxin Yang637b9be2013-05-03 19:17:26 +00001338 return true;
1339 }
1340
1341 // Step 4: Eliminate partial redundancy.
1342 if (!EnablePRE || !EnableLoadPRE)
1343 return false;
1344
1345 return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1346}
1347
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001348bool GVN::processAssumeIntrinsic(IntrinsicInst *IntrinsicI) {
1349 assert(IntrinsicI->getIntrinsicID() == Intrinsic::assume &&
1350 "This function can only be called with llvm.assume intrinsic");
1351 Value *V = IntrinsicI->getArgOperand(0);
Piotr Padlewski0c7d8fc2015-09-02 20:00:03 +00001352
1353 if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
1354 if (Cond->isZero()) {
1355 Type *Int8Ty = Type::getInt8Ty(V->getContext());
1356 // Insert a new store to null instruction before the load to indicate that
1357 // this code is not reachable. FIXME: We could insert unreachable
1358 // instruction directly because we can modify the CFG.
1359 new StoreInst(UndefValue::get(Int8Ty),
1360 Constant::getNullValue(Int8Ty->getPointerTo()),
1361 IntrinsicI);
1362 }
1363 markInstructionForDeletion(IntrinsicI);
1364 return false;
1365 }
1366
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001367 Constant *True = ConstantInt::getTrue(V->getContext());
1368 bool Changed = false;
Piotr Padlewski0c7d8fc2015-09-02 20:00:03 +00001369
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001370 for (BasicBlock *Successor : successors(IntrinsicI->getParent())) {
1371 BasicBlockEdge Edge(IntrinsicI->getParent(), Successor);
1372
1373 // This property is only true in dominated successors, propagateEquality
1374 // will check dominance for us.
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001375 Changed |= propagateEquality(V, True, Edge, false);
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001376 }
Piotr Padlewski0c7d8fc2015-09-02 20:00:03 +00001377
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001378 // We can replace assume value with true, which covers cases like this:
1379 // call void @llvm.assume(i1 %cmp)
1380 // br i1 %cmp, label %bb1, label %bb2 ; will change %cmp to true
1381 ReplaceWithConstMap[V] = True;
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001382
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001383 // If one of *cmp *eq operand is const, adding it to map will cover this:
1384 // %cmp = fcmp oeq float 3.000000e+00, %0 ; const on lhs could happen
1385 // call void @llvm.assume(i1 %cmp)
1386 // ret float %0 ; will change it to ret float 3.000000e+00
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001387 if (auto *CmpI = dyn_cast<CmpInst>(V)) {
1388 if (CmpI->getPredicate() == CmpInst::Predicate::ICMP_EQ ||
1389 CmpI->getPredicate() == CmpInst::Predicate::FCMP_OEQ ||
1390 (CmpI->getPredicate() == CmpInst::Predicate::FCMP_UEQ &&
1391 CmpI->getFastMathFlags().noNaNs())) {
1392 Value *CmpLHS = CmpI->getOperand(0);
1393 Value *CmpRHS = CmpI->getOperand(1);
1394 if (isa<Constant>(CmpLHS))
1395 std::swap(CmpLHS, CmpRHS);
1396 auto *RHSConst = dyn_cast<Constant>(CmpRHS);
1397
1398 // If only one operand is constant.
1399 if (RHSConst != nullptr && !isa<Constant>(CmpLHS))
1400 ReplaceWithConstMap[CmpLHS] = RHSConst;
1401 }
1402 }
1403 return Changed;
1404}
Shuxin Yang637b9be2013-05-03 19:17:26 +00001405
Dan Gohman00253592013-03-12 16:22:56 +00001406static void patchReplacementInstruction(Instruction *I, Value *Repl) {
David Majnemerd0ce8f12016-04-22 06:37:51 +00001407 auto *ReplInst = dyn_cast<Instruction>(Repl);
1408 if (!ReplInst)
1409 return;
1410
Rafael Espindola47d988c2012-06-04 22:44:21 +00001411 // Patch the replacement so that it is not more restrictive than the value
1412 // being replaced.
Taewook Oh75acec82017-01-31 20:57:13 +00001413 // Note that if 'I' is a load being replaced by some operation,
Vyacheslav Klochkov9a630df2016-11-22 20:52:53 +00001414 // for example, by an arithmetic operation, then andIRFlags()
1415 // would just erase all math flags from the original arithmetic
1416 // operation, which is clearly not wanted and not needed.
1417 if (!isa<LoadInst>(I))
1418 ReplInst->andIRFlags(I);
David Majnemer63d606b2015-06-24 21:52:25 +00001419
David Majnemerd0ce8f12016-04-22 06:37:51 +00001420 // FIXME: If both the original and replacement value are part of the
1421 // same control-flow region (meaning that the execution of one
1422 // guarantees the execution of the other), then we can combine the
1423 // noalias scopes here and do better than the general conservative
1424 // answer used in combineMetadata().
Hal Finkel94146652014-07-24 14:25:39 +00001425
David Majnemerd0ce8f12016-04-22 06:37:51 +00001426 // In general, GVN unifies expressions over different control-flow
1427 // regions, and so we need a conservative combination of the noalias
1428 // scopes.
1429 static const unsigned KnownIDs[] = {
1430 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1431 LLVMContext::MD_noalias, LLVMContext::MD_range,
1432 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1433 LLVMContext::MD_invariant_group};
1434 combineMetadata(ReplInst, I, KnownIDs);
Rafael Espindola47d988c2012-06-04 22:44:21 +00001435}
1436
Dan Gohman00253592013-03-12 16:22:56 +00001437static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1438 patchReplacementInstruction(I, Repl);
Rafael Espindola47d988c2012-06-04 22:44:21 +00001439 I->replaceAllUsesWith(Repl);
1440}
1441
Sanjay Patelcee38612015-02-24 22:43:06 +00001442/// Attempt to eliminate a load, first by eliminating it
Owen Anderson221a4362007-08-16 22:02:55 +00001443/// locally, and then attempting non-local elimination if that fails.
Chris Lattner6cec6ab2011-04-28 16:18:52 +00001444bool GVN::processLoad(LoadInst *L) {
Dan Gohman81132462009-11-14 02:27:51 +00001445 if (!MD)
1446 return false;
1447
Philip Reamesae8997f2016-05-06 18:17:13 +00001448 // This code hasn't been audited for ordered or volatile memory access
1449 if (!L->isUnordered())
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001450 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001451
Chris Lattnerf0d59072011-05-22 07:03:34 +00001452 if (L->use_empty()) {
1453 markInstructionForDeletion(L);
1454 return true;
1455 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001456
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001457 // ... to a pointer that has been loaded from before...
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001458 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001459
Philip Reames273dcb02016-01-25 23:37:53 +00001460 // If it is defined in another block, try harder.
1461 if (Dep.isNonLocal())
1462 return processNonLocalLoad(L);
1463
1464 // Only handle the local case below
1465 if (!Dep.isDef() && !Dep.isClobber()) {
1466 // This might be a NonFuncLocal or an Unknown
1467 DEBUG(
1468 // fast print dep, using operator<< on instruction is too slow.
1469 dbgs() << "GVN: load ";
1470 L->printAsOperand(dbgs());
1471 dbgs() << " has unknown dependence\n";
1472 );
1473 return false;
1474 }
1475
Philip Reames96fccc22016-02-12 19:24:57 +00001476 AvailableValue AV;
1477 if (AnalyzeLoadAvailability(L, Dep, L->getPointerOperand(), AV)) {
1478 Value *AvailableValue = AV.MaterializeAdjustedValue(L, L, *this);
Chad Rosier712b7d72016-04-28 16:00:15 +00001479
Philip Reames96fccc22016-02-12 19:24:57 +00001480 // Replace the load!
Philip Reames10a50b12016-01-25 23:19:12 +00001481 patchAndReplaceAllUsesWith(L, AvailableValue);
Duncan P. N. Exon Smithfd5c5532014-06-12 21:16:19 +00001482 markInstructionForDeletion(L);
1483 ++NumGVNLoad;
Adam Nemet8b5fba82016-12-01 17:34:44 +00001484 reportLoadElim(L, AvailableValue, ORE);
Philip Reames10a50b12016-01-25 23:19:12 +00001485 // Tell MDA to rexamine the reused pointer since we might have more
1486 // information after forwarding it.
Craig Topper95d23472017-07-09 07:04:00 +00001487 if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy())
Philip Reames10a50b12016-01-25 23:19:12 +00001488 MD->invalidateCachedPointerInfo(AvailableValue);
Duncan P. N. Exon Smithfd5c5532014-06-12 21:16:19 +00001489 return true;
1490 }
1491
Chris Lattner0e3d6332008-12-05 21:04:20 +00001492 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001493}
1494
Wei Mi55c05e12017-07-28 15:47:25 +00001495/// Return a pair the first field showing the value number of \p Exp and the
1496/// second field showing whether it is a value number newly created.
1497std::pair<uint32_t, bool>
1498GVN::ValueTable::assignExpNewValueNum(Expression &Exp) {
1499 uint32_t &e = expressionNumbering[Exp];
1500 bool CreateNewValNum = !e;
1501 if (CreateNewValNum) {
1502 Expressions.push_back(Exp);
1503 if (ExprIdx.size() < nextValueNumber + 1)
1504 ExprIdx.resize(nextValueNumber * 2);
1505 e = nextValueNumber;
1506 ExprIdx[nextValueNumber++] = nextExprNumber++;
1507 }
1508 return {e, CreateNewValNum};
1509}
1510
1511/// Return whether all the values related with the same \p num are
1512/// defined in \p BB.
1513bool GVN::ValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB,
1514 GVN &Gvn) {
1515 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
1516 while (Vals && Vals->BB == BB)
1517 Vals = Vals->Next;
1518 return !Vals;
1519}
1520
1521/// Wrap phiTranslateImpl to provide caching functionality.
1522uint32_t GVN::ValueTable::phiTranslate(const BasicBlock *Pred,
1523 const BasicBlock *PhiBlock, uint32_t Num,
1524 GVN &Gvn) {
1525 auto FindRes = PhiTranslateTable.find({Num, Pred});
1526 if (FindRes != PhiTranslateTable.end())
1527 return FindRes->second;
1528 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn);
1529 PhiTranslateTable.insert({{Num, Pred}, NewNum});
1530 return NewNum;
1531}
1532
1533/// Translate value number \p Num using phis, so that it has the values of
1534/// the phis in BB.
1535uint32_t GVN::ValueTable::phiTranslateImpl(const BasicBlock *Pred,
1536 const BasicBlock *PhiBlock,
1537 uint32_t Num, GVN &Gvn) {
1538 if (PHINode *PN = NumberingPhi[Num]) {
1539 for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
1540 if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred)
1541 if (uint32_t TransVal = lookup(PN->getIncomingValue(i), false))
1542 return TransVal;
1543 }
1544 return Num;
1545 }
1546
1547 // If there is any value related with Num is defined in a BB other than
1548 // PhiBlock, it cannot depend on a phi in PhiBlock without going through
1549 // a backedge. We can do an early exit in that case to save compile time.
1550 if (!areAllValsInBB(Num, PhiBlock, Gvn))
1551 return Num;
1552
1553 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
1554 return Num;
1555 Expression Exp = Expressions[ExprIdx[Num]];
1556
1557 for (unsigned i = 0; i < Exp.varargs.size(); i++) {
1558 // For InsertValue and ExtractValue, some varargs are index numbers
1559 // instead of value numbers. Those index numbers should not be
1560 // translated.
1561 if ((i > 1 && Exp.opcode == Instruction::InsertValue) ||
1562 (i > 0 && Exp.opcode == Instruction::ExtractValue))
1563 continue;
1564 Exp.varargs[i] = phiTranslate(Pred, PhiBlock, Exp.varargs[i], Gvn);
1565 }
1566
1567 if (Exp.commutative) {
1568 assert(Exp.varargs.size() == 2 && "Unsupported commutative expression!");
1569 if (Exp.varargs[0] > Exp.varargs[1]) {
1570 std::swap(Exp.varargs[0], Exp.varargs[1]);
1571 uint32_t Opcode = Exp.opcode >> 8;
1572 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
1573 Exp.opcode = (Opcode << 8) |
1574 CmpInst::getSwappedPredicate(
1575 static_cast<CmpInst::Predicate>(Exp.opcode & 255));
1576 }
1577 }
1578
1579 if (uint32_t NewNum = expressionNumbering[Exp])
1580 return NewNum;
1581 return Num;
1582}
1583
Wei Mibb9106a2017-08-08 21:40:14 +00001584/// Erase stale entry from phiTranslate cache so phiTranslate can be computed
1585/// again.
1586void GVN::ValueTable::eraseTranslateCacheEntry(uint32_t Num,
1587 const BasicBlock &CurrBlock) {
1588 for (const BasicBlock *Pred : predecessors(&CurrBlock)) {
1589 auto FindRes = PhiTranslateTable.find({Num, Pred});
1590 if (FindRes != PhiTranslateTable.end())
1591 PhiTranslateTable.erase(FindRes);
1592 }
1593}
1594
Sanjay Patelcee38612015-02-24 22:43:06 +00001595// In order to find a leader for a given value number at a
Owen Andersonea326db2010-11-19 22:48:40 +00001596// specific basic block, we first obtain the list of all Values for that number,
Nadav Rotem465834c2012-07-24 10:51:42 +00001597// and then scan the list to find one whose block dominates the block in
Owen Andersonea326db2010-11-19 22:48:40 +00001598// question. This is fast because dominator tree queries consist of only
1599// a few comparisons of DFS numbers.
Rafael Espindola64e7b5702012-08-10 15:55:25 +00001600Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
Owen Andersone39cb572011-01-04 19:29:46 +00001601 LeaderTableEntry Vals = LeaderTable[num];
Craig Topperf40110f2014-04-25 05:29:35 +00001602 if (!Vals.Val) return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +00001603
Craig Topperf40110f2014-04-25 05:29:35 +00001604 Value *Val = nullptr;
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001605 if (DT->dominates(Vals.BB, BB)) {
1606 Val = Vals.Val;
1607 if (isa<Constant>(Val)) return Val;
1608 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001609
Owen Andersonc7c3bc62011-01-04 19:13:25 +00001610 LeaderTableEntry* Next = Vals.Next;
Owen Andersonc21c1002010-11-18 18:32:40 +00001611 while (Next) {
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001612 if (DT->dominates(Next->BB, BB)) {
1613 if (isa<Constant>(Next->Val)) return Next->Val;
1614 if (!Val) Val = Next->Val;
1615 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001616
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001617 Next = Next->Next;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001618 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001619
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001620 return Val;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001621}
1622
Sanjay Patelcee38612015-02-24 22:43:06 +00001623/// There is an edge from 'Src' to 'Dst'. Return
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001624/// true if every path from the entry block to 'Dst' passes via this edge. In
1625/// particular 'Dst' must not be reachable via another edge from 'Src'.
1626static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
1627 DominatorTree *DT) {
1628 // While in theory it is interesting to consider the case in which Dst has
1629 // more than one predecessor, because Dst might be part of a loop which is
1630 // only reachable from Src, in practice it is pointless since at the time
1631 // GVN runs all such loops have preheaders, which means that Dst will have
1632 // been changed to have only one predecessor, namely Src.
1633 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
Chad Rosier712b7d72016-04-28 16:00:15 +00001634 assert((!Pred || Pred == E.getStart()) &&
1635 "No edge between these basic blocks!");
Craig Topperf40110f2014-04-25 05:29:35 +00001636 return Pred != nullptr;
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001637}
1638
Wei Mi55c05e12017-07-28 15:47:25 +00001639void GVN::assignBlockRPONumber(Function &F) {
1640 uint32_t NextBlockNumber = 1;
1641 ReversePostOrderTraversal<Function *> RPOT(&F);
1642 for (BasicBlock *BB : RPOT)
1643 BlockRPONumber[BB] = NextBlockNumber++;
1644}
1645
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001646// Tries to replace instruction with const, using information from
1647// ReplaceWithConstMap.
1648bool GVN::replaceOperandsWithConsts(Instruction *Instr) const {
1649 bool Changed = false;
1650 for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); ++OpNum) {
1651 Value *Operand = Instr->getOperand(OpNum);
1652 auto it = ReplaceWithConstMap.find(Operand);
1653 if (it != ReplaceWithConstMap.end()) {
Piotr Padlewski0c7d8fc2015-09-02 20:00:03 +00001654 assert(!isa<Constant>(Operand) &&
1655 "Replacing constants with constants is invalid");
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001656 DEBUG(dbgs() << "GVN replacing: " << *Operand << " with " << *it->second
1657 << " in instruction " << *Instr << '\n');
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001658 Instr->setOperand(OpNum, it->second);
1659 Changed = true;
1660 }
1661 }
1662 return Changed;
1663}
1664
Sanjay Patelcee38612015-02-24 22:43:06 +00001665/// The given values are known to be equal in every block
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001666/// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
1667/// 'RHS' everywhere in the scope. Returns whether a change was made.
David L Kreitzer4d7257d2016-01-21 21:32:35 +00001668/// If DominatesByEdge is false, then it means that we will propagate the RHS
1669/// value starting from the end of Root.Start.
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001670bool GVN::propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root,
1671 bool DominatesByEdge) {
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001672 SmallVector<std::pair<Value*, Value*>, 4> Worklist;
1673 Worklist.push_back(std::make_pair(LHS, RHS));
Duncan Sandsf537a6e2011-10-15 11:13:42 +00001674 bool Changed = false;
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001675 // For speed, compute a conservative fast approximation to
1676 // DT->dominates(Root, Root.getEnd());
Chad Rosier712b7d72016-04-28 16:00:15 +00001677 const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001678
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001679 while (!Worklist.empty()) {
1680 std::pair<Value*, Value*> Item = Worklist.pop_back_val();
1681 LHS = Item.first; RHS = Item.second;
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001682
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001683 if (LHS == RHS)
1684 continue;
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001685 assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001686
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001687 // Don't try to propagate equalities between constants.
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001688 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1689 continue;
Duncan Sands27f45952012-02-27 08:14:30 +00001690
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001691 // Prefer a constant on the right-hand side, or an Argument if no constants.
1692 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
1693 std::swap(LHS, RHS);
1694 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
Duncan Sands27f45952012-02-27 08:14:30 +00001695
Sanjay Patel06d55892015-01-12 21:21:28 +00001696 // If there is no obvious reason to prefer the left-hand side over the
1697 // right-hand side, ensure the longest lived term is on the right-hand side,
1698 // so the shortest lived term will be replaced by the longest lived.
1699 // This tends to expose more simplifications.
Chad Rosier712b7d72016-04-28 16:00:15 +00001700 uint32_t LVN = VN.lookupOrAdd(LHS);
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001701 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
1702 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
Sanjay Patel06d55892015-01-12 21:21:28 +00001703 // Move the 'oldest' value to the right-hand side, using the value number
1704 // as a proxy for age.
Chad Rosier712b7d72016-04-28 16:00:15 +00001705 uint32_t RVN = VN.lookupOrAdd(RHS);
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001706 if (LVN < RVN) {
1707 std::swap(LHS, RHS);
1708 LVN = RVN;
Duncan Sands9edea842012-02-27 12:11:41 +00001709 }
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001710 }
Duncan Sands27f45952012-02-27 08:14:30 +00001711
Duncan Sands4df5e962012-05-22 14:17:53 +00001712 // If value numbering later sees that an instruction in the scope is equal
1713 // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
1714 // the invariant that instructions only occur in the leader table for their
1715 // own value number (this is used by removeFromLeaderTable), do not do this
1716 // if RHS is an instruction (if an instruction in the scope is morphed into
1717 // LHS then it will be turned into RHS by the next GVN iteration anyway, so
1718 // using the leader table is about compiling faster, not optimizing better).
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001719 // The leader table only tracks basic blocks, not edges. Only add to if we
1720 // have the simple case where the edge dominates the end.
1721 if (RootDominatesEnd && !isa<Instruction>(RHS))
1722 addToLeaderTable(LVN, RHS, Root.getEnd());
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001723
1724 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
1725 // LHS always has at least one use that is not dominated by Root, this will
1726 // never do anything if LHS has only one use.
1727 if (!LHS->hasOneUse()) {
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001728 unsigned NumReplacements =
1729 DominatesByEdge
1730 ? replaceDominatedUsesWith(LHS, RHS, *DT, Root)
Dehao Chendb381072016-09-08 15:25:12 +00001731 : replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart());
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001732
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001733 Changed |= NumReplacements > 0;
1734 NumGVNEqProp += NumReplacements;
1735 }
1736
Sanjay Patel06d55892015-01-12 21:21:28 +00001737 // Now try to deduce additional equalities from this one. For example, if
1738 // the known equality was "(A != B)" == "false" then it follows that A and B
1739 // are equal in the scope. Only boolean equalities with an explicit true or
1740 // false RHS are currently supported.
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001741 if (!RHS->getType()->isIntegerTy(1))
1742 // Not a boolean equality - bail out.
1743 continue;
1744 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
1745 if (!CI)
1746 // RHS neither 'true' nor 'false' - bail out.
1747 continue;
1748 // Whether RHS equals 'true'. Otherwise it equals 'false'.
Craig Topper79ab6432017-07-06 18:39:47 +00001749 bool isKnownTrue = CI->isMinusOne();
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001750 bool isKnownFalse = !isKnownTrue;
1751
1752 // If "A && B" is known true then both A and B are known true. If "A || B"
1753 // is known false then both A and B are known false.
1754 Value *A, *B;
1755 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
1756 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
1757 Worklist.push_back(std::make_pair(A, RHS));
1758 Worklist.push_back(std::make_pair(B, RHS));
1759 continue;
1760 }
1761
1762 // If we are propagating an equality like "(A == B)" == "true" then also
1763 // propagate the equality A == B. When propagating a comparison such as
1764 // "(A >= B)" == "true", replace all instances of "A < B" with "false".
Sanjay Patel5f1d9ea2015-01-12 19:29:48 +00001765 if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001766 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1767
1768 // If "A == B" is known true, or "A != B" is known false, then replace
1769 // A with B everywhere in the scope.
1770 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
1771 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
1772 Worklist.push_back(std::make_pair(Op0, Op1));
1773
Sanjay Patel5f1d9ea2015-01-12 19:29:48 +00001774 // Handle the floating point versions of equality comparisons too.
1775 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::FCMP_OEQ) ||
Sanjay Patel4f07a562015-01-29 20:51:49 +00001776 (isKnownFalse && Cmp->getPredicate() == CmpInst::FCMP_UNE)) {
Sanjay Patelcc29f4f2015-02-25 22:46:08 +00001777
1778 // Floating point -0.0 and 0.0 compare equal, so we can only
1779 // propagate values if we know that we have a constant and that
1780 // its value is non-zero.
Chad Rosier712b7d72016-04-28 16:00:15 +00001781
Sanjay Patel4f07a562015-01-29 20:51:49 +00001782 // FIXME: We should do this optimization if 'no signed zeros' is
1783 // applicable via an instruction-level fast-math-flag or some other
1784 // indicator that relaxed FP semantics are being used.
Sanjay Patelcc29f4f2015-02-25 22:46:08 +00001785
1786 if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->isZero())
Sanjay Patel4f07a562015-01-29 20:51:49 +00001787 Worklist.push_back(std::make_pair(Op0, Op1));
1788 }
Chad Rosier712b7d72016-04-28 16:00:15 +00001789
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001790 // If "A >= B" is known true, replace "A < B" with false everywhere.
1791 CmpInst::Predicate NotPred = Cmp->getInversePredicate();
1792 Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
Sanjay Patel06d55892015-01-12 21:21:28 +00001793 // Since we don't have the instruction "A < B" immediately to hand, work
1794 // out the value number that it would have and use that to find an
1795 // appropriate instruction (if any).
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001796 uint32_t NextNum = VN.getNextUnusedValueNumber();
Chad Rosier712b7d72016-04-28 16:00:15 +00001797 uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001798 // If the number we were assigned was brand new then there is no point in
1799 // looking for an instruction realizing it: there cannot be one!
1800 if (Num < NextNum) {
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001801 Value *NotCmp = findLeader(Root.getEnd(), Num);
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001802 if (NotCmp && isa<Instruction>(NotCmp)) {
1803 unsigned NumReplacements =
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001804 DominatesByEdge
1805 ? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root)
1806 : replaceDominatedUsesWith(NotCmp, NotVal, *DT,
Dehao Chendb381072016-09-08 15:25:12 +00001807 Root.getStart());
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001808 Changed |= NumReplacements > 0;
1809 NumGVNEqProp += NumReplacements;
1810 }
1811 }
1812 // Ensure that any instruction in scope that gets the "A < B" value number
1813 // is replaced with false.
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001814 // The leader table only tracks basic blocks, not edges. Only add to if we
1815 // have the simple case where the edge dominates the end.
1816 if (RootDominatesEnd)
1817 addToLeaderTable(Num, NotVal, Root.getEnd());
Duncan Sandsd12b18f2012-04-06 15:31:09 +00001818
1819 continue;
1820 }
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001821 }
1822
1823 return Changed;
1824}
Owen Andersonbfe133e2008-12-15 02:03:00 +00001825
Sanjay Patelcee38612015-02-24 22:43:06 +00001826/// When calculating availability, handle an instruction
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001827/// by inserting it into the appropriate sets
Chris Lattner6cec6ab2011-04-28 16:18:52 +00001828bool GVN::processInstruction(Instruction *I) {
Devang Patel03936a12010-02-11 00:20:49 +00001829 // Ignore dbg info intrinsics.
1830 if (isa<DbgInfoIntrinsic>(I))
1831 return false;
1832
Duncan Sands246b71c2010-11-12 21:10:24 +00001833 // If the instruction can be easily simplified then do so now in preference
1834 // to value numbering it. Value numbering often exposes redundancies, for
1835 // example if it determines that %y is equal to %x then the instruction
1836 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001837 const DataLayout &DL = I->getModule()->getDataLayout();
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001838 if (Value *V = SimplifyInstruction(I, {DL, TLI, DT, AC})) {
David Majnemerb8da3a22016-06-25 00:04:10 +00001839 bool Changed = false;
1840 if (!I->use_empty()) {
1841 I->replaceAllUsesWith(V);
1842 Changed = true;
1843 }
1844 if (isInstructionTriviallyDead(I, TLI)) {
1845 markInstructionForDeletion(I);
1846 Changed = true;
1847 }
1848 if (Changed) {
Craig Topper95d23472017-07-09 07:04:00 +00001849 if (MD && V->getType()->isPtrOrPtrVectorTy())
David Majnemerb8da3a22016-06-25 00:04:10 +00001850 MD->invalidateCachedPointerInfo(V);
1851 ++NumGVNSimpl;
1852 return true;
1853 }
Duncan Sands246b71c2010-11-12 21:10:24 +00001854 }
1855
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001856 if (IntrinsicInst *IntrinsicI = dyn_cast<IntrinsicInst>(I))
1857 if (IntrinsicI->getIntrinsicID() == Intrinsic::assume)
1858 return processAssumeIntrinsic(IntrinsicI);
1859
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001860 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner6cec6ab2011-04-28 16:18:52 +00001861 if (processLoad(LI))
1862 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001863
Chad Rosier712b7d72016-04-28 16:00:15 +00001864 unsigned Num = VN.lookupOrAdd(LI);
Chris Lattner6cec6ab2011-04-28 16:18:52 +00001865 addToLeaderTable(Num, LI, LI->getParent());
1866 return false;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001867 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001868
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001869 // For conditional branches, we can perform simple conditional propagation on
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001870 // the condition value itself.
1871 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Shuxin Yang3168ab32013-11-11 22:00:23 +00001872 if (!BI->isConditional())
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001873 return false;
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001874
Shuxin Yang3168ab32013-11-11 22:00:23 +00001875 if (isa<Constant>(BI->getCondition()))
1876 return processFoldableCondBr(BI);
Bill Wendlingfed6c222013-11-10 07:34:34 +00001877
Shuxin Yang3168ab32013-11-11 22:00:23 +00001878 Value *BranchCond = BI->getCondition();
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001879 BasicBlock *TrueSucc = BI->getSuccessor(0);
1880 BasicBlock *FalseSucc = BI->getSuccessor(1);
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001881 // Avoid multiple edges early.
1882 if (TrueSucc == FalseSucc)
1883 return false;
1884
Duncan Sandse90dd052011-10-05 14:17:01 +00001885 BasicBlock *Parent = BI->getParent();
Duncan Sandsc52af462011-10-07 08:29:06 +00001886 bool Changed = false;
Duncan Sandse90dd052011-10-05 14:17:01 +00001887
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001888 Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
1889 BasicBlockEdge TrueE(Parent, TrueSucc);
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001890 Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true);
Duncan Sandsc52af462011-10-07 08:29:06 +00001891
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001892 Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
1893 BasicBlockEdge FalseE(Parent, FalseSucc);
Piotr Padlewski28ffcbe2015-09-02 19:59:59 +00001894 Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true);
Duncan Sandsc52af462011-10-07 08:29:06 +00001895
1896 return Changed;
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001897 }
Duncan Sandsc52af462011-10-07 08:29:06 +00001898
1899 // For switches, propagate the case values into the case destinations.
1900 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1901 Value *SwitchCond = SI->getCondition();
1902 BasicBlock *Parent = SI->getParent();
1903 bool Changed = false;
Benjamin Kramerdd62d6b2012-08-24 15:06:28 +00001904
1905 // Remember how many outgoing edges there are to every successor.
1906 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
1907 for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
1908 ++SwitchEdges[SI->getSuccessor(i)];
1909
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001910 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00001911 i != e; ++i) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00001912 BasicBlock *Dst = i->getCaseSuccessor();
Benjamin Kramerdd62d6b2012-08-24 15:06:28 +00001913 // If there is only a single edge, propagate the case value into it.
1914 if (SwitchEdges.lookup(Dst) == 1) {
1915 BasicBlockEdge E(Parent, Dst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00001916 Changed |= propagateEquality(SwitchCond, i->getCaseValue(), E, true);
Benjamin Kramerdd62d6b2012-08-24 15:06:28 +00001917 }
Duncan Sandsc52af462011-10-07 08:29:06 +00001918 }
1919 return Changed;
1920 }
1921
Owen Anderson7b25ff02011-01-04 22:15:21 +00001922 // Instructions with void type don't return a value, so there's
Duncan Sands1be25a72012-02-27 09:54:35 +00001923 // no point in trying to find redundancies in them.
Piotr Padlewski14e815c2015-09-02 19:59:53 +00001924 if (I->getType()->isVoidTy())
1925 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001926
Owen Anderson41a15502011-01-04 18:54:18 +00001927 uint32_t NextNum = VN.getNextUnusedValueNumber();
Chad Rosier712b7d72016-04-28 16:00:15 +00001928 unsigned Num = VN.lookupOrAdd(I);
Owen Anderson41a15502011-01-04 18:54:18 +00001929
Owen Anderson0c1e6342008-04-07 09:59:07 +00001930 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001931 // by fast failing them.
Chris Lattnerb6252a32010-12-19 20:24:28 +00001932 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
Owen Andersonc7c3bc62011-01-04 19:13:25 +00001933 addToLeaderTable(Num, I, I->getParent());
Owen Anderson0c1e6342008-04-07 09:59:07 +00001934 return false;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001935 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001936
Owen Anderson3ea90a72008-07-03 17:44:33 +00001937 // If the number we were assigned was a brand new VN, then we don't
1938 // need to do a lookup to see if the number already exists
1939 // somewhere in the domtree: it can't!
Duncan Sands1be25a72012-02-27 09:54:35 +00001940 if (Num >= NextNum) {
Owen Andersonc7c3bc62011-01-04 19:13:25 +00001941 addToLeaderTable(Num, I, I->getParent());
Chris Lattnerb6252a32010-12-19 20:24:28 +00001942 return false;
1943 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001944
Owen Andersonbfe133e2008-12-15 02:03:00 +00001945 // Perform fast-path value-number based elimination of values inherited from
1946 // dominators.
Tim Northoverd4f55c02015-10-23 20:30:02 +00001947 Value *Repl = findLeader(I->getParent(), Num);
1948 if (!Repl) {
Chris Lattnerb6252a32010-12-19 20:24:28 +00001949 // Failure, just remember this instance for future use.
Owen Andersonc7c3bc62011-01-04 19:13:25 +00001950 addToLeaderTable(Num, I, I->getParent());
Chris Lattnerb6252a32010-12-19 20:24:28 +00001951 return false;
Tim Northoverd4f55c02015-10-23 20:30:02 +00001952 } else if (Repl == I) {
1953 // If I was the result of a shortcut PRE, it might already be in the table
1954 // and the best replacement for itself. Nothing to do.
1955 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001956 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001957
Chris Lattnerb6252a32010-12-19 20:24:28 +00001958 // Remove it!
Tim Northoverd4f55c02015-10-23 20:30:02 +00001959 patchAndReplaceAllUsesWith(I, Repl);
Craig Topper95d23472017-07-09 07:04:00 +00001960 if (MD && Repl->getType()->isPtrOrPtrVectorTy())
Tim Northoverd4f55c02015-10-23 20:30:02 +00001961 MD->invalidateCachedPointerInfo(Repl);
Chris Lattnerf81f7892011-04-28 16:36:48 +00001962 markInstructionForDeletion(I);
Chris Lattnerb6252a32010-12-19 20:24:28 +00001963 return true;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001964}
1965
Bill Wendling456e8852008-12-22 22:32:22 +00001966/// runOnFunction - This is the main transformation entry point for a function.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001967bool GVN::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
Chandler Carruth89c45a12016-03-11 08:50:55 +00001968 const TargetLibraryInfo &RunTLI, AAResults &RunAA,
Adam Nemet4d2a6e52016-12-01 16:40:32 +00001969 MemoryDependenceResults *RunMD, LoopInfo *LI,
1970 OptimizationRemarkEmitter *RunORE) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001971 AC = &RunAC;
Chandler Carruth89c45a12016-03-11 08:50:55 +00001972 DT = &RunDT;
Chris Lattner8541ede2008-12-01 00:40:32 +00001973 VN.setDomTree(DT);
Chandler Carruth89c45a12016-03-11 08:50:55 +00001974 TLI = &RunTLI;
1975 VN.setAliasAnalysis(&RunAA);
1976 MD = RunMD;
1977 VN.setMemDep(MD);
Adam Nemet4d2a6e52016-12-01 16:40:32 +00001978 ORE = RunORE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001979
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001980 bool Changed = false;
1981 bool ShouldContinue = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001982
Owen Andersonac310962008-07-16 17:52:31 +00001983 // Merge unconditional branches, allowing PRE to catch more
1984 // optimization opportunities.
1985 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001986 BasicBlock *BB = &*FI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00001987
Adam Nemetfeafcd92016-12-01 03:56:43 +00001988 bool removedBlock = MergeBlockIntoPredecessor(BB, DT, LI, MD);
1989 if (removedBlock)
1990 ++NumGVNBlocks;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001991
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001992 Changed |= removedBlock;
Owen Andersonac310962008-07-16 17:52:31 +00001993 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001994
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001995 unsigned Iteration = 0;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001996 while (ShouldContinue) {
David Greene2e6efc42010-01-05 01:27:17 +00001997 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001998 ShouldContinue = iterateOnFunction(F);
1999 Changed |= ShouldContinue;
Chris Lattner0a5a8d52008-12-09 19:21:47 +00002000 ++Iteration;
Owen Anderson676070d2007-08-14 18:04:11 +00002001 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002002
Owen Anderson04a6e0b2008-07-18 18:03:38 +00002003 if (EnablePRE) {
Shuxin Yang3168ab32013-11-11 22:00:23 +00002004 // Fabricate val-num for dead-code in order to suppress assertion in
2005 // performPRE().
2006 assignValNumForDeadCode();
Wei Mi55c05e12017-07-28 15:47:25 +00002007 assignBlockRPONumber(F);
Owen Anderson2fbfb702008-09-03 23:06:07 +00002008 bool PREChanged = true;
2009 while (PREChanged) {
2010 PREChanged = performPRE(F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002011 Changed |= PREChanged;
Owen Anderson2fbfb702008-09-03 23:06:07 +00002012 }
Owen Anderson04a6e0b2008-07-18 18:03:38 +00002013 }
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00002014
Chris Lattner0a5a8d52008-12-09 19:21:47 +00002015 // FIXME: Should perform GVN again after PRE does something. PRE can move
2016 // computations into blocks where they become fully redundant. Note that
2017 // we can't do this until PRE's critical edge splitting updates memdep.
2018 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopese3127f32008-10-10 16:25:50 +00002019
2020 cleanupGlobalSets();
Shuxin Yang3168ab32013-11-11 22:00:23 +00002021 // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
Chad Rosier712b7d72016-04-28 16:00:15 +00002022 // iteration.
Shuxin Yang3168ab32013-11-11 22:00:23 +00002023 DeadBlocks.clear();
Nuno Lopese3127f32008-10-10 16:25:50 +00002024
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002025 return Changed;
Owen Anderson676070d2007-08-14 18:04:11 +00002026}
2027
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002028bool GVN::processBlock(BasicBlock *BB) {
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002029 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2030 // (and incrementing BI before processing an instruction).
2031 assert(InstrsToErase.empty() &&
2032 "We expect InstrsToErase to be empty across iterations");
Shuxin Yang3168ab32013-11-11 22:00:23 +00002033 if (DeadBlocks.count(BB))
2034 return false;
2035
Piotr Padlewski14e815c2015-09-02 19:59:53 +00002036 // Clearing map before every BB because it can be used only for single BB.
2037 ReplaceWithConstMap.clear();
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002038 bool ChangedFunction = false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002039
Owen Andersonaccdca12008-06-12 19:25:32 +00002040 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2041 BI != BE;) {
Piotr Padlewski14e815c2015-09-02 19:59:53 +00002042 if (!ReplaceWithConstMap.empty())
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00002043 ChangedFunction |= replaceOperandsWithConsts(&*BI);
2044 ChangedFunction |= processInstruction(&*BI);
Piotr Padlewski0c7d8fc2015-09-02 20:00:03 +00002045
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002046 if (InstrsToErase.empty()) {
Owen Andersonaccdca12008-06-12 19:25:32 +00002047 ++BI;
2048 continue;
2049 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002050
Owen Andersonaccdca12008-06-12 19:25:32 +00002051 // If we need some instructions deleted, do it now.
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002052 NumGVNInstr += InstrsToErase.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002053
Owen Andersonaccdca12008-06-12 19:25:32 +00002054 // Avoid iterator invalidation.
2055 bool AtStart = BI == BB->begin();
2056 if (!AtStart)
2057 --BI;
2058
Craig Topperaf0dea12013-07-04 01:31:24 +00002059 for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002060 E = InstrsToErase.end(); I != E; ++I) {
David Greene2e6efc42010-01-05 01:27:17 +00002061 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
Dan Gohman81132462009-11-14 02:27:51 +00002062 if (MD) MD->removeInstruction(*I);
Bill Wendlingebb6a542008-12-22 21:57:30 +00002063 DEBUG(verifyRemoved(*I));
Dan Gohmanfd41de02013-02-12 18:44:43 +00002064 (*I)->eraseFromParent();
Chris Lattner8541ede2008-12-01 00:40:32 +00002065 }
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002066 InstrsToErase.clear();
Owen Andersonaccdca12008-06-12 19:25:32 +00002067
2068 if (AtStart)
2069 BI = BB->begin();
2070 else
2071 ++BI;
Owen Andersonaccdca12008-06-12 19:25:32 +00002072 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002073
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002074 return ChangedFunction;
Owen Andersonaccdca12008-06-12 19:25:32 +00002075}
2076
Daniel Berlin487aed02015-02-03 20:37:08 +00002077// Instantiate an expression in a predecessor that lacked it.
2078bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
Wei Mi55c05e12017-07-28 15:47:25 +00002079 BasicBlock *Curr, unsigned int ValNo) {
Daniel Berlin487aed02015-02-03 20:37:08 +00002080 // Because we are going top-down through the block, all value numbers
2081 // will be available in the predecessor by the time we need them. Any
2082 // that weren't originally present will have been instantiated earlier
2083 // in this loop.
2084 bool success = true;
2085 for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
2086 Value *Op = Instr->getOperand(i);
2087 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2088 continue;
Weiming Zhaob69babd2015-11-19 02:45:18 +00002089 // This could be a newly inserted instruction, in which case, we won't
2090 // find a value number, and should give up before we hurt ourselves.
2091 // FIXME: Rewrite the infrastructure to let it easier to value number
2092 // and process newly inserted instructions.
2093 if (!VN.exists(Op)) {
2094 success = false;
2095 break;
2096 }
Wei Mi55c05e12017-07-28 15:47:25 +00002097 uint32_t TValNo =
2098 VN.phiTranslate(Pred, Curr, VN.lookup(Op), *this);
2099 if (Value *V = findLeader(Pred, TValNo)) {
Daniel Berlin487aed02015-02-03 20:37:08 +00002100 Instr->setOperand(i, V);
2101 } else {
2102 success = false;
2103 break;
2104 }
2105 }
2106
2107 // Fail out if we encounter an operand that is not available in
2108 // the PRE predecessor. This is typically because of loads which
2109 // are not value numbered precisely.
2110 if (!success)
2111 return false;
2112
2113 Instr->insertBefore(Pred->getTerminator());
2114 Instr->setName(Instr->getName() + ".pre");
2115 Instr->setDebugLoc(Instr->getDebugLoc());
Wei Mi55c05e12017-07-28 15:47:25 +00002116
2117 unsigned Num = VN.lookupOrAdd(Instr);
2118 VN.add(Instr, Num);
Daniel Berlin487aed02015-02-03 20:37:08 +00002119
2120 // Update the availability map to include the new instruction.
Wei Mi55c05e12017-07-28 15:47:25 +00002121 addToLeaderTable(Num, Instr, Pred);
Daniel Berlin487aed02015-02-03 20:37:08 +00002122 return true;
2123}
2124
Tim Northovereb161122015-01-09 19:19:56 +00002125bool GVN::performScalarPRE(Instruction *CurInst) {
Tim Northovereb161122015-01-09 19:19:56 +00002126 if (isa<AllocaInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
2127 isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
2128 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2129 isa<DbgInfoIntrinsic>(CurInst))
2130 return false;
2131
2132 // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
2133 // sinking the compare again, and it would force the code generator to
2134 // move the i1 from processor flags or predicate registers into a general
2135 // purpose register.
2136 if (isa<CmpInst>(CurInst))
2137 return false;
2138
2139 // We don't currently value number ANY inline asm calls.
2140 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2141 if (CallI->isInlineAsm())
2142 return false;
2143
2144 uint32_t ValNo = VN.lookup(CurInst);
2145
2146 // Look for the predecessors for PRE opportunities. We're
2147 // only trying to solve the basic diamond case, where
2148 // a value is computed in the successor and one predecessor,
2149 // but not the other. We also explicitly disallow cases
2150 // where the successor is its own predecessor, because they're
2151 // more complicated to get right.
2152 unsigned NumWith = 0;
2153 unsigned NumWithout = 0;
2154 BasicBlock *PREPred = nullptr;
2155 BasicBlock *CurrentBlock = CurInst->getParent();
Tim Northovereb161122015-01-09 19:19:56 +00002156
Chad Rosier712b7d72016-04-28 16:00:15 +00002157 SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap;
Craig Toppere471cf32015-11-28 08:23:04 +00002158 for (BasicBlock *P : predecessors(CurrentBlock)) {
Wei Mi55c05e12017-07-28 15:47:25 +00002159 // We're not interested in PRE where blocks with predecessors that are
2160 // not reachable.
2161 if (!DT->isReachableFromEntry(P)) {
Tim Northovereb161122015-01-09 19:19:56 +00002162 NumWithout = 2;
2163 break;
Wei Mi55c05e12017-07-28 15:47:25 +00002164 }
2165 // It is not safe to do PRE when P->CurrentBlock is a loop backedge, and
2166 // when CurInst has operand defined in CurrentBlock (so it may be defined
2167 // by phi in the loop header).
2168 if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
Eugene Zelenko8002c502017-09-13 21:43:53 +00002169 llvm::any_of(CurInst->operands(), [&](const Use &U) {
Wei Mi55c05e12017-07-28 15:47:25 +00002170 if (auto *Inst = dyn_cast<Instruction>(U.get()))
2171 return Inst->getParent() == CurrentBlock;
2172 return false;
2173 })) {
Tim Northovereb161122015-01-09 19:19:56 +00002174 NumWithout = 2;
2175 break;
2176 }
2177
Wei Mi55c05e12017-07-28 15:47:25 +00002178 uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, *this);
2179 Value *predV = findLeader(P, TValNo);
Tim Northovereb161122015-01-09 19:19:56 +00002180 if (!predV) {
2181 predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
2182 PREPred = P;
2183 ++NumWithout;
2184 } else if (predV == CurInst) {
2185 /* CurInst dominates this predecessor. */
2186 NumWithout = 2;
2187 break;
2188 } else {
2189 predMap.push_back(std::make_pair(predV, P));
2190 ++NumWith;
2191 }
2192 }
2193
2194 // Don't do PRE when it might increase code size, i.e. when
2195 // we would need to insert instructions in more than one pred.
Daniel Berlin487aed02015-02-03 20:37:08 +00002196 if (NumWithout > 1 || NumWith == 0)
Tim Northovereb161122015-01-09 19:19:56 +00002197 return false;
2198
Daniel Berlin487aed02015-02-03 20:37:08 +00002199 // We may have a case where all predecessors have the instruction,
2200 // and we just need to insert a phi node. Otherwise, perform
2201 // insertion.
2202 Instruction *PREInstr = nullptr;
Tim Northovereb161122015-01-09 19:19:56 +00002203
Daniel Berlin487aed02015-02-03 20:37:08 +00002204 if (NumWithout != 0) {
2205 // Don't do PRE across indirect branch.
2206 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2207 return false;
Tim Northovereb161122015-01-09 19:19:56 +00002208
Daniel Berlin487aed02015-02-03 20:37:08 +00002209 // We can't do PRE safely on a critical edge, so instead we schedule
2210 // the edge to be split and perform the PRE the next time we iterate
2211 // on the function.
2212 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2213 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2214 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2215 return false;
2216 }
2217 // We need to insert somewhere, so let's give it a shot
2218 PREInstr = CurInst->clone();
Wei Mi55c05e12017-07-28 15:47:25 +00002219 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
Daniel Berlin487aed02015-02-03 20:37:08 +00002220 // If we failed insertion, make sure we remove the instruction.
2221 DEBUG(verifyRemoved(PREInstr));
Reid Kleckner96ab8722017-05-18 17:24:10 +00002222 PREInstr->deleteValue();
Daniel Berlin487aed02015-02-03 20:37:08 +00002223 return false;
Tim Northovereb161122015-01-09 19:19:56 +00002224 }
2225 }
2226
Daniel Berlin487aed02015-02-03 20:37:08 +00002227 // Either we should have filled in the PRE instruction, or we should
2228 // not have needed insertions.
Eugene Zelenko8002c502017-09-13 21:43:53 +00002229 assert(PREInstr != nullptr || NumWithout == 0);
Tim Northovereb161122015-01-09 19:19:56 +00002230
Tim Northovereb161122015-01-09 19:19:56 +00002231 ++NumGVNPRE;
2232
Tim Northovereb161122015-01-09 19:19:56 +00002233 // Create a PHI to make the value available in this block.
2234 PHINode *Phi =
2235 PHINode::Create(CurInst->getType(), predMap.size(),
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00002236 CurInst->getName() + ".pre-phi", &CurrentBlock->front());
Tim Northovereb161122015-01-09 19:19:56 +00002237 for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
2238 if (Value *V = predMap[i].first)
2239 Phi->addIncoming(V, predMap[i].second);
2240 else
2241 Phi->addIncoming(PREInstr, PREPred);
2242 }
2243
2244 VN.add(Phi, ValNo);
Wei Mibb9106a2017-08-08 21:40:14 +00002245 // After creating a new PHI for ValNo, the phi translate result for ValNo will
2246 // be changed, so erase the related stale entries in phi translate cache.
2247 VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
Tim Northovereb161122015-01-09 19:19:56 +00002248 addToLeaderTable(ValNo, Phi, CurrentBlock);
2249 Phi->setDebugLoc(CurInst->getDebugLoc());
2250 CurInst->replaceAllUsesWith(Phi);
Craig Topper95d23472017-07-09 07:04:00 +00002251 if (MD && Phi->getType()->isPtrOrPtrVectorTy())
Chandler Carruth9f2bf1af2015-07-18 03:26:46 +00002252 MD->invalidateCachedPointerInfo(Phi);
Tim Northovereb161122015-01-09 19:19:56 +00002253 VN.erase(CurInst);
2254 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2255
2256 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2257 if (MD)
2258 MD->removeInstruction(CurInst);
2259 DEBUG(verifyRemoved(CurInst));
2260 CurInst->eraseFromParent();
Daniel Berlin487aed02015-02-03 20:37:08 +00002261 ++NumGVNInstr;
Chad Rosier712b7d72016-04-28 16:00:15 +00002262
Tim Northovereb161122015-01-09 19:19:56 +00002263 return true;
2264}
2265
Sanjay Patelcee38612015-02-24 22:43:06 +00002266/// Perform a purely local form of PRE that looks for diamond
Owen Anderson6a903bc2008-06-18 21:41:49 +00002267/// control flow patterns and attempts to perform simple PRE at the join point.
Chris Lattnera546dcf2009-10-31 22:11:15 +00002268bool GVN::performPRE(Function &F) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002269 bool Changed = false;
David Blaikieceec2bd2014-04-11 01:50:01 +00002270 for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
Owen Anderson6a903bc2008-06-18 21:41:49 +00002271 // Nothing to PRE in the entry block.
Tim Northovereb161122015-01-09 19:19:56 +00002272 if (CurrentBlock == &F.getEntryBlock())
2273 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002274
David Majnemereb518bd2015-08-04 08:21:40 +00002275 // Don't perform PRE on an EH pad.
2276 if (CurrentBlock->isEHPad())
Tim Northovereb161122015-01-09 19:19:56 +00002277 continue;
Bill Wendling8bbcbed2011-08-17 21:32:02 +00002278
Owen Anderson6a903bc2008-06-18 21:41:49 +00002279 for (BasicBlock::iterator BI = CurrentBlock->begin(),
Tim Northovereb161122015-01-09 19:19:56 +00002280 BE = CurrentBlock->end();
2281 BI != BE;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00002282 Instruction *CurInst = &*BI++;
Mehdi Aminiadb40572015-11-18 22:49:49 +00002283 Changed |= performScalarPRE(CurInst);
Owen Anderson6a903bc2008-06-18 21:41:49 +00002284 }
2285 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002286
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002287 if (splitCriticalEdges())
2288 Changed = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002289
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002290 return Changed;
2291}
2292
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00002293/// Split the critical edge connecting the given two blocks, and return
2294/// the block inserted to the critical edge.
2295BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
Chandler Carruth96ada252015-07-22 09:52:54 +00002296 BasicBlock *BB =
2297 SplitCriticalEdge(Pred, Succ, CriticalEdgeSplittingOptions(DT));
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00002298 if (MD)
2299 MD->invalidateCachedPredecessors();
2300 return BB;
2301}
2302
Sanjay Patelcee38612015-02-24 22:43:06 +00002303/// Split critical edges found during the previous
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002304/// iteration that may enable further optimization.
2305bool GVN::splitCriticalEdges() {
2306 if (toSplit.empty())
2307 return false;
2308 do {
2309 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
Chandler Carruth37df2cf2015-01-19 12:09:11 +00002310 SplitCriticalEdge(Edge.first, Edge.second,
Chandler Carruth96ada252015-07-22 09:52:54 +00002311 CriticalEdgeSplittingOptions(DT));
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002312 } while (!toSplit.empty());
Evan Cheng7263cf8432010-03-01 22:23:12 +00002313 if (MD) MD->invalidateCachedPredecessors();
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002314 return true;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002315}
2316
Sanjay Patelcee38612015-02-24 22:43:06 +00002317/// Executes one iteration of GVN
Owen Anderson676070d2007-08-14 18:04:11 +00002318bool GVN::iterateOnFunction(Function &F) {
Nuno Lopese3127f32008-10-10 16:25:50 +00002319 cleanupGlobalSets();
Nadav Rotem465834c2012-07-24 10:51:42 +00002320
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002321 // Top-down walk of the dominator tree
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002322 bool Changed = false;
Tim Northovereb161122015-01-09 19:19:56 +00002323 // Needed for value numbering with phi construction to work.
Craig Topperd55e1532017-03-18 18:24:41 +00002324 // RPOT walks the graph in its constructor and will not be invalidated during
2325 // processBlock.
Tim Northovereb161122015-01-09 19:19:56 +00002326 ReversePostOrderTraversal<Function *> RPOT(&F);
Craig Topperd55e1532017-03-18 18:24:41 +00002327 for (BasicBlock *BB : RPOT)
2328 Changed |= processBlock(BB);
Chad Rosier8716b582014-11-13 22:54:59 +00002329
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002330 return Changed;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002331}
Nuno Lopese3127f32008-10-10 16:25:50 +00002332
2333void GVN::cleanupGlobalSets() {
2334 VN.clear();
Owen Andersone39cb572011-01-04 19:29:46 +00002335 LeaderTable.clear();
Wei Mi55c05e12017-07-28 15:47:25 +00002336 BlockRPONumber.clear();
Owen Andersonc21c1002010-11-18 18:32:40 +00002337 TableAllocator.Reset();
Nuno Lopese3127f32008-10-10 16:25:50 +00002338}
Bill Wendling6b18a392008-12-22 21:36:08 +00002339
Sanjay Patelcee38612015-02-24 22:43:06 +00002340/// Verify that the specified instruction does not occur in our
Bill Wendling6b18a392008-12-22 21:36:08 +00002341/// internal data structures.
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002342void GVN::verifyRemoved(const Instruction *Inst) const {
2343 VN.verifyRemoved(Inst);
Bill Wendling3c793442008-12-22 22:14:07 +00002344
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002345 // Walk through the value number scope to make sure the instruction isn't
2346 // ferreted away in it.
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002347 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
Owen Andersone39cb572011-01-04 19:29:46 +00002348 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002349 const LeaderTableEntry *Node = &I->second;
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002350 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Nadav Rotem465834c2012-07-24 10:51:42 +00002351
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002352 while (Node->Next) {
2353 Node = Node->Next;
2354 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Bill Wendling3c793442008-12-22 22:14:07 +00002355 }
2356 }
Bill Wendling6b18a392008-12-22 21:36:08 +00002357}
Shuxin Yang3168ab32013-11-11 22:00:23 +00002358
Sanjay Patelcee38612015-02-24 22:43:06 +00002359/// BB is declared dead, which implied other blocks become dead as well. This
2360/// function is to add all these blocks to "DeadBlocks". For the dead blocks'
2361/// live successors, update their phi nodes by replacing the operands
2362/// corresponding to dead blocks with UndefVal.
Shuxin Yang3168ab32013-11-11 22:00:23 +00002363void GVN::addDeadBlock(BasicBlock *BB) {
2364 SmallVector<BasicBlock *, 4> NewDead;
2365 SmallSetVector<BasicBlock *, 4> DF;
2366
2367 NewDead.push_back(BB);
2368 while (!NewDead.empty()) {
2369 BasicBlock *D = NewDead.pop_back_val();
2370 if (DeadBlocks.count(D))
2371 continue;
2372
2373 // All blocks dominated by D are dead.
2374 SmallVector<BasicBlock *, 8> Dom;
2375 DT->getDescendants(D, Dom);
2376 DeadBlocks.insert(Dom.begin(), Dom.end());
Chad Rosier712b7d72016-04-28 16:00:15 +00002377
Shuxin Yang3168ab32013-11-11 22:00:23 +00002378 // Figure out the dominance-frontier(D).
Craig Toppere471cf32015-11-28 08:23:04 +00002379 for (BasicBlock *B : Dom) {
2380 for (BasicBlock *S : successors(B)) {
Shuxin Yang3168ab32013-11-11 22:00:23 +00002381 if (DeadBlocks.count(S))
2382 continue;
2383
2384 bool AllPredDead = true;
Craig Toppere471cf32015-11-28 08:23:04 +00002385 for (BasicBlock *P : predecessors(S))
2386 if (!DeadBlocks.count(P)) {
Shuxin Yang3168ab32013-11-11 22:00:23 +00002387 AllPredDead = false;
2388 break;
2389 }
2390
2391 if (!AllPredDead) {
2392 // S could be proved dead later on. That is why we don't update phi
2393 // operands at this moment.
2394 DF.insert(S);
2395 } else {
2396 // While S is not dominated by D, it is dead by now. This could take
2397 // place if S already have a dead predecessor before D is declared
2398 // dead.
2399 NewDead.push_back(S);
2400 }
2401 }
2402 }
2403 }
2404
2405 // For the dead blocks' live successors, update their phi nodes by replacing
2406 // the operands corresponding to dead blocks with UndefVal.
2407 for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
2408 I != E; I++) {
2409 BasicBlock *B = *I;
2410 if (DeadBlocks.count(B))
2411 continue;
2412
Shuxin Yangf1ec34b2013-11-12 08:33:03 +00002413 SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
Craig Toppere471cf32015-11-28 08:23:04 +00002414 for (BasicBlock *P : Preds) {
Shuxin Yang3168ab32013-11-11 22:00:23 +00002415 if (!DeadBlocks.count(P))
2416 continue;
2417
2418 if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
2419 if (BasicBlock *S = splitCriticalEdges(P, B))
2420 DeadBlocks.insert(P = S);
2421 }
2422
2423 for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
2424 PHINode &Phi = cast<PHINode>(*II);
2425 Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
2426 UndefValue::get(Phi.getType()));
2427 }
2428 }
2429 }
2430}
2431
2432// If the given branch is recognized as a foldable branch (i.e. conditional
2433// branch with constant condition), it will perform following analyses and
2434// transformation.
Chad Rosier712b7d72016-04-28 16:00:15 +00002435// 1) If the dead out-coming edge is a critical-edge, split it. Let
Shuxin Yang3168ab32013-11-11 22:00:23 +00002436// R be the target of the dead out-coming edge.
2437// 1) Identify the set of dead blocks implied by the branch's dead outcoming
2438// edge. The result of this step will be {X| X is dominated by R}
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002439// 2) Identify those blocks which haves at least one dead predecessor. The
Shuxin Yang3168ab32013-11-11 22:00:23 +00002440// result of this step will be dominance-frontier(R).
Chad Rosier712b7d72016-04-28 16:00:15 +00002441// 3) Update the PHIs in DF(R) by replacing the operands corresponding to
Shuxin Yang3168ab32013-11-11 22:00:23 +00002442// dead blocks with "UndefVal" in an hope these PHIs will optimized away.
2443//
2444// Return true iff *NEW* dead code are found.
2445bool GVN::processFoldableCondBr(BranchInst *BI) {
2446 if (!BI || BI->isUnconditional())
2447 return false;
2448
Peter Collingbourne2a3443c2015-06-25 18:32:02 +00002449 // If a branch has two identical successors, we cannot declare either dead.
2450 if (BI->getSuccessor(0) == BI->getSuccessor(1))
2451 return false;
2452
Shuxin Yang3168ab32013-11-11 22:00:23 +00002453 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
2454 if (!Cond)
2455 return false;
2456
Chad Rosier712b7d72016-04-28 16:00:15 +00002457 BasicBlock *DeadRoot =
2458 Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0);
Shuxin Yang3168ab32013-11-11 22:00:23 +00002459 if (DeadBlocks.count(DeadRoot))
2460 return false;
2461
2462 if (!DeadRoot->getSinglePredecessor())
2463 DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
2464
2465 addDeadBlock(DeadRoot);
2466 return true;
2467}
2468
JF Bastienac8b66b2014-08-05 23:27:34 +00002469// performPRE() will trigger assert if it comes across an instruction without
Shuxin Yang3168ab32013-11-11 22:00:23 +00002470// associated val-num. As it normally has far more live instructions than dead
2471// instructions, it makes more sense just to "fabricate" a val-number for the
2472// dead code than checking if instruction involved is dead or not.
2473void GVN::assignValNumForDeadCode() {
Craig Toppere471cf32015-11-28 08:23:04 +00002474 for (BasicBlock *BB : DeadBlocks) {
2475 for (Instruction &Inst : *BB) {
Chad Rosier712b7d72016-04-28 16:00:15 +00002476 unsigned ValNum = VN.lookupOrAdd(&Inst);
Craig Toppere471cf32015-11-28 08:23:04 +00002477 addToLeaderTable(ValNum, &Inst, BB);
Shuxin Yang3168ab32013-11-11 22:00:23 +00002478 }
2479 }
2480}
Chandler Carruth89c45a12016-03-11 08:50:55 +00002481
2482class llvm::gvn::GVNLegacyPass : public FunctionPass {
2483public:
2484 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko8002c502017-09-13 21:43:53 +00002485
Chandler Carruth89c45a12016-03-11 08:50:55 +00002486 explicit GVNLegacyPass(bool NoLoads = false)
2487 : FunctionPass(ID), NoLoads(NoLoads) {
2488 initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry());
2489 }
2490
2491 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00002492 if (skipFunction(F))
Chandler Carruth89c45a12016-03-11 08:50:55 +00002493 return false;
2494
Adam Nemetfeafcd92016-12-01 03:56:43 +00002495 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
2496
Chandler Carruth89c45a12016-03-11 08:50:55 +00002497 return Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002498 F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2499 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
Chandler Carruth89c45a12016-03-11 08:50:55 +00002500 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2501 getAnalysis<AAResultsWrapperPass>().getAAResults(),
2502 NoLoads ? nullptr
Adam Nemetfeafcd92016-12-01 03:56:43 +00002503 : &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(),
Adam Nemet4d2a6e52016-12-01 16:40:32 +00002504 LIWP ? &LIWP->getLoopInfo() : nullptr,
2505 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
Chandler Carruth89c45a12016-03-11 08:50:55 +00002506 }
2507
2508 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002509 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth89c45a12016-03-11 08:50:55 +00002510 AU.addRequired<DominatorTreeWrapperPass>();
2511 AU.addRequired<TargetLibraryInfoWrapperPass>();
2512 if (!NoLoads)
2513 AU.addRequired<MemoryDependenceWrapperPass>();
2514 AU.addRequired<AAResultsWrapperPass>();
2515
2516 AU.addPreserved<DominatorTreeWrapperPass>();
2517 AU.addPreserved<GlobalsAAWrapperPass>();
Davide Italiano116464a2017-01-31 21:53:18 +00002518 AU.addPreserved<TargetLibraryInfoWrapperPass>();
Adam Nemet4d2a6e52016-12-01 16:40:32 +00002519 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Chandler Carruth89c45a12016-03-11 08:50:55 +00002520 }
2521
2522private:
2523 bool NoLoads;
2524 GVN Impl;
2525};
2526
2527char GVNLegacyPass::ID = 0;
2528
Chandler Carruth89c45a12016-03-11 08:50:55 +00002529INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002530INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth89c45a12016-03-11 08:50:55 +00002531INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2532INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2533INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2534INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2535INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Adam Nemet4d2a6e52016-12-01 16:40:32 +00002536INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Chandler Carruth89c45a12016-03-11 08:50:55 +00002537INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
Eugene Zelenko8002c502017-09-13 21:43:53 +00002538
2539// The public interface to this file...
2540FunctionPass *llvm::createGVNPass(bool NoLoads) {
2541 return new GVNLegacyPass(NoLoads);
2542}