blob: 237faede16bf676681f26d33abd9f7191751ff4d [file] [log] [blame]
Teresa Johnson2d5487c2016-04-11 13:58:45 +00001//===- ModuleSummaryAnalysis.cpp - Module summary index builder -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass builds a ModuleSummaryIndex object for the module, to be written
11// to bitcode or LLVM assembly.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000016#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseSet.h"
Peter Collingbourne0c30f082016-12-20 21:12:28 +000018#include "llvm/ADT/MapVector.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000019#include "llvm/ADT/STLExtras.h"
Peter Collingbourne0c30f082016-12-20 21:12:28 +000020#include "llvm/ADT/SetVector.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000024#include "llvm/Analysis/BlockFrequencyInfo.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000025#include "llvm/Analysis/BranchProbabilityInfo.h"
Teresa Johnsoncd21a642016-07-17 14:47:01 +000026#include "llvm/Analysis/IndirectCallPromotionAnalysis.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000027#include "llvm/Analysis/LoopInfo.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000028#include "llvm/Analysis/ProfileSummaryInfo.h"
Peter Collingbourne1b4137a72016-12-21 23:03:45 +000029#include "llvm/Analysis/TypeMetadataUtils.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000030#include "llvm/IR/Attributes.h"
31#include "llvm/IR/BasicBlock.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000032#include "llvm/IR/CallSite.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000033#include "llvm/IR/Constant.h"
34#include "llvm/IR/Constants.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000035#include "llvm/IR/Dominators.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000036#include "llvm/IR/Function.h"
37#include "llvm/IR/GlobalAlias.h"
38#include "llvm/IR/GlobalValue.h"
39#include "llvm/IR/GlobalVariable.h"
40#include "llvm/IR/Instructions.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000041#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000042#include "llvm/IR/Intrinsics.h"
43#include "llvm/IR/Metadata.h"
44#include "llvm/IR/Module.h"
45#include "llvm/IR/ModuleSummaryIndex.h"
46#include "llvm/IR/Use.h"
47#include "llvm/IR/User.h"
Peter Collingbourne61781ac2017-03-31 00:08:24 +000048#include "llvm/Object/ModuleSymbolTable.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000049#include "llvm/Object/SymbolicFile.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000050#include "llvm/Pass.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000051#include "llvm/Support/Casting.h"
Teresa Johnsondb83ace2018-03-31 00:18:08 +000052#include "llvm/Support/CommandLine.h"
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +000053#include <algorithm>
54#include <cassert>
55#include <cstdint>
56#include <vector>
57
Teresa Johnson2d5487c2016-04-11 13:58:45 +000058using namespace llvm;
59
60#define DEBUG_TYPE "module-summary-analysis"
61
Teresa Johnsondb83ace2018-03-31 00:18:08 +000062// Option to force edges cold which will block importing when the
63// -import-cold-multiplier is set to 0. Useful for debugging.
64FunctionSummary::ForceSummaryHotnessType ForceSummaryEdgesCold =
65 FunctionSummary::FSHT_None;
66cl::opt<FunctionSummary::ForceSummaryHotnessType, true> FSEC(
67 "force-summary-edges-cold", cl::Hidden, cl::location(ForceSummaryEdgesCold),
68 cl::desc("Force all edges in the function summary to cold"),
69 cl::values(clEnumValN(FunctionSummary::FSHT_None, "none", "None."),
70 clEnumValN(FunctionSummary::FSHT_AllNonCritical,
71 "all-non-critical", "All non-critical edges."),
72 clEnumValN(FunctionSummary::FSHT_All, "all", "All edges.")));
73
Teresa Johnson2d5487c2016-04-11 13:58:45 +000074// Walk through the operands of a given User via worklist iteration and populate
75// the set of GlobalValue references encountered. Invoked either on an
76// Instruction or a GlobalVariable (which walks its initializer).
Eugene Levianteddf6b52018-10-12 07:24:02 +000077// Return true if any of the operands contains blockaddress. This is important
78// to know when computing summary for global var, because if global variable
79// references basic block address we can't import it separately from function
80// containing that basic block. For simplicity we currently don't import such
81// global vars at all. When importing function we aren't interested if any
82// instruction in it takes an address of any basic block, because instruction
83// can only take an address of basic block located in the same function.
84static bool findRefEdges(ModuleSummaryIndex &Index, const User *CurUser,
Peter Collingbourne9667b912017-05-04 18:03:25 +000085 SetVector<ValueInfo> &RefEdges,
Teresa Johnson2d5487c2016-04-11 13:58:45 +000086 SmallPtrSet<const User *, 8> &Visited) {
Eugene Levianteddf6b52018-10-12 07:24:02 +000087 bool HasBlockAddress = false;
Teresa Johnson2d5487c2016-04-11 13:58:45 +000088 SmallVector<const User *, 32> Worklist;
89 Worklist.push_back(CurUser);
90
91 while (!Worklist.empty()) {
92 const User *U = Worklist.pop_back_val();
93
94 if (!Visited.insert(U).second)
95 continue;
96
97 ImmutableCallSite CS(U);
98
99 for (const auto &OI : U->operands()) {
100 const User *Operand = dyn_cast<User>(OI);
101 if (!Operand)
102 continue;
Eugene Levianteddf6b52018-10-12 07:24:02 +0000103 if (isa<BlockAddress>(Operand)) {
104 HasBlockAddress = true;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000105 continue;
Eugene Levianteddf6b52018-10-12 07:24:02 +0000106 }
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000107 if (auto *GV = dyn_cast<GlobalValue>(Operand)) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000108 // We have a reference to a global value. This should be added to
109 // the reference set unless it is a callee. Callees are handled
110 // specially by WriteFunction and are added to a separate list.
111 if (!(CS && CS.isCallee(&OI)))
Peter Collingbourne9667b912017-05-04 18:03:25 +0000112 RefEdges.insert(Index.getOrInsertValueInfo(GV));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000113 continue;
114 }
115 Worklist.push_back(Operand);
116 }
117 }
Eugene Levianteddf6b52018-10-12 07:24:02 +0000118 return HasBlockAddress;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000119}
120
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000121static CalleeInfo::HotnessType getHotness(uint64_t ProfileCount,
122 ProfileSummaryInfo *PSI) {
123 if (!PSI)
124 return CalleeInfo::HotnessType::Unknown;
125 if (PSI->isHotCount(ProfileCount))
126 return CalleeInfo::HotnessType::Hot;
127 if (PSI->isColdCount(ProfileCount))
128 return CalleeInfo::HotnessType::Cold;
129 return CalleeInfo::HotnessType::None;
130}
131
Teresa Johnson519465b2017-01-05 14:32:16 +0000132static bool isNonRenamableLocal(const GlobalValue &GV) {
133 return GV.hasSection() && GV.hasLocalLinkage();
134}
135
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000136/// Determine whether this call has all constant integer arguments (excluding
137/// "this") and summarize it to VCalls or ConstVCalls as appropriate.
138static void addVCallToSet(DevirtCallSite Call, GlobalValue::GUID Guid,
139 SetVector<FunctionSummary::VFuncId> &VCalls,
140 SetVector<FunctionSummary::ConstVCall> &ConstVCalls) {
141 std::vector<uint64_t> Args;
142 // Start from the second argument to skip the "this" pointer.
143 for (auto &Arg : make_range(Call.CS.arg_begin() + 1, Call.CS.arg_end())) {
144 auto *CI = dyn_cast<ConstantInt>(Arg);
145 if (!CI || CI->getBitWidth() > 64) {
146 VCalls.insert({Guid, Call.Offset});
147 return;
148 }
149 Args.push_back(CI->getZExtValue());
150 }
151 ConstVCalls.insert({{Guid, Call.Offset}, std::move(Args)});
152}
153
154/// If this intrinsic call requires that we add information to the function
155/// summary, do so via the non-constant reference arguments.
156static void addIntrinsicToSummary(
157 const CallInst *CI, SetVector<GlobalValue::GUID> &TypeTests,
158 SetVector<FunctionSummary::VFuncId> &TypeTestAssumeVCalls,
159 SetVector<FunctionSummary::VFuncId> &TypeCheckedLoadVCalls,
160 SetVector<FunctionSummary::ConstVCall> &TypeTestAssumeConstVCalls,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000161 SetVector<FunctionSummary::ConstVCall> &TypeCheckedLoadConstVCalls,
162 DominatorTree &DT) {
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000163 switch (CI->getCalledFunction()->getIntrinsicID()) {
164 case Intrinsic::type_test: {
165 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(1));
166 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
167 if (!TypeId)
168 break;
169 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
170
171 // Produce a summary from type.test intrinsics. We only summarize type.test
172 // intrinsics that are used other than by an llvm.assume intrinsic.
173 // Intrinsics that are assumed are relevant only to the devirtualization
174 // pass, not the type test lowering pass.
175 bool HasNonAssumeUses = llvm::any_of(CI->uses(), [](const Use &CIU) {
176 auto *AssumeCI = dyn_cast<CallInst>(CIU.getUser());
177 if (!AssumeCI)
178 return true;
179 Function *F = AssumeCI->getCalledFunction();
180 return !F || F->getIntrinsicID() != Intrinsic::assume;
181 });
182 if (HasNonAssumeUses)
183 TypeTests.insert(Guid);
184
185 SmallVector<DevirtCallSite, 4> DevirtCalls;
186 SmallVector<CallInst *, 4> Assumes;
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000187 findDevirtualizableCallsForTypeTest(DevirtCalls, Assumes, CI, DT);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000188 for (auto &Call : DevirtCalls)
189 addVCallToSet(Call, Guid, TypeTestAssumeVCalls,
190 TypeTestAssumeConstVCalls);
191
192 break;
193 }
194
195 case Intrinsic::type_checked_load: {
196 auto *TypeMDVal = cast<MetadataAsValue>(CI->getArgOperand(2));
197 auto *TypeId = dyn_cast<MDString>(TypeMDVal->getMetadata());
198 if (!TypeId)
199 break;
200 GlobalValue::GUID Guid = GlobalValue::getGUID(TypeId->getString());
201
202 SmallVector<DevirtCallSite, 4> DevirtCalls;
203 SmallVector<Instruction *, 4> LoadedPtrs;
204 SmallVector<Instruction *, 4> Preds;
205 bool HasNonCallUses = false;
206 findDevirtualizableCallsForTypeCheckedLoad(DevirtCalls, LoadedPtrs, Preds,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000207 HasNonCallUses, CI, DT);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000208 // Any non-call uses of the result of llvm.type.checked.load will
209 // prevent us from optimizing away the llvm.type.test.
210 if (HasNonCallUses)
211 TypeTests.insert(Guid);
212 for (auto &Call : DevirtCalls)
213 addVCallToSet(Call, Guid, TypeCheckedLoadVCalls,
214 TypeCheckedLoadConstVCalls);
215
216 break;
217 }
218 default:
219 break;
220 }
221}
222
Eugene Leviantbf46e742018-11-16 07:08:00 +0000223static bool isNonVolatileLoad(const Instruction *I) {
224 if (const auto *LI = dyn_cast<LoadInst>(I))
225 return !LI->isVolatile();
226
227 return false;
228}
229
230static void computeFunctionSummary(ModuleSummaryIndex &Index, const Module &M,
231 const Function &F, BlockFrequencyInfo *BFI,
232 ProfileSummaryInfo *PSI, DominatorTree &DT,
233 bool HasLocalsInUsedOrAsm,
234 DenseSet<GlobalValue::GUID> &CantBePromoted,
235 bool IsThinLTO) {
Teresa Johnson02563cd2016-10-28 02:39:38 +0000236 // Summary not currently supported for anonymous functions, they should
237 // have been named.
238 assert(F.hasName());
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000239
240 unsigned NumInsts = 0;
241 // Map from callee ValueId to profile count. Used to accumulate profile
242 // counts for all static calls to a given callee.
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000243 MapVector<ValueInfo, CalleeInfo> CallGraphEdges;
244 SetVector<ValueInfo> RefEdges;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000245 SetVector<GlobalValue::GUID> TypeTests;
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000246 SetVector<FunctionSummary::VFuncId> TypeTestAssumeVCalls,
247 TypeCheckedLoadVCalls;
248 SetVector<FunctionSummary::ConstVCall> TypeTestAssumeConstVCalls,
249 TypeCheckedLoadConstVCalls;
Teresa Johnsoncd21a642016-07-17 14:47:01 +0000250 ICallPromotionAnalysis ICallAnalysis;
Peter Collingbourne681fbb62017-09-07 05:35:35 +0000251 SmallPtrSet<const User *, 8> Visited;
252
253 // Add personality function, prefix data and prologue data to function's ref
254 // list.
255 findRefEdges(Index, &F, RefEdges, Visited);
Eugene Leviantbf46e742018-11-16 07:08:00 +0000256 std::vector<const Instruction *> NonVolatileLoads;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000257
Teresa Johnsond5033a42016-11-14 16:40:19 +0000258 bool HasInlineAsmMaybeReferencingInternal = false;
Teresa Johnson32dc5b92018-11-14 19:30:13 +0000259 bool InitsVarArgs = false;
Benjamin Krameraa209152016-06-26 17:27:42 +0000260 for (const BasicBlock &BB : F)
261 for (const Instruction &I : BB) {
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000262 if (isa<DbgInfoIntrinsic>(I))
263 continue;
Teresa Johnson32dc5b92018-11-14 19:30:13 +0000264 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
265 if (II->getIntrinsicID() == Intrinsic::vastart)
266 InitsVarArgs = true;
267 }
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000268 ++NumInsts;
Eugene Leviantbf46e742018-11-16 07:08:00 +0000269 if (isNonVolatileLoad(&I)) {
270 // Postpone processing of non-volatile load instructions
271 // See comments below
272 Visited.insert(&I);
273 NonVolatileLoads.push_back(&I);
274 continue;
275 }
Peter Collingbourne9667b912017-05-04 18:03:25 +0000276 findRefEdges(Index, &I, RefEdges, Visited);
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000277 auto CS = ImmutableCallSite(&I);
278 if (!CS)
279 continue;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000280
281 const auto *CI = dyn_cast<CallInst>(&I);
282 // Since we don't know exactly which local values are referenced in inline
Teresa Johnsond5033a42016-11-14 16:40:19 +0000283 // assembly, conservatively mark the function as possibly referencing
284 // a local value from inline assembly to ensure we don't export a
285 // reference (which would require renaming and promotion of the
286 // referenced value).
Peter Collingbourne5e8b94c12017-09-01 16:24:02 +0000287 if (HasLocalsInUsedOrAsm && CI && CI->isInlineAsm())
Teresa Johnsond5033a42016-11-14 16:40:19 +0000288 HasInlineAsmMaybeReferencingInternal = true;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000289
Teresa Johnson897bab92016-10-08 16:11:42 +0000290 auto *CalledValue = CS.getCalledValue();
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000291 auto *CalledFunction = CS.getCalledFunction();
Volodymyr Sapsaia7396022017-11-10 00:47:47 +0000292 if (CalledValue && !CalledFunction) {
293 CalledValue = CalledValue->stripPointerCastsNoFollowAliases();
294 // Stripping pointer casts can reveal a called function.
295 CalledFunction = dyn_cast<Function>(CalledValue);
296 }
Teresa Johnson897bab92016-10-08 16:11:42 +0000297 // Check if this is an alias to a function. If so, get the
298 // called aliasee for the checks below.
299 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
300 assert(!CalledFunction && "Expected null called function in callsite for alias");
301 CalledFunction = dyn_cast<Function>(GA->getBaseObject());
302 }
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000303 // Check if this is a direct call to a known function or a known
304 // intrinsic, or an indirect call with profile data.
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000305 if (CalledFunction) {
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000306 if (CI && CalledFunction->isIntrinsic()) {
307 addIntrinsicToSummary(
308 CI, TypeTests, TypeTestAssumeVCalls, TypeCheckedLoadVCalls,
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000309 TypeTestAssumeConstVCalls, TypeCheckedLoadConstVCalls, DT);
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000310 continue;
Peter Collingbourne1b4137a72016-12-21 23:03:45 +0000311 }
Teresa Johnson02563cd2016-10-28 02:39:38 +0000312 // We should have named any anonymous globals
313 assert(CalledFunction->hasName());
Easwaran Ramanf5f91602017-05-09 23:21:10 +0000314 auto ScaledCount = PSI->getProfileCount(&I, BFI);
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000315 auto Hotness = ScaledCount ? getHotness(ScaledCount.getValue(), PSI)
316 : CalleeInfo::HotnessType::Unknown;
Teresa Johnsondb83ace2018-03-31 00:18:08 +0000317 if (ForceSummaryEdgesCold != FunctionSummary::FSHT_None)
318 Hotness = CalleeInfo::HotnessType::Cold;
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000319
Teresa Johnson897bab92016-10-08 16:11:42 +0000320 // Use the original CalledValue, in case it was an alias. We want
321 // to record the call edge to the alias in that case. Eventually
322 // an alias summary will be created to associate the alias and
323 // aliasee.
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000324 auto &ValueInfo = CallGraphEdges[Index.getOrInsertValueInfo(
325 cast<GlobalValue>(CalledValue))];
326 ValueInfo.updateHotness(Hotness);
327 // Add the relative block frequency to CalleeInfo if there is no profile
328 // information.
329 if (BFI != nullptr && Hotness == CalleeInfo::HotnessType::Unknown) {
Easwaran Raman385d8ea2018-02-22 19:44:08 +0000330 uint64_t BBFreq = BFI->getBlockFreq(&BB).getFrequency();
331 uint64_t EntryFreq = BFI->getEntryFreq();
332 ValueInfo.updateRelBlockFreq(BBFreq, EntryFreq);
Easwaran Ramanc73cec82018-01-25 19:27:17 +0000333 }
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000334 } else {
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000335 // Skip inline assembly calls.
336 if (CI && CI->isInlineAsm())
337 continue;
Volodymyr Sapsai8b46ff12017-11-17 18:28:05 +0000338 // Skip direct calls.
339 if (!CalledValue || isa<Constant>(CalledValue))
340 continue;
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000341
Taewook Oh7646e772018-03-13 04:26:58 +0000342 // Check if the instruction has a callees metadata. If so, add callees
343 // to CallGraphEdges to reflect the references from the metadata, and
344 // to enable importing for subsequent indirect call promotion and
345 // inlining.
346 if (auto *MD = I.getMetadata(LLVMContext::MD_callees)) {
347 for (auto &Op : MD->operands()) {
348 Function *Callee = mdconst::extract_or_null<Function>(Op);
349 if (Callee)
350 CallGraphEdges[Index.getOrInsertValueInfo(Callee)];
351 }
352 }
353
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000354 uint32_t NumVals, NumCandidates;
355 uint64_t TotalCount;
356 auto CandidateProfileData =
357 ICallAnalysis.getPromotionCandidatesForInstruction(
358 &I, NumVals, TotalCount, NumCandidates);
359 for (auto &Candidate : CandidateProfileData)
Peter Collingbourne9667b912017-05-04 18:03:25 +0000360 CallGraphEdges[Index.getOrInsertValueInfo(Candidate.Value)]
361 .updateHotness(getHotness(Candidate.Count, PSI));
Piotr Padlewski442d38c2016-08-30 00:46:26 +0000362 }
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000363 }
364
Eugene Leviantbf46e742018-11-16 07:08:00 +0000365 // By now we processed all instructions in a function, except
366 // non-volatile loads. All new refs we add in a loop below
367 // are obviously constant. All constant refs are grouped in the
368 // end of RefEdges vector, so we can use a single integer value
369 // to identify them.
370 unsigned RefCnt = RefEdges.size();
371 for (const Instruction *I : NonVolatileLoads) {
372 Visited.erase(I);
373 findRefEdges(Index, I, RefEdges, Visited);
374 }
375 std::vector<ValueInfo> Refs = RefEdges.takeVector();
376 // Regular LTO module doesn't participate in ThinLTO import,
377 // so no reference from it can be readonly, since this would
378 // require importing variable as local copy
379 if (IsThinLTO)
380 for (; RefCnt < Refs.size(); ++RefCnt)
381 Refs[RefCnt].setReadOnly();
382
Dehao Chena60cdd32017-02-28 18:09:44 +0000383 // Explicit add hot edges to enforce importing for designated GUIDs for
384 // sample PGO, to enable the same inlines as the profiled optimized binary.
385 for (auto &I : F.getImportGUIDs())
Peter Collingbourne9667b912017-05-04 18:03:25 +0000386 CallGraphEdges[Index.getOrInsertValueInfo(I)].updateHotness(
Teresa Johnsondb83ace2018-03-31 00:18:08 +0000387 ForceSummaryEdgesCold == FunctionSummary::FSHT_All
388 ? CalleeInfo::HotnessType::Cold
389 : CalleeInfo::HotnessType::Critical);
Dehao Chena60cdd32017-02-28 18:09:44 +0000390
Teresa Johnson519465b2017-01-05 14:32:16 +0000391 bool NonRenamableLocal = isNonRenamableLocal(F);
392 bool NotEligibleForImport =
Teresa Johnsoncb397462018-11-06 19:41:35 +0000393 NonRenamableLocal || HasInlineAsmMaybeReferencingInternal;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000394 GlobalValueSummary::GVFlags Flags(F.getLinkage(), NotEligibleForImport,
Sean Fertile4595a912017-11-04 17:04:39 +0000395 /* Live = */ false, F.isDSOLocal());
Charles Saternos75da10d2017-08-04 16:00:58 +0000396 FunctionSummary::FFlags FunFlags{
397 F.hasFnAttribute(Attribute::ReadNone),
398 F.hasFnAttribute(Attribute::ReadOnly),
Teresa Johnsoncb397462018-11-06 19:41:35 +0000399 F.hasFnAttribute(Attribute::NoRecurse), F.returnDoesNotAlias(),
Teresa Johnson32dc5b92018-11-14 19:30:13 +0000400 // Inliner doesn't handle variadic functions with va_start calls.
Teresa Johnsoncb397462018-11-06 19:41:35 +0000401 // FIXME: refactor this to use the same code that inliner is using.
Teresa Johnson32dc5b92018-11-14 19:30:13 +0000402 InitsVarArgs ||
Teresa Johnsoncb397462018-11-06 19:41:35 +0000403 // Don't try to import functions with noinline attribute.
404 F.getAttributes().hasFnAttribute(Attribute::NoInline)};
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000405 auto FuncSummary = llvm::make_unique<FunctionSummary>(
Eugene Leviantbf46e742018-11-16 07:08:00 +0000406 Flags, NumInsts, FunFlags, std::move(Refs), CallGraphEdges.takeVector(),
407 TypeTests.takeVector(), TypeTestAssumeVCalls.takeVector(),
408 TypeCheckedLoadVCalls.takeVector(),
Peter Collingbournebe9ffaa2017-02-10 22:29:38 +0000409 TypeTestAssumeConstVCalls.takeVector(),
410 TypeCheckedLoadConstVCalls.takeVector());
Teresa Johnson519465b2017-01-05 14:32:16 +0000411 if (NonRenamableLocal)
412 CantBePromoted.insert(F.getGUID());
Teresa Johnson7bea1aa2018-06-26 00:20:49 +0000413 Index.addGlobalValueSummary(F, std::move(FuncSummary));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000414}
415
Teresa Johnson519465b2017-01-05 14:32:16 +0000416static void
417computeVariableSummary(ModuleSummaryIndex &Index, const GlobalVariable &V,
Teresa Johnsone27b0582017-01-05 14:59:56 +0000418 DenseSet<GlobalValue::GUID> &CantBePromoted) {
Peter Collingbourne0c30f082016-12-20 21:12:28 +0000419 SetVector<ValueInfo> RefEdges;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000420 SmallPtrSet<const User *, 8> Visited;
Eugene Levianteddf6b52018-10-12 07:24:02 +0000421 bool HasBlockAddress = findRefEdges(Index, &V, RefEdges, Visited);
Teresa Johnson519465b2017-01-05 14:32:16 +0000422 bool NonRenamableLocal = isNonRenamableLocal(V);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000423 GlobalValueSummary::GVFlags Flags(V.getLinkage(), NonRenamableLocal,
Sean Fertile4595a912017-11-04 17:04:39 +0000424 /* Live = */ false, V.isDSOLocal());
Eugene Leviantbf46e742018-11-16 07:08:00 +0000425
426 // Don't mark variables we won't be able to internalize as read-only.
427 GlobalVarSummary::GVarFlags VarFlags(
428 !V.hasComdat() && !V.hasAppendingLinkage() && !V.isInterposable() &&
429 !V.hasAvailableExternallyLinkage() && !V.hasDLLExportStorageClass());
430 auto GVarSummary = llvm::make_unique<GlobalVarSummary>(Flags, VarFlags,
431 RefEdges.takeVector());
Teresa Johnson519465b2017-01-05 14:32:16 +0000432 if (NonRenamableLocal)
433 CantBePromoted.insert(V.getGUID());
Eugene Levianteddf6b52018-10-12 07:24:02 +0000434 if (HasBlockAddress)
435 GVarSummary->setNotEligibleToImport();
Teresa Johnson7bea1aa2018-06-26 00:20:49 +0000436 Index.addGlobalValueSummary(V, std::move(GVarSummary));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000437}
438
Teresa Johnson519465b2017-01-05 14:32:16 +0000439static void
440computeAliasSummary(ModuleSummaryIndex &Index, const GlobalAlias &A,
Teresa Johnsone27b0582017-01-05 14:59:56 +0000441 DenseSet<GlobalValue::GUID> &CantBePromoted) {
Teresa Johnson519465b2017-01-05 14:32:16 +0000442 bool NonRenamableLocal = isNonRenamableLocal(A);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000443 GlobalValueSummary::GVFlags Flags(A.getLinkage(), NonRenamableLocal,
Sean Fertile4595a912017-11-04 17:04:39 +0000444 /* Live = */ false, A.isDSOLocal());
Teresa Johnsoncbdc5ff2017-09-13 17:10:24 +0000445 auto AS = llvm::make_unique<AliasSummary>(Flags);
Teresa Johnson02563cd2016-10-28 02:39:38 +0000446 auto *Aliasee = A.getBaseObject();
447 auto *AliaseeSummary = Index.getGlobalValueSummary(*Aliasee);
448 assert(AliaseeSummary && "Alias expects aliasee summary to be parsed");
449 AS->setAliasee(AliaseeSummary);
Teresa Johnson519465b2017-01-05 14:32:16 +0000450 if (NonRenamableLocal)
451 CantBePromoted.insert(A.getGUID());
Teresa Johnson7bea1aa2018-06-26 00:20:49 +0000452 Index.addGlobalValueSummary(A, std::move(AS));
Teresa Johnson02563cd2016-10-28 02:39:38 +0000453}
454
Teresa Johnson6c475a72017-01-05 21:34:18 +0000455// Set LiveRoot flag on entries matching the given value name.
456static void setLiveRoot(ModuleSummaryIndex &Index, StringRef Name) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000457 if (ValueInfo VI = Index.getValueInfo(GlobalValue::getGUID(Name)))
458 for (auto &Summary : VI.getSummaryList())
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000459 Summary->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000460}
461
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000462ModuleSummaryIndex llvm::buildModuleSummaryIndex(
463 const Module &M,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000464 std::function<BlockFrequencyInfo *(const Function &F)> GetBFICallback,
465 ProfileSummaryInfo *PSI) {
Teresa Johnson94624ac2017-05-10 18:52:16 +0000466 assert(PSI);
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000467 ModuleSummaryIndex Index(/*HaveGVs=*/true);
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000468
Teresa Johnsona0811452016-11-10 16:57:32 +0000469 // Identify the local values in the llvm.used and llvm.compiler.used sets,
470 // which should not be exported as they would then require renaming and
471 // promotion, but we may have opaque uses e.g. in inline asm. We collect them
472 // here because we use this information to mark functions containing inline
473 // assembly calls as not importable.
Mehdi Aminib6a11a72016-11-09 01:45:13 +0000474 SmallPtrSet<GlobalValue *, 8> LocalsUsed;
Teresa Johnsona0811452016-11-10 16:57:32 +0000475 SmallPtrSet<GlobalValue *, 8> Used;
476 // First collect those in the llvm.used set.
477 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
Teresa Johnsona0811452016-11-10 16:57:32 +0000478 // Next collect those in the llvm.compiler.used set.
479 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ true);
Teresa Johnsone27b0582017-01-05 14:59:56 +0000480 DenseSet<GlobalValue::GUID> CantBePromoted;
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000481 for (auto *V : Used) {
Teresa Johnson519465b2017-01-05 14:32:16 +0000482 if (V->hasLocalLinkage()) {
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000483 LocalsUsed.insert(V);
Teresa Johnson519465b2017-01-05 14:32:16 +0000484 CantBePromoted.insert(V->getGUID());
485 }
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000486 }
Teresa Johnsonb35cc692016-04-20 14:39:45 +0000487
Peter Collingbourne5e8b94c12017-09-01 16:24:02 +0000488 bool HasLocalInlineAsmSymbol = false;
489 if (!M.getModuleInlineAsm().empty()) {
490 // Collect the local values defined by module level asm, and set up
491 // summaries for these symbols so that they can be marked as NoRename,
492 // to prevent export of any use of them in regular IR that would require
493 // renaming within the module level asm. Note we don't need to create a
494 // summary for weak or global defs, as they don't need to be flagged as
495 // NoRename, and defs in module level asm can't be imported anyway.
496 // Also, any values used but not defined within module level asm should
497 // be listed on the llvm.used or llvm.compiler.used global and marked as
498 // referenced from there.
499 ModuleSymbolTable::CollectAsmSymbols(
500 M, [&](StringRef Name, object::BasicSymbolRef::Flags Flags) {
501 // Symbols not marked as Weak or Global are local definitions.
502 if (Flags & (object::BasicSymbolRef::SF_Weak |
503 object::BasicSymbolRef::SF_Global))
504 return;
505 HasLocalInlineAsmSymbol = true;
506 GlobalValue *GV = M.getNamedValue(Name);
507 if (!GV)
508 return;
509 assert(GV->isDeclaration() && "Def in module asm already has definition");
510 GlobalValueSummary::GVFlags GVFlags(GlobalValue::InternalLinkage,
511 /* NotEligibleToImport = */ true,
Sean Fertile4595a912017-11-04 17:04:39 +0000512 /* Live = */ true,
513 /* Local */ GV->isDSOLocal());
Teresa Johnson7bea1aa2018-06-26 00:20:49 +0000514 CantBePromoted.insert(GV->getGUID());
Peter Collingbourne5e8b94c12017-09-01 16:24:02 +0000515 // Create the appropriate summary type.
516 if (Function *F = dyn_cast<Function>(GV)) {
517 std::unique_ptr<FunctionSummary> Summary =
518 llvm::make_unique<FunctionSummary>(
519 GVFlags, 0,
520 FunctionSummary::FFlags{
521 F->hasFnAttribute(Attribute::ReadNone),
522 F->hasFnAttribute(Attribute::ReadOnly),
523 F->hasFnAttribute(Attribute::NoRecurse),
Teresa Johnsoncb397462018-11-06 19:41:35 +0000524 F->returnDoesNotAlias(),
525 /* NoInline = */ false},
Peter Collingbourne5e8b94c12017-09-01 16:24:02 +0000526 ArrayRef<ValueInfo>{}, ArrayRef<FunctionSummary::EdgeTy>{},
527 ArrayRef<GlobalValue::GUID>{},
528 ArrayRef<FunctionSummary::VFuncId>{},
529 ArrayRef<FunctionSummary::VFuncId>{},
530 ArrayRef<FunctionSummary::ConstVCall>{},
531 ArrayRef<FunctionSummary::ConstVCall>{});
Teresa Johnson7bea1aa2018-06-26 00:20:49 +0000532 Index.addGlobalValueSummary(*GV, std::move(Summary));
Peter Collingbourne5e8b94c12017-09-01 16:24:02 +0000533 } else {
534 std::unique_ptr<GlobalVarSummary> Summary =
Eugene Leviantbf46e742018-11-16 07:08:00 +0000535 llvm::make_unique<GlobalVarSummary>(
536 GVFlags, GlobalVarSummary::GVarFlags(),
537 ArrayRef<ValueInfo>{});
Teresa Johnson7bea1aa2018-06-26 00:20:49 +0000538 Index.addGlobalValueSummary(*GV, std::move(Summary));
Peter Collingbourne5e8b94c12017-09-01 16:24:02 +0000539 }
540 });
541 }
542
Eugene Leviantbf46e742018-11-16 07:08:00 +0000543 bool IsThinLTO = true;
544 if (auto *MD =
545 mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
546 IsThinLTO = MD->getZExtValue();
547
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000548 // Compute summaries for all functions defined in module, and save in the
549 // index.
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000550 for (auto &F : M) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000551 if (F.isDeclaration())
552 continue;
553
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000554 DominatorTree DT(const_cast<Function &>(F));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000555 BlockFrequencyInfo *BFI = nullptr;
556 std::unique_ptr<BlockFrequencyInfo> BFIPtr;
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000557 if (GetBFICallback)
558 BFI = GetBFICallback(F);
Easwaran Ramana17f2202017-12-22 01:33:52 +0000559 else if (F.hasProfileData()) {
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000560 LoopInfo LI{DT};
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000561 BranchProbabilityInfo BPI{F, LI};
562 BFIPtr = llvm::make_unique<BlockFrequencyInfo>(F, BPI, LI);
563 BFI = BFIPtr.get();
564 }
565
Teresa Johnsonf24136f2018-09-27 14:55:32 +0000566 computeFunctionSummary(Index, M, F, BFI, PSI, DT,
Peter Collingbourne5e8b94c12017-09-01 16:24:02 +0000567 !LocalsUsed.empty() || HasLocalInlineAsmSymbol,
Eugene Leviantbf46e742018-11-16 07:08:00 +0000568 CantBePromoted, IsThinLTO);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000569 }
570
571 // Compute summaries for all variables defined in module, and save in the
572 // index.
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000573 for (const GlobalVariable &G : M.globals()) {
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000574 if (G.isDeclaration())
575 continue;
Teresa Johnson519465b2017-01-05 14:32:16 +0000576 computeVariableSummary(Index, G, CantBePromoted);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000577 }
Teresa Johnson02563cd2016-10-28 02:39:38 +0000578
579 // Compute summaries for all aliases defined in module, and save in the
580 // index.
581 for (const GlobalAlias &A : M.aliases())
Teresa Johnson519465b2017-01-05 14:32:16 +0000582 computeAliasSummary(Index, A, CantBePromoted);
Teresa Johnson02563cd2016-10-28 02:39:38 +0000583
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000584 for (auto *V : LocalsUsed) {
585 auto *Summary = Index.getGlobalValueSummary(*V);
586 assert(Summary && "Missing summary for global value");
Teresa Johnson519465b2017-01-05 14:32:16 +0000587 Summary->setNotEligibleToImport();
Teresa Johnsonbf28c8f2016-10-30 05:40:44 +0000588 }
589
Teresa Johnson6c475a72017-01-05 21:34:18 +0000590 // The linker doesn't know about these LLVM produced values, so we need
591 // to flag them as live in the index to ensure index-based dead value
592 // analysis treats them as live roots of the analysis.
593 setLiveRoot(Index, "llvm.used");
594 setLiveRoot(Index, "llvm.compiler.used");
595 setLiveRoot(Index, "llvm.global_ctors");
596 setLiveRoot(Index, "llvm.global_dtors");
597 setLiveRoot(Index, "llvm.global.annotations");
598
Teresa Johnson519465b2017-01-05 14:32:16 +0000599 for (auto &GlobalList : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000600 // Ignore entries for references that are undefined in the current module.
601 if (GlobalList.second.SummaryList.empty())
602 continue;
603
604 assert(GlobalList.second.SummaryList.size() == 1 &&
Teresa Johnson519465b2017-01-05 14:32:16 +0000605 "Expected module's index to have one summary per GUID");
Peter Collingbourne9667b912017-05-04 18:03:25 +0000606 auto &Summary = GlobalList.second.SummaryList[0];
Peter Collingbournee357fbd2017-06-08 23:01:49 +0000607 if (!IsThinLTO) {
608 Summary->setNotEligibleToImport();
609 continue;
610 }
611
Teresa Johnson519465b2017-01-05 14:32:16 +0000612 bool AllRefsCanBeExternallyReferenced =
613 llvm::all_of(Summary->refs(), [&](const ValueInfo &VI) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000614 return !CantBePromoted.count(VI.getGUID());
Teresa Johnson519465b2017-01-05 14:32:16 +0000615 });
616 if (!AllRefsCanBeExternallyReferenced) {
617 Summary->setNotEligibleToImport();
618 continue;
619 }
620
621 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
622 bool AllCallsCanBeExternallyReferenced = llvm::all_of(
623 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000624 return !CantBePromoted.count(Edge.first.getGUID());
Teresa Johnson519465b2017-01-05 14:32:16 +0000625 });
626 if (!AllCallsCanBeExternallyReferenced)
627 Summary->setNotEligibleToImport();
628 }
629 }
630
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000631 return Index;
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000632}
633
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000634AnalysisKey ModuleSummaryIndexAnalysis::Key;
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000635
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000636ModuleSummaryIndex
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000637ModuleSummaryIndexAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000638 ProfileSummaryInfo &PSI = AM.getResult<ProfileSummaryAnalysis>(M);
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000639 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000640 return buildModuleSummaryIndex(
641 M,
642 [&FAM](const Function &F) {
643 return &FAM.getResult<BlockFrequencyAnalysis>(
644 *const_cast<Function *>(&F));
645 },
646 &PSI);
Teresa Johnsonf93b2462016-08-12 13:53:02 +0000647}
648
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000649char ModuleSummaryIndexWrapperPass::ID = 0;
Eugene Zelenkobb1b2d02017-08-16 22:07:40 +0000650
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000651INITIALIZE_PASS_BEGIN(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
652 "Module Summary Analysis", false, true)
653INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
Mehdi Amini89029482017-01-21 06:01:22 +0000654INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000655INITIALIZE_PASS_END(ModuleSummaryIndexWrapperPass, "module-summary-analysis",
656 "Module Summary Analysis", false, true)
657
658ModulePass *llvm::createModuleSummaryIndexWrapperPass() {
659 return new ModuleSummaryIndexWrapperPass();
660}
661
662ModuleSummaryIndexWrapperPass::ModuleSummaryIndexWrapperPass()
663 : ModulePass(ID) {
664 initializeModuleSummaryIndexWrapperPassPass(*PassRegistry::getPassRegistry());
665}
666
667bool ModuleSummaryIndexWrapperPass::runOnModule(Module &M) {
Dehao Chen5461d8b2016-09-28 21:00:58 +0000668 auto &PSI = *getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Teresa Johnson51905532018-06-26 02:29:08 +0000669 Index.emplace(buildModuleSummaryIndex(
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000670 M,
671 [this](const Function &F) {
672 return &(this->getAnalysis<BlockFrequencyInfoWrapperPass>(
673 *const_cast<Function *>(&F))
674 .getBFI());
675 },
Teresa Johnson51905532018-06-26 02:29:08 +0000676 &PSI));
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000677 return false;
678}
679
680bool ModuleSummaryIndexWrapperPass::doFinalization(Module &M) {
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000681 Index.reset();
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000682 return false;
683}
684
685void ModuleSummaryIndexWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
686 AU.setPreservesAll();
687 AU.addRequired<BlockFrequencyInfoWrapperPass>();
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000688 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000689}