blob: 74acd9e5e207fb0311101db8e5b8d407f09c49cb [file] [log] [blame]
Justin Bognerf8d79192014-03-21 17:24:48 +00001//=-- InstrProf.cpp - Instrumented profiling format support -----------------=//
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 file contains support for clang's instrumentation based PGO and
11// coverage.
12//
13//===----------------------------------------------------------------------===//
14
Xinliang David Lie413f1a2015-12-31 07:57:16 +000015#include "llvm/ProfileData/InstrProf.h"
Xinliang David Li0c677872016-01-04 21:31:09 +000016#include "llvm/ADT/StringExtras.h"
Rong Xu97b68c52016-07-21 20:50:02 +000017#include "llvm/ADT/Triple.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000018#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000020#include "llvm/IR/GlobalVariable.h"
Xinliang David Li402477d2016-02-04 19:11:43 +000021#include "llvm/IR/MDBuilder.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000022#include "llvm/IR/Module.h"
23#include "llvm/Support/Compression.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000024#include "llvm/Support/ErrorHandling.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000025#include "llvm/Support/LEB128.h"
Chris Bieneman1efe8012014-09-19 23:19:24 +000026#include "llvm/Support/ManagedStatic.h"
Xinliang David Li9eb472b2016-07-12 17:14:51 +000027#include "llvm/Support/Path.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000028
29using namespace llvm;
30
Xinliang David Li9eb472b2016-07-12 17:14:51 +000031static cl::opt<bool> StaticFuncFullModulePrefix(
32 "static-func-full-module-prefix", cl::init(false),
33 cl::desc("Use full module build paths in the profile counter names for "
34 "static functions."));
35
Justin Bognerf8d79192014-03-21 17:24:48 +000036namespace {
Vedant Kumar9152fd12016-05-19 03:54:45 +000037std::string getInstrProfErrString(instrprof_error Err) {
38 switch (Err) {
39 case instrprof_error::success:
40 return "Success";
41 case instrprof_error::eof:
42 return "End of File";
43 case instrprof_error::unrecognized_format:
44 return "Unrecognized instrumentation profile encoding format";
45 case instrprof_error::bad_magic:
46 return "Invalid instrumentation profile data (bad magic)";
47 case instrprof_error::bad_header:
48 return "Invalid instrumentation profile data (file header is corrupt)";
49 case instrprof_error::unsupported_version:
50 return "Unsupported instrumentation profile format version";
51 case instrprof_error::unsupported_hash_type:
52 return "Unsupported instrumentation profile hash type";
53 case instrprof_error::too_large:
54 return "Too much profile data";
55 case instrprof_error::truncated:
56 return "Truncated profile data";
57 case instrprof_error::malformed:
58 return "Malformed instrumentation profile data";
59 case instrprof_error::unknown_function:
60 return "No profile data available for function";
61 case instrprof_error::hash_mismatch:
62 return "Function control flow change detected (hash mismatch)";
63 case instrprof_error::count_mismatch:
64 return "Function basic block count change detected (counter mismatch)";
65 case instrprof_error::counter_overflow:
66 return "Counter overflow";
67 case instrprof_error::value_site_count_mismatch:
68 return "Function value site count change detected (counter mismatch)";
69 case instrprof_error::compress_failed:
70 return "Failed to compress data (zlib)";
71 case instrprof_error::uncompress_failed:
72 return "Failed to uncompress data (zlib)";
Rong Xu2c684cf2016-10-19 22:51:17 +000073 case instrprof_error::empty_raw_profile:
74 return "Empty raw profile file";
Vedant Kumar9152fd12016-05-19 03:54:45 +000075 }
76 llvm_unreachable("A value of instrprof_error has no message.");
77}
78
Peter Collingbourne4718f8b2016-05-24 20:13:46 +000079// FIXME: This class is only here to support the transition to llvm::Error. It
80// will be removed once this transition is complete. Clients should prefer to
81// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +000082class InstrProfErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +000083 const char *name() const noexcept override { return "llvm.instrprof"; }
Justin Bognerf8d79192014-03-21 17:24:48 +000084 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +000085 return getInstrProfErrString(static_cast<instrprof_error>(IE));
Justin Bognerf8d79192014-03-21 17:24:48 +000086 }
Justin Bognerf8d79192014-03-21 17:24:48 +000087};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000088} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +000089
Chris Bieneman1efe8012014-09-19 23:19:24 +000090static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
91
Rafael Espindola25188c92014-06-12 01:45:43 +000092const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +000093 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +000094}
Xinliang David Li441959d2015-11-09 00:01:22 +000095
96namespace llvm {
97
Vedant Kumar42369db2016-05-11 19:42:19 +000098void SoftInstrProfErrors::addError(instrprof_error IE) {
99 if (IE == instrprof_error::success)
100 return;
101
102 if (FirstError == instrprof_error::success)
103 FirstError = IE;
104
105 switch (IE) {
106 case instrprof_error::hash_mismatch:
107 ++NumHashMismatches;
108 break;
109 case instrprof_error::count_mismatch:
110 ++NumCountMismatches;
111 break;
112 case instrprof_error::counter_overflow:
113 ++NumCounterOverflows;
114 break;
115 case instrprof_error::value_site_count_mismatch:
116 ++NumValueSiteCountMismatches;
117 break;
118 default:
119 llvm_unreachable("Not a soft error");
120 }
121}
122
Vedant Kumar9152fd12016-05-19 03:54:45 +0000123std::string InstrProfError::message() const {
124 return getInstrProfErrString(Err);
125}
126
127char InstrProfError::ID = 0;
128
Xinliang David Li441959d2015-11-09 00:01:22 +0000129std::string getPGOFuncName(StringRef RawFuncName,
130 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +0000131 StringRef FileName,
132 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +0000133 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000134}
135
Rong Xub5341662016-03-30 18:37:52 +0000136// Return the PGOFuncName. This function has some special handling when called
137// in LTO optimization. The following only applies when calling in LTO passes
138// (when \c InLTO is true): LTO's internalization privatizes many global linkage
139// symbols. This happens after value profile annotation, but those internal
140// linkage functions should not have a source prefix.
Teresa Johnson8c1bc982016-08-29 22:46:56 +0000141// Additionally, for ThinLTO mode, exported internal functions are promoted
142// and renamed. We need to ensure that the original internal PGO name is
143// used when computing the GUID that is compared against the profiled GUIDs.
Rong Xub5341662016-03-30 18:37:52 +0000144// To differentiate compiler generated internal symbols from original ones,
145// PGOFuncName meta data are created and attached to the original internal
146// symbols in the value profile annotation step
147// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
148// data, its original linkage must be non-internal.
149std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000150 if (!InLTO) {
151 StringRef FileName = (StaticFuncFullModulePrefix
152 ? F.getParent()->getName()
153 : sys::path::filename(F.getParent()->getName()));
154 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
155 }
Rong Xub5341662016-03-30 18:37:52 +0000156
Rong Xu8e8fe852016-04-01 16:43:30 +0000157 // In LTO mode (when InLTO is true), first check if there is a meta data.
158 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000159 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
160 return S.str();
161 }
162
163 // If there is no meta data, the function must be a global before the value
164 // profile annotation pass. Its current linkage may be internal if it is
165 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000166 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000167}
168
Xinliang David Li4ec40142015-12-15 19:44:45 +0000169StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
170 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000171 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000172 // Drop the file name including ':'. See also getPGOFuncName.
173 if (PGOFuncName.startswith(FileName))
174 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
175 return PGOFuncName;
176}
177
Xinliang David Lid1bab962015-12-12 17:28:03 +0000178// \p FuncName is the string used as profile lookup key for the function. A
179// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000180std::string getPGOFuncNameVarName(StringRef FuncName,
181 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000182 std::string VarName = getInstrProfNameVarPrefix();
183 VarName += FuncName;
184
185 if (!GlobalValue::isLocalLinkage(Linkage))
186 return VarName;
187
188 // Now fix up illegal chars in local VarName that may upset the assembler.
Xinliang David Lieeaf0bc2016-06-10 06:32:26 +0000189 const char *InvalidChars = "-:<>/\"'";
Xinliang David Lid1bab962015-12-12 17:28:03 +0000190 size_t found = VarName.find_first_of(InvalidChars);
191 while (found != std::string::npos) {
192 VarName[found] = '_';
193 found = VarName.find_first_of(InvalidChars, found + 1);
194 }
195 return VarName;
196}
197
Xinliang David Li441959d2015-11-09 00:01:22 +0000198GlobalVariable *createPGOFuncNameVar(Module &M,
199 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000200 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000201
202 // We generally want to match the function's linkage, but available_externally
203 // and extern_weak both have the wrong semantics, and anything that doesn't
204 // need to link across compilation units doesn't need to be visible at all.
205 if (Linkage == GlobalValue::ExternalWeakLinkage)
206 Linkage = GlobalValue::LinkOnceAnyLinkage;
207 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
208 Linkage = GlobalValue::LinkOnceODRLinkage;
209 else if (Linkage == GlobalValue::InternalLinkage ||
210 Linkage == GlobalValue::ExternalLinkage)
211 Linkage = GlobalValue::PrivateLinkage;
212
Xinliang David Li897d2922016-03-16 22:13:41 +0000213 auto *Value =
214 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000215 auto FuncNameVar =
216 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000217 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000218
219 // Hide the symbol so that we correctly get a copy for each executable.
220 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
221 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
222
223 return FuncNameVar;
224}
225
Xinliang David Li897d2922016-03-16 22:13:41 +0000226GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
227 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000228}
Xinliang David Liee415892015-11-10 00:24:45 +0000229
Rong Xub5341662016-03-30 18:37:52 +0000230void InstrProfSymtab::create(Module &M, bool InLTO) {
231 for (Function &F : M) {
232 // Function may not have a name: like using asm("") to overwrite the name.
233 // Ignore in this case.
234 if (!F.hasName())
235 continue;
236 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
237 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000238 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Rong Xub5341662016-03-30 18:37:52 +0000239 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000240
241 finalizeSymtab();
242}
243
Vedant Kumar9152fd12016-05-19 03:54:45 +0000244Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
245 bool doCompression, std::string &Result) {
Vedant Kumar86705ba2016-03-28 21:06:42 +0000246 assert(NameStrs.size() && "No name data to emit");
247
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000248 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000249 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000250 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
251
252 assert(StringRef(UncompressedNameStrings)
253 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
254 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000255
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000256 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
257 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000258
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000259 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000260 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000261 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000262 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
263 unsigned HeaderLen = P - &Header[0];
264 Result.append(HeaderStr, HeaderLen);
265 Result += InputStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000266 return Error::success();
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000267 };
268
Vedant Kumar9152fd12016-05-19 03:54:45 +0000269 if (!doCompression) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000270 return WriteStringToResult(0, UncompressedNameStrings);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000271 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000272
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000273 SmallString<128> CompressedNameStrings;
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000274 zlib::Status Success =
275 zlib::compress(StringRef(UncompressedNameStrings), CompressedNameStrings,
276 zlib::BestSizeCompression);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000277
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000278 if (Success != zlib::StatusOK)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000279 return make_error<InstrProfError>(instrprof_error::compress_failed);
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000280
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000281 return WriteStringToResult(CompressedNameStrings.size(),
282 CompressedNameStrings);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000283}
284
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000285StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000286 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
287 StringRef NameStr =
288 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
289 return NameStr;
290}
291
Vedant Kumar9152fd12016-05-19 03:54:45 +0000292Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
293 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000294 std::vector<std::string> NameStrs;
295 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000296 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000297 }
Xinliang David Li73163752016-01-26 23:13:00 +0000298 return collectPGOFuncNameStrings(
299 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000300}
301
Vedant Kumar9152fd12016-05-19 03:54:45 +0000302Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000303 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
304 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
305 NameStrings.size());
306 while (P < EndP) {
307 uint32_t N;
308 uint64_t UncompressedSize = decodeULEB128(P, &N);
309 P += N;
310 uint64_t CompressedSize = decodeULEB128(P, &N);
311 P += N;
312 bool isCompressed = (CompressedSize != 0);
313 SmallString<128> UncompressedNameStrings;
314 StringRef NameStrings;
315 if (isCompressed) {
316 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
317 CompressedSize);
318 if (zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
319 UncompressedSize) != zlib::StatusOK)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000320 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000321 P += CompressedSize;
322 NameStrings = StringRef(UncompressedNameStrings.data(),
323 UncompressedNameStrings.size());
324 } else {
325 NameStrings =
326 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
327 P += UncompressedSize;
328 }
329 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000330 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000331 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000332 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000333 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000334
335 while (P < EndP && *P == 0)
336 P++;
337 }
338 Symtab.finalizeSymtab();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000339 return Error::success();
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000340}
341
Vedant Kumar42369db2016-05-11 19:42:19 +0000342void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
343 InstrProfValueSiteRecord &Input,
344 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000345 this->sortByTargetValues();
346 Input.sortByTargetValues();
347 auto I = ValueData.begin();
348 auto IE = ValueData.end();
Xinliang David Li5c24da52015-12-20 05:15:45 +0000349 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
350 ++J) {
351 while (I != IE && I->Value < J->Value)
352 ++I;
353 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000354 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000355 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000356 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000357 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000358 ++I;
359 continue;
360 }
361 ValueData.insert(I, *J);
362 }
Xinliang David Li5c24da52015-12-20 05:15:45 +0000363}
364
Vedant Kumar42369db2016-05-11 19:42:19 +0000365void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
366 uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000367 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
368 bool Overflowed;
369 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
370 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000371 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000372 }
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000373}
374
Xinliang David Li020f22d2015-12-18 23:06:37 +0000375// Merge Value Profile data from Src record to this record for ValueKind.
376// Scale merged value counts by \p Weight.
Vedant Kumar42369db2016-05-11 19:42:19 +0000377void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
378 InstrProfRecord &Src,
379 uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000380 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
381 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
Vedant Kumar42369db2016-05-11 19:42:19 +0000382 if (ThisNumValueSites != OtherNumValueSites) {
383 SIPE.addError(instrprof_error::value_site_count_mismatch);
384 return;
385 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000386 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
387 getValueSitesForKind(ValueKind);
388 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
389 Src.getValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000390 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000391 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000392}
393
Vedant Kumar42369db2016-05-11 19:42:19 +0000394void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000395 // If the number of counters doesn't match we either have bad data
396 // or a hash collision.
Vedant Kumar42369db2016-05-11 19:42:19 +0000397 if (Counts.size() != Other.Counts.size()) {
398 SIPE.addError(instrprof_error::count_mismatch);
399 return;
400 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000401
402 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
403 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000404 Counts[I] =
405 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000406 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000407 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000408 }
409
410 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000411 mergeValueProfData(Kind, Other, Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000412}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000413
Vedant Kumar42369db2016-05-11 19:42:19 +0000414void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000415 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
416 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
417 getValueSitesForKind(ValueKind);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000418 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000419 ThisSiteRecords[I].scale(SIPE, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000420}
421
Vedant Kumar42369db2016-05-11 19:42:19 +0000422void InstrProfRecord::scale(uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000423 for (auto &Count : this->Counts) {
424 bool Overflowed;
425 Count = SaturatingMultiply(Count, Weight, &Overflowed);
Vedant Kumar42369db2016-05-11 19:42:19 +0000426 if (Overflowed)
427 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000428 }
429 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000430 scaleValueProfData(Kind, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000431}
432
Xinliang David Li020f22d2015-12-18 23:06:37 +0000433// Map indirect call target name hash to name string.
434uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000435 ValueMapType *ValueMap) {
436 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000437 return Value;
438 switch (ValueKind) {
439 case IPVK_IndirectCallTarget: {
440 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000441 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
442 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000443 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000444 // Raw function pointer collected by value profiler may be from
445 // external functions that are not instrumented. They won't have
446 // mapping data to be used by the deserializer. Force the value to
447 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000448 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000449 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000450 else
451 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000452 break;
453 }
454 }
455 return Value;
456}
457
Xinliang David Li020f22d2015-12-18 23:06:37 +0000458void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
459 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000460 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000461 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000462 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000463 }
464 std::vector<InstrProfValueSiteRecord> &ValueSites =
465 getValueSitesForKind(ValueKind);
466 if (N == 0)
Vedant Kumar6b22ba62016-05-11 16:03:02 +0000467 ValueSites.emplace_back();
Xinliang David Li020f22d2015-12-18 23:06:37 +0000468 else
469 ValueSites.emplace_back(VData, VData + N);
470}
471
Xinliang David Lib75544a2015-11-28 19:07:09 +0000472#define INSTR_PROF_COMMON_API_IMPL
473#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000474
Xinliang David Li020f22d2015-12-18 23:06:37 +0000475/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000476 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000477 * class. These C wrappers are used as adaptors so that C++ code can be
478 * invoked as callbacks.
479 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000480uint32_t getNumValueKindsInstrProf(const void *Record) {
481 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
482}
483
484uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
485 return reinterpret_cast<const InstrProfRecord *>(Record)
486 ->getNumValueSites(VKind);
487}
488
489uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
490 return reinterpret_cast<const InstrProfRecord *>(Record)
491 ->getNumValueData(VKind);
492}
493
494uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
495 uint32_t S) {
496 return reinterpret_cast<const InstrProfRecord *>(R)
497 ->getNumValueDataForSite(VK, S);
498}
499
500void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000501 uint32_t K, uint32_t S) {
502 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000503}
504
Xinliang David Lif47cf552015-11-25 06:23:38 +0000505ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000506 ValueProfData *VD =
507 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
508 memset(VD, 0, TotalSizeInBytes);
509 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000510}
511
512static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000513 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000514 getNumValueKindsInstrProf,
515 getNumValueSitesInstrProf,
516 getNumValueDataInstrProf,
517 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000518 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000519 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000520 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000521
Xinliang David Lie8092312015-11-25 19:13:00 +0000522// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000523uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
524 InstrProfRecordClosure.Record = &Record;
525 return getValueProfDataSize(&InstrProfRecordClosure);
526}
527
Xinliang David Lie8092312015-11-25 19:13:00 +0000528// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000529std::unique_ptr<ValueProfData>
530ValueProfData::serializeFrom(const InstrProfRecord &Record) {
531 InstrProfRecordClosure.Record = &Record;
532
533 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000534 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000535 return VPD;
536}
537
Xinliang David Lie8092312015-11-25 19:13:00 +0000538void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
539 InstrProfRecord::ValueMapType *VMap) {
540 Record.reserveSites(Kind, NumValueSites);
541
542 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
543 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
544 uint8_t ValueDataCount = this->SiteCountArray[VSite];
545 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
546 ValueData += ValueDataCount;
547 }
548}
Xinliang David Lied966772015-11-25 23:31:18 +0000549
Xinliang David Lie8092312015-11-25 19:13:00 +0000550// For writing/serializing, Old is the host endianness, and New is
551// byte order intended on disk. For Reading/deserialization, Old
552// is the on-disk source endianness, and New is the host endianness.
553void ValueProfRecord::swapBytes(support::endianness Old,
554 support::endianness New) {
555 using namespace support;
556 if (Old == New)
557 return;
558
559 if (getHostEndianness() != Old) {
560 sys::swapByteOrder<uint32_t>(NumValueSites);
561 sys::swapByteOrder<uint32_t>(Kind);
562 }
563 uint32_t ND = getValueProfRecordNumValueData(this);
564 InstrProfValueData *VD = getValueProfRecordValueData(this);
565
566 // No need to swap byte array: SiteCountArrray.
567 for (uint32_t I = 0; I < ND; I++) {
568 sys::swapByteOrder<uint64_t>(VD[I].Value);
569 sys::swapByteOrder<uint64_t>(VD[I].Count);
570 }
571 if (getHostEndianness() == Old) {
572 sys::swapByteOrder<uint32_t>(NumValueSites);
573 sys::swapByteOrder<uint32_t>(Kind);
574 }
575}
576
577void ValueProfData::deserializeTo(InstrProfRecord &Record,
578 InstrProfRecord::ValueMapType *VMap) {
579 if (NumValueKinds == 0)
580 return;
581
582 ValueProfRecord *VR = getFirstValueProfRecord(this);
583 for (uint32_t K = 0; K < NumValueKinds; K++) {
584 VR->deserializeTo(Record, VMap);
585 VR = getValueProfRecordNext(VR);
586 }
587}
588
589template <class T>
590static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
591 using namespace support;
592 if (Orig == little)
593 return endian::readNext<T, little, unaligned>(D);
594 else
595 return endian::readNext<T, big, unaligned>(D);
596}
597
598static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
599 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
600 ValueProfData());
601}
602
Vedant Kumar9152fd12016-05-19 03:54:45 +0000603Error ValueProfData::checkIntegrity() {
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000604 if (NumValueKinds > IPVK_Last + 1)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000605 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000606 // Total size needs to be mulltiple of quadword size.
607 if (TotalSize % sizeof(uint64_t))
Vedant Kumar9152fd12016-05-19 03:54:45 +0000608 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000609
610 ValueProfRecord *VR = getFirstValueProfRecord(this);
611 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
612 if (VR->Kind > IPVK_Last)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000613 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000614 VR = getValueProfRecordNext(VR);
615 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000616 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000617 }
Vedant Kumar9152fd12016-05-19 03:54:45 +0000618 return Error::success();
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000619}
620
Vedant Kumar9152fd12016-05-19 03:54:45 +0000621Expected<std::unique_ptr<ValueProfData>>
Xinliang David Liee415892015-11-10 00:24:45 +0000622ValueProfData::getValueProfData(const unsigned char *D,
623 const unsigned char *const BufferEnd,
624 support::endianness Endianness) {
625 using namespace support;
626 if (D + sizeof(ValueProfData) > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000627 return make_error<InstrProfError>(instrprof_error::truncated);
Xinliang David Liee415892015-11-10 00:24:45 +0000628
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000629 const unsigned char *Header = D;
630 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000631 if (D + TotalSize > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000632 return make_error<InstrProfError>(instrprof_error::too_large);
Xinliang David Liee415892015-11-10 00:24:45 +0000633
Xinliang David Lif47cf552015-11-25 06:23:38 +0000634 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000635 memcpy(VPD.get(), D, TotalSize);
636 // Byte swap.
637 VPD->swapBytesToHost(Endianness);
638
Vedant Kumar9152fd12016-05-19 03:54:45 +0000639 Error E = VPD->checkIntegrity();
640 if (E)
641 return std::move(E);
Xinliang David Liee415892015-11-10 00:24:45 +0000642
Xinliang David Liee415892015-11-10 00:24:45 +0000643 return std::move(VPD);
644}
645
646void ValueProfData::swapBytesToHost(support::endianness Endianness) {
647 using namespace support;
648 if (Endianness == getHostEndianness())
649 return;
650
651 sys::swapByteOrder<uint32_t>(TotalSize);
652 sys::swapByteOrder<uint32_t>(NumValueKinds);
653
Xinliang David Lif47cf552015-11-25 06:23:38 +0000654 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000655 for (uint32_t K = 0; K < NumValueKinds; K++) {
656 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000657 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000658 }
659}
660
661void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
662 using namespace support;
663 if (Endianness == getHostEndianness())
664 return;
665
Xinliang David Lif47cf552015-11-25 06:23:38 +0000666 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000667 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000668 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000669 VR->swapBytes(getHostEndianness(), Endianness);
670 VR = NVR;
671 }
672 sys::swapByteOrder<uint32_t>(TotalSize);
673 sys::swapByteOrder<uint32_t>(NumValueKinds);
674}
Xinliang David Lie8092312015-11-25 19:13:00 +0000675
Xinliang David Li402477d2016-02-04 19:11:43 +0000676void annotateValueSite(Module &M, Instruction &Inst,
677 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000678 InstrProfValueKind ValueKind, uint32_t SiteIdx,
679 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000680 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000681 if (!NV)
682 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000683
684 uint64_t Sum = 0;
685 std::unique_ptr<InstrProfValueData[]> VD =
686 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
687
Rong Xu311ada12016-03-30 16:56:31 +0000688 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
689 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000690}
691
692void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000693 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000694 uint64_t Sum, InstrProfValueKind ValueKind,
695 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000696 LLVMContext &Ctx = M.getContext();
697 MDBuilder MDHelper(Ctx);
698 SmallVector<Metadata *, 3> Vals;
699 // Tag
700 Vals.push_back(MDHelper.createString("VP"));
701 // Value Kind
702 Vals.push_back(MDHelper.createConstant(
703 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
704 // Total Count
705 Vals.push_back(
706 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
707
708 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000709 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000710 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000711 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000712 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000713 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000714 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000715 if (--MDCount == 0)
716 break;
717 }
718 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
719}
720
721bool getValueProfDataFromInst(const Instruction &Inst,
722 InstrProfValueKind ValueKind,
723 uint32_t MaxNumValueData,
724 InstrProfValueData ValueData[],
725 uint32_t &ActualNumValueData, uint64_t &TotalC) {
726 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
727 if (!MD)
728 return false;
729
730 unsigned NOps = MD->getNumOperands();
731
732 if (NOps < 5)
733 return false;
734
735 // Operand 0 is a string tag "VP":
736 MDString *Tag = cast<MDString>(MD->getOperand(0));
737 if (!Tag)
738 return false;
739
740 if (!Tag->getString().equals("VP"))
741 return false;
742
743 // Now check kind:
744 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
745 if (!KindInt)
746 return false;
747 if (KindInt->getZExtValue() != ValueKind)
748 return false;
749
750 // Get total count
751 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
752 if (!TotalCInt)
753 return false;
754 TotalC = TotalCInt->getZExtValue();
755
756 ActualNumValueData = 0;
757
758 for (unsigned I = 3; I < NOps; I += 2) {
759 if (ActualNumValueData >= MaxNumValueData)
760 break;
761 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
762 ConstantInt *Count =
763 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
764 if (!Value || !Count)
765 return false;
766 ValueData[ActualNumValueData].Value = Value->getZExtValue();
767 ValueData[ActualNumValueData].Count = Count->getZExtValue();
768 ActualNumValueData++;
769 }
770 return true;
771}
Rong Xu8e8fe852016-04-01 16:43:30 +0000772
Rong Xu92c2eae2016-04-01 20:15:04 +0000773MDNode *getPGOFuncNameMetadata(const Function &F) {
774 return F.getMetadata(getPGOFuncNameMetadataName());
775}
776
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000777void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
Rong Xuf8f051c2016-04-22 21:00:17 +0000778 // Only for internal linkage functions.
779 if (PGOFuncName == F.getName())
780 return;
781 // Don't create duplicated meta-data.
782 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000783 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000784 LLVMContext &C = F.getContext();
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000785 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
Rong Xu8e8fe852016-04-01 16:43:30 +0000786 F.setMetadata(getPGOFuncNameMetadataName(), N);
787}
788
Rong Xu97b68c52016-07-21 20:50:02 +0000789bool needsComdatForCounter(const Function &F, const Module &M) {
790 if (F.hasComdat())
791 return true;
792
793 Triple TT(M.getTargetTriple());
794 if (!TT.isOSBinFormatELF())
795 return false;
796
797 // See createPGOFuncNameVar for more details. To avoid link errors, profile
798 // counters for function with available_externally linkage needs to be changed
799 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
800 // created. Without using comdat, duplicate entries won't be removed by the
801 // linker leading to increased data segement size and raw profile size. Even
802 // worse, since the referenced counter from profile per-function data object
803 // will be resolved to the common strong definition, the profile counts for
804 // available_externally functions will end up being duplicated in raw profile
805 // data. This can result in distorted profile as the counts of those dups
806 // will be accumulated by the profile merger.
807 GlobalValue::LinkageTypes Linkage = F.getLinkage();
808 if (Linkage != GlobalValue::ExternalWeakLinkage &&
809 Linkage != GlobalValue::AvailableExternallyLinkage)
810 return false;
811
812 return true;
813}
Rong Xu20f5df12017-01-11 20:19:41 +0000814
815// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
816bool isIRPGOFlagSet(const Module *M) {
817 auto IRInstrVar =
818 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
819 if (!IRInstrVar || IRInstrVar->isDeclaration() ||
820 IRInstrVar->hasLocalLinkage())
821 return false;
822
823 // Check if the flag is set.
824 if (!IRInstrVar->hasInitializer())
825 return false;
826
827 const Constant *InitVal = IRInstrVar->getInitializer();
828 if (!InitVal)
829 return false;
830
831 return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
832 VARIANT_MASK_IR_PROF) != 0;
833}
834
835// Check if we can safely rename this Comdat function.
836bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
837 if (F.getName().empty())
838 return false;
839 if (!needsComdatForCounter(F, *(F.getParent())))
840 return false;
841 // Unsafe to rename the address-taken function (which can be used in
842 // function comparison).
843 if (CheckAddressTaken && F.hasAddressTaken())
844 return false;
845 // Only safe to do if this function may be discarded if it is not used
846 // in the compilation unit.
847 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
848 return false;
849
850 // For AvailableExternallyLinkage functions.
851 if (!F.hasComdat()) {
852 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
853 return true;
854 }
855 return true;
856}
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000857} // end namespace llvm