blob: a8f5b7f3d0e1047ccd5a4f2e0c3c4b05284354fa [file] [log] [blame]
Eugene Zelenkoe78d1312017-03-03 01:07:34 +00001//===- InstrProf.cpp - Instrumented profiling format support --------------===//
Justin Bognerf8d79192014-03-21 17:24:48 +00002//
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
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000015#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/SmallVector.h"
Xinliang David Li0c677872016-01-04 21:31:09 +000018#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000019#include "llvm/ADT/StringRef.h"
Rong Xu97b68c52016-07-21 20:50:02 +000020#include "llvm/ADT/Triple.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000021#include "llvm/IR/Constant.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/Function.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000024#include "llvm/IR/GlobalValue.h"
Xinliang David Li441959d2015-11-09 00:01:22 +000025#include "llvm/IR/GlobalVariable.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000026#include "llvm/IR/Instruction.h"
27#include "llvm/IR/LLVMContext.h"
Xinliang David Li402477d2016-02-04 19:11:43 +000028#include "llvm/IR/MDBuilder.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000029#include "llvm/IR/Metadata.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000030#include "llvm/IR/Module.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000031#include "llvm/IR/Type.h"
32#include "llvm/ProfileData/InstrProf.h"
33#include "llvm/Support/Casting.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Compiler.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000036#include "llvm/Support/Compression.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000037#include "llvm/Support/Endian.h"
38#include "llvm/Support/Error.h"
Justin Bognerf8d79192014-03-21 17:24:48 +000039#include "llvm/Support/ErrorHandling.h"
Xinliang David Lie413f1a2015-12-31 07:57:16 +000040#include "llvm/Support/LEB128.h"
Chris Bieneman1efe8012014-09-19 23:19:24 +000041#include "llvm/Support/ManagedStatic.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000042#include "llvm/Support/MathExtras.h"
Xinliang David Li9eb472b2016-07-12 17:14:51 +000043#include "llvm/Support/Path.h"
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000044#include "llvm/Support/SwapByteOrder.h"
45#include <algorithm>
46#include <cassert>
47#include <cstddef>
48#include <cstring>
49#include <cstdint>
50#include <memory>
51#include <string>
52#include <system_error>
53#include <utility>
54#include <vector>
Justin Bognerf8d79192014-03-21 17:24:48 +000055
56using namespace llvm;
57
Xinliang David Li9eb472b2016-07-12 17:14:51 +000058static cl::opt<bool> StaticFuncFullModulePrefix(
Rong Xua1a9f702017-02-25 00:00:36 +000059 "static-func-full-module-prefix", cl::init(true),
Xinliang David Li9eb472b2016-07-12 17:14:51 +000060 cl::desc("Use full module build paths in the profile counter names for "
61 "static functions."));
62
Rong Xua1a9f702017-02-25 00:00:36 +000063// This option is tailored to users that have different top-level directory in
64// profile-gen and profile-use compilation. Users need to specific the number
65// of levels to strip. A value larger than the number of directories in the
66// source file will strip all the directory names and only leave the basename.
67//
Rong Xu08d08402017-02-27 17:59:01 +000068// Note current ThinLTO module importing for the indirect-calls assumes
Rong Xua1a9f702017-02-25 00:00:36 +000069// the source directory name not being stripped. A non-zero option value here
70// can potentially prevent some inter-module indirect-call-promotions.
71static cl::opt<unsigned> StaticFuncStripDirNamePrefix(
72 "static-func-strip-dirname-prefix", cl::init(0),
73 cl::desc("Strip specified level of directory name from source path in "
74 "the profile counter name for static functions."));
75
Eugene Zelenkoe78d1312017-03-03 01:07:34 +000076static std::string getInstrProfErrString(instrprof_error Err) {
Vedant Kumar9152fd12016-05-19 03:54:45 +000077 switch (Err) {
78 case instrprof_error::success:
79 return "Success";
80 case instrprof_error::eof:
81 return "End of File";
82 case instrprof_error::unrecognized_format:
83 return "Unrecognized instrumentation profile encoding format";
84 case instrprof_error::bad_magic:
85 return "Invalid instrumentation profile data (bad magic)";
86 case instrprof_error::bad_header:
87 return "Invalid instrumentation profile data (file header is corrupt)";
88 case instrprof_error::unsupported_version:
89 return "Unsupported instrumentation profile format version";
90 case instrprof_error::unsupported_hash_type:
91 return "Unsupported instrumentation profile hash type";
92 case instrprof_error::too_large:
93 return "Too much profile data";
94 case instrprof_error::truncated:
95 return "Truncated profile data";
96 case instrprof_error::malformed:
97 return "Malformed instrumentation profile data";
98 case instrprof_error::unknown_function:
99 return "No profile data available for function";
100 case instrprof_error::hash_mismatch:
101 return "Function control flow change detected (hash mismatch)";
102 case instrprof_error::count_mismatch:
103 return "Function basic block count change detected (counter mismatch)";
104 case instrprof_error::counter_overflow:
105 return "Counter overflow";
106 case instrprof_error::value_site_count_mismatch:
107 return "Function value site count change detected (counter mismatch)";
108 case instrprof_error::compress_failed:
109 return "Failed to compress data (zlib)";
110 case instrprof_error::uncompress_failed:
111 return "Failed to uncompress data (zlib)";
Rong Xu2c684cf2016-10-19 22:51:17 +0000112 case instrprof_error::empty_raw_profile:
113 return "Empty raw profile file";
Vedant Kumar9152fd12016-05-19 03:54:45 +0000114 }
115 llvm_unreachable("A value of instrprof_error has no message.");
116}
117
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000118namespace {
119
Peter Collingbourne4718f8b2016-05-24 20:13:46 +0000120// FIXME: This class is only here to support the transition to llvm::Error. It
121// will be removed once this transition is complete. Clients should prefer to
122// deal with the Error value directly, rather than converting to error_code.
Rafael Espindola25188c92014-06-12 01:45:43 +0000123class InstrProfErrorCategoryType : public std::error_category {
Reid Kleckner990504e2016-10-19 23:52:38 +0000124 const char *name() const noexcept override { return "llvm.instrprof"; }
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000125
Justin Bognerf8d79192014-03-21 17:24:48 +0000126 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000127 return getInstrProfErrString(static_cast<instrprof_error>(IE));
Justin Bognerf8d79192014-03-21 17:24:48 +0000128 }
Justin Bognerf8d79192014-03-21 17:24:48 +0000129};
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000130
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000131} // end anonymous namespace
Justin Bognerf8d79192014-03-21 17:24:48 +0000132
Chris Bieneman1efe8012014-09-19 23:19:24 +0000133static ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;
134
Rafael Espindola25188c92014-06-12 01:45:43 +0000135const std::error_category &llvm::instrprof_category() {
Chris Bieneman1efe8012014-09-19 23:19:24 +0000136 return *ErrorCategory;
Justin Bognerf8d79192014-03-21 17:24:48 +0000137}
Xinliang David Li441959d2015-11-09 00:01:22 +0000138
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000139namespace {
140
141enum InstrProfSectKind {
142#define INSTR_PROF_SECT_ENTRY(Kind, SectName, SectNameCommon, SectNameCoff, \
143 Prefix) \
144 Kind,
145#include "llvm/ProfileData/InstrProfData.inc"
146};
147
148const char *InstrProfSectName[] = {
149#define INSTR_PROF_SECT_ENTRY(Kind, SectName, SectNameCommon, SectNameCoff, \
150 Prefix) \
151 SectName,
152#include "llvm/ProfileData/InstrProfData.inc"
153};
154
155const char *InstrProfSectNameCommon[] = {
156#define INSTR_PROF_SECT_ENTRY(Kind, SectName, SectNameCommon, SectNameCoff, \
157 Prefix) \
158 SectNameCommon,
159#include "llvm/ProfileData/InstrProfData.inc"
160};
161
162const char *InstrProfSectNameCoff[] = {
163#define INSTR_PROF_SECT_ENTRY(Kind, SectName, SectNameCommon, SectNameCoff, \
164 Prefix) \
165 SectNameCoff,
166#include "llvm/ProfileData/InstrProfData.inc"
167};
168
169const char *InstrProfSectNamePrefix[] = {
170#define INSTR_PROF_SECT_ENTRY(Kind, SectName, SectNameCommon, SectNameCoff, \
171 Prefix) \
172 Prefix,
173#include "llvm/ProfileData/InstrProfData.inc"
174};
175
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000176std::string getInstrProfSectionName(bool isCoff, InstrProfSectKind Kind) {
177 return isCoff ? InstrProfSectNameCoff[Kind] : InstrProfSectNameCommon[Kind];
178}
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000179
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000180std::string getInstrProfSectionName(const Module *M, InstrProfSectKind Kind) {
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000181 if (!M)
182 return InstrProfSectName[Kind];
183
184 bool AddSegment = Triple(M->getTargetTriple()).isOSBinFormatMachO();
185 std::string SectName;
186 if (Triple(M->getTargetTriple()).isOSBinFormatCOFF())
187 SectName = InstrProfSectNameCoff[Kind];
188 else
189 SectName = InstrProfSectNameCommon[Kind];
190
191 if (AddSegment) {
192 SectName = InstrProfSectNamePrefix[Kind] + SectName;
193 if (Kind == IPSK_data) {
194 SectName += ",regular,live_support";
195 }
196 }
197 return SectName;
198}
199
200} // namespace
201
Xinliang David Li441959d2015-11-09 00:01:22 +0000202namespace llvm {
203
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000204std::string getInstrProfCountersSectionName(const Module *M) {
205 return getInstrProfSectionName(M, IPSK_cnts);
206}
207
208std::string getInstrProfNameSectionName(const Module *M) {
209 return getInstrProfSectionName(M, IPSK_name);
210}
211
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000212std::string getInstrProfNameSectionNameInObject(bool isCoff) {
213 return getInstrProfSectionName(isCoff, IPSK_name);
214}
215
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000216std::string getInstrProfDataSectionName(const Module *M) {
217 return getInstrProfSectionName(M, IPSK_data);
218}
219
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000220std::string getInstrProfDataSectionNameInObject(bool isCoff) {
221 return getInstrProfSectionName(isCoff, IPSK_data);
222}
223
Xinliang David Li57dea2d2017-04-13 23:37:12 +0000224std::string getInstrProfValuesSectionName(const Module *M) {
225 return getInstrProfSectionName(M, IPSK_vals);
226}
227
228std::string getInstrProfVNodesSectionName(const Module *M) {
229 return getInstrProfSectionName(M, IPSK_vnodes);
230}
231
232std::string getInstrProfCoverageSectionName(const Module *M) {
233 return getInstrProfSectionName(M, IPSK_covmap);
234}
235
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000236std::string getInstrProfCoverageSectionNameInObject(bool isCoff) {
237 return getInstrProfSectionName(isCoff, IPSK_covmap);
238}
239
Vedant Kumar42369db2016-05-11 19:42:19 +0000240void SoftInstrProfErrors::addError(instrprof_error IE) {
241 if (IE == instrprof_error::success)
242 return;
243
244 if (FirstError == instrprof_error::success)
245 FirstError = IE;
246
247 switch (IE) {
248 case instrprof_error::hash_mismatch:
249 ++NumHashMismatches;
250 break;
251 case instrprof_error::count_mismatch:
252 ++NumCountMismatches;
253 break;
254 case instrprof_error::counter_overflow:
255 ++NumCounterOverflows;
256 break;
257 case instrprof_error::value_site_count_mismatch:
258 ++NumValueSiteCountMismatches;
259 break;
260 default:
261 llvm_unreachable("Not a soft error");
262 }
263}
264
Vedant Kumar9152fd12016-05-19 03:54:45 +0000265std::string InstrProfError::message() const {
266 return getInstrProfErrString(Err);
267}
268
269char InstrProfError::ID = 0;
270
Xinliang David Li441959d2015-11-09 00:01:22 +0000271std::string getPGOFuncName(StringRef RawFuncName,
272 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +0000273 StringRef FileName,
274 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +0000275 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000276}
277
Rong Xua1a9f702017-02-25 00:00:36 +0000278// Strip NumPrefix level of directory name from PathNameStr. If the number of
279// directory separators is less than NumPrefix, strip all the directories and
280// leave base file name only.
281static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
282 uint32_t Count = NumPrefix;
283 uint32_t Pos = 0, LastPos = 0;
284 for (auto & CI : PathNameStr) {
285 ++Pos;
286 if (llvm::sys::path::is_separator(CI)) {
287 LastPos = Pos;
288 --Count;
289 }
290 if (Count == 0)
291 break;
292 }
293 return PathNameStr.substr(LastPos);
294}
295
Rong Xub5341662016-03-30 18:37:52 +0000296// Return the PGOFuncName. This function has some special handling when called
297// in LTO optimization. The following only applies when calling in LTO passes
298// (when \c InLTO is true): LTO's internalization privatizes many global linkage
299// symbols. This happens after value profile annotation, but those internal
300// linkage functions should not have a source prefix.
Teresa Johnson8c1bc982016-08-29 22:46:56 +0000301// Additionally, for ThinLTO mode, exported internal functions are promoted
302// and renamed. We need to ensure that the original internal PGO name is
303// used when computing the GUID that is compared against the profiled GUIDs.
Rong Xub5341662016-03-30 18:37:52 +0000304// To differentiate compiler generated internal symbols from original ones,
305// PGOFuncName meta data are created and attached to the original internal
306// symbols in the value profile annotation step
307// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
308// data, its original linkage must be non-internal.
309std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000310 if (!InLTO) {
311 StringRef FileName = (StaticFuncFullModulePrefix
312 ? F.getParent()->getName()
313 : sys::path::filename(F.getParent()->getName()));
Rong Xua1a9f702017-02-25 00:00:36 +0000314 if (StaticFuncFullModulePrefix && StaticFuncStripDirNamePrefix != 0)
315 FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000316 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
317 }
Rong Xub5341662016-03-30 18:37:52 +0000318
Rong Xu8e8fe852016-04-01 16:43:30 +0000319 // In LTO mode (when InLTO is true), first check if there is a meta data.
320 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000321 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
322 return S.str();
323 }
324
325 // If there is no meta data, the function must be a global before the value
326 // profile annotation pass. Its current linkage may be internal if it is
327 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000328 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000329}
330
Xinliang David Li4ec40142015-12-15 19:44:45 +0000331StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
332 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000333 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000334 // Drop the file name including ':'. See also getPGOFuncName.
335 if (PGOFuncName.startswith(FileName))
336 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
337 return PGOFuncName;
338}
339
Xinliang David Lid1bab962015-12-12 17:28:03 +0000340// \p FuncName is the string used as profile lookup key for the function. A
341// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000342std::string getPGOFuncNameVarName(StringRef FuncName,
343 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000344 std::string VarName = getInstrProfNameVarPrefix();
345 VarName += FuncName;
346
347 if (!GlobalValue::isLocalLinkage(Linkage))
348 return VarName;
349
350 // Now fix up illegal chars in local VarName that may upset the assembler.
Xinliang David Lieeaf0bc2016-06-10 06:32:26 +0000351 const char *InvalidChars = "-:<>/\"'";
Xinliang David Lid1bab962015-12-12 17:28:03 +0000352 size_t found = VarName.find_first_of(InvalidChars);
353 while (found != std::string::npos) {
354 VarName[found] = '_';
355 found = VarName.find_first_of(InvalidChars, found + 1);
356 }
357 return VarName;
358}
359
Xinliang David Li441959d2015-11-09 00:01:22 +0000360GlobalVariable *createPGOFuncNameVar(Module &M,
361 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000362 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000363 // We generally want to match the function's linkage, but available_externally
364 // and extern_weak both have the wrong semantics, and anything that doesn't
365 // need to link across compilation units doesn't need to be visible at all.
366 if (Linkage == GlobalValue::ExternalWeakLinkage)
367 Linkage = GlobalValue::LinkOnceAnyLinkage;
368 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
369 Linkage = GlobalValue::LinkOnceODRLinkage;
370 else if (Linkage == GlobalValue::InternalLinkage ||
371 Linkage == GlobalValue::ExternalLinkage)
372 Linkage = GlobalValue::PrivateLinkage;
373
Xinliang David Li897d2922016-03-16 22:13:41 +0000374 auto *Value =
375 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000376 auto FuncNameVar =
377 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000378 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000379
380 // Hide the symbol so that we correctly get a copy for each executable.
381 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
382 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
383
384 return FuncNameVar;
385}
386
Xinliang David Li897d2922016-03-16 22:13:41 +0000387GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
388 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000389}
Xinliang David Liee415892015-11-10 00:24:45 +0000390
Rong Xub5341662016-03-30 18:37:52 +0000391void InstrProfSymtab::create(Module &M, bool InLTO) {
392 for (Function &F : M) {
393 // Function may not have a name: like using asm("") to overwrite the name.
394 // Ignore in this case.
395 if (!F.hasName())
396 continue;
397 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
398 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000399 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Dehao Chen4a435e02017-03-14 17:33:01 +0000400 // In ThinLTO, local function may have been promoted to global and have
401 // suffix added to the function name. We need to add the stripped function
402 // name to the symbol table so that we can find a match from profile.
403 if (InLTO) {
404 auto pos = PGOFuncName.find('.');
405 if (pos != std::string::npos) {
406 const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
407 addFuncName(OtherFuncName);
408 MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
409 }
410 }
Rong Xub5341662016-03-30 18:37:52 +0000411 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000412
413 finalizeSymtab();
414}
415
Vedant Kumar9152fd12016-05-19 03:54:45 +0000416Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
417 bool doCompression, std::string &Result) {
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000418 assert(!NameStrs.empty() && "No name data to emit");
Vedant Kumar86705ba2016-03-28 21:06:42 +0000419
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000420 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000421 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000422 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
423
424 assert(StringRef(UncompressedNameStrings)
425 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
426 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000427
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000428 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
429 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000430
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000431 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000432 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000433 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000434 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
435 unsigned HeaderLen = P - &Header[0];
436 Result.append(HeaderStr, HeaderLen);
437 Result += InputStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000438 return Error::success();
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000439 };
440
Vedant Kumar9152fd12016-05-19 03:54:45 +0000441 if (!doCompression) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000442 return WriteStringToResult(0, UncompressedNameStrings);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000443 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000444
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000445 SmallString<128> CompressedNameStrings;
George Rimar167ca4a2017-01-17 15:45:07 +0000446 Error E = zlib::compress(StringRef(UncompressedNameStrings),
447 CompressedNameStrings, zlib::BestSizeCompression);
448 if (E) {
449 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000450 return make_error<InstrProfError>(instrprof_error::compress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000451 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000452
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000453 return WriteStringToResult(CompressedNameStrings.size(),
454 CompressedNameStrings);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000455}
456
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000457StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000458 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
459 StringRef NameStr =
460 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
461 return NameStr;
462}
463
Vedant Kumar9152fd12016-05-19 03:54:45 +0000464Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
465 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000466 std::vector<std::string> NameStrs;
467 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000468 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000469 }
Xinliang David Li73163752016-01-26 23:13:00 +0000470 return collectPGOFuncNameStrings(
471 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000472}
473
Vedant Kumar9152fd12016-05-19 03:54:45 +0000474Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000475 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
476 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
477 NameStrings.size());
478 while (P < EndP) {
479 uint32_t N;
480 uint64_t UncompressedSize = decodeULEB128(P, &N);
481 P += N;
482 uint64_t CompressedSize = decodeULEB128(P, &N);
483 P += N;
484 bool isCompressed = (CompressedSize != 0);
485 SmallString<128> UncompressedNameStrings;
486 StringRef NameStrings;
487 if (isCompressed) {
488 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
489 CompressedSize);
George Rimar167ca4a2017-01-17 15:45:07 +0000490 if (Error E =
491 zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
492 UncompressedSize)) {
493 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000494 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000495 }
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000496 P += CompressedSize;
497 NameStrings = StringRef(UncompressedNameStrings.data(),
498 UncompressedNameStrings.size());
499 } else {
500 NameStrings =
501 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
502 P += UncompressedSize;
503 }
504 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000505 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000506 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000507 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000508 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000509
510 while (P < EndP && *P == 0)
511 P++;
512 }
513 Symtab.finalizeSymtab();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000514 return Error::success();
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000515}
516
Vedant Kumar42369db2016-05-11 19:42:19 +0000517void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
518 InstrProfValueSiteRecord &Input,
519 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000520 this->sortByTargetValues();
521 Input.sortByTargetValues();
522 auto I = ValueData.begin();
523 auto IE = ValueData.end();
Xinliang David Li5c24da52015-12-20 05:15:45 +0000524 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
525 ++J) {
526 while (I != IE && I->Value < J->Value)
527 ++I;
528 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000529 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000530 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000531 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000532 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000533 ++I;
534 continue;
535 }
536 ValueData.insert(I, *J);
537 }
Xinliang David Li5c24da52015-12-20 05:15:45 +0000538}
539
Vedant Kumar42369db2016-05-11 19:42:19 +0000540void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
541 uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000542 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
543 bool Overflowed;
544 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
545 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000546 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000547 }
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000548}
549
Xinliang David Li020f22d2015-12-18 23:06:37 +0000550// Merge Value Profile data from Src record to this record for ValueKind.
551// Scale merged value counts by \p Weight.
Vedant Kumar42369db2016-05-11 19:42:19 +0000552void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
553 InstrProfRecord &Src,
554 uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000555 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
556 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
Vedant Kumar42369db2016-05-11 19:42:19 +0000557 if (ThisNumValueSites != OtherNumValueSites) {
558 SIPE.addError(instrprof_error::value_site_count_mismatch);
559 return;
560 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000561 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
562 getValueSitesForKind(ValueKind);
563 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
564 Src.getValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000565 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000566 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000567}
568
Vedant Kumar42369db2016-05-11 19:42:19 +0000569void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000570 // If the number of counters doesn't match we either have bad data
571 // or a hash collision.
Vedant Kumar42369db2016-05-11 19:42:19 +0000572 if (Counts.size() != Other.Counts.size()) {
573 SIPE.addError(instrprof_error::count_mismatch);
574 return;
575 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000576
577 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
578 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000579 Counts[I] =
580 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000581 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000582 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000583 }
584
585 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000586 mergeValueProfData(Kind, Other, Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000587}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000588
Vedant Kumar42369db2016-05-11 19:42:19 +0000589void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000590 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
591 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
592 getValueSitesForKind(ValueKind);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000593 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000594 ThisSiteRecords[I].scale(SIPE, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000595}
596
Vedant Kumar42369db2016-05-11 19:42:19 +0000597void InstrProfRecord::scale(uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000598 for (auto &Count : this->Counts) {
599 bool Overflowed;
600 Count = SaturatingMultiply(Count, Weight, &Overflowed);
Vedant Kumar42369db2016-05-11 19:42:19 +0000601 if (Overflowed)
602 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000603 }
604 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000605 scaleValueProfData(Kind, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000606}
607
Xinliang David Li020f22d2015-12-18 23:06:37 +0000608// Map indirect call target name hash to name string.
609uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000610 ValueMapType *ValueMap) {
611 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000612 return Value;
613 switch (ValueKind) {
614 case IPVK_IndirectCallTarget: {
615 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000616 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
617 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000618 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000619 // Raw function pointer collected by value profiler may be from
620 // external functions that are not instrumented. They won't have
621 // mapping data to be used by the deserializer. Force the value to
622 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000623 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000624 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000625 else
626 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000627 break;
628 }
629 }
630 return Value;
631}
632
Xinliang David Li020f22d2015-12-18 23:06:37 +0000633void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
634 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000635 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000636 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000637 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000638 }
639 std::vector<InstrProfValueSiteRecord> &ValueSites =
640 getValueSitesForKind(ValueKind);
641 if (N == 0)
Vedant Kumar6b22ba62016-05-11 16:03:02 +0000642 ValueSites.emplace_back();
Xinliang David Li020f22d2015-12-18 23:06:37 +0000643 else
644 ValueSites.emplace_back(VData, VData + N);
645}
646
Xinliang David Lib75544a2015-11-28 19:07:09 +0000647#define INSTR_PROF_COMMON_API_IMPL
648#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000649
Xinliang David Li020f22d2015-12-18 23:06:37 +0000650/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000651 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000652 * class. These C wrappers are used as adaptors so that C++ code can be
653 * invoked as callbacks.
654 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000655uint32_t getNumValueKindsInstrProf(const void *Record) {
656 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
657}
658
659uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
660 return reinterpret_cast<const InstrProfRecord *>(Record)
661 ->getNumValueSites(VKind);
662}
663
664uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
665 return reinterpret_cast<const InstrProfRecord *>(Record)
666 ->getNumValueData(VKind);
667}
668
669uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
670 uint32_t S) {
671 return reinterpret_cast<const InstrProfRecord *>(R)
672 ->getNumValueDataForSite(VK, S);
673}
674
675void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000676 uint32_t K, uint32_t S) {
677 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000678}
679
Xinliang David Lif47cf552015-11-25 06:23:38 +0000680ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000681 ValueProfData *VD =
682 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
683 memset(VD, 0, TotalSizeInBytes);
684 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000685}
686
687static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000688 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000689 getNumValueKindsInstrProf,
690 getNumValueSitesInstrProf,
691 getNumValueDataInstrProf,
692 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000693 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000694 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000695 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000696
Xinliang David Lie8092312015-11-25 19:13:00 +0000697// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000698uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
699 InstrProfRecordClosure.Record = &Record;
700 return getValueProfDataSize(&InstrProfRecordClosure);
701}
702
Xinliang David Lie8092312015-11-25 19:13:00 +0000703// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000704std::unique_ptr<ValueProfData>
705ValueProfData::serializeFrom(const InstrProfRecord &Record) {
706 InstrProfRecordClosure.Record = &Record;
707
708 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000709 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000710 return VPD;
711}
712
Xinliang David Lie8092312015-11-25 19:13:00 +0000713void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
714 InstrProfRecord::ValueMapType *VMap) {
715 Record.reserveSites(Kind, NumValueSites);
716
717 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
718 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
719 uint8_t ValueDataCount = this->SiteCountArray[VSite];
720 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
721 ValueData += ValueDataCount;
722 }
723}
Xinliang David Lied966772015-11-25 23:31:18 +0000724
Xinliang David Lie8092312015-11-25 19:13:00 +0000725// For writing/serializing, Old is the host endianness, and New is
726// byte order intended on disk. For Reading/deserialization, Old
727// is the on-disk source endianness, and New is the host endianness.
728void ValueProfRecord::swapBytes(support::endianness Old,
729 support::endianness New) {
730 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000731
Xinliang David Lie8092312015-11-25 19:13:00 +0000732 if (Old == New)
733 return;
734
735 if (getHostEndianness() != Old) {
736 sys::swapByteOrder<uint32_t>(NumValueSites);
737 sys::swapByteOrder<uint32_t>(Kind);
738 }
739 uint32_t ND = getValueProfRecordNumValueData(this);
740 InstrProfValueData *VD = getValueProfRecordValueData(this);
741
742 // No need to swap byte array: SiteCountArrray.
743 for (uint32_t I = 0; I < ND; I++) {
744 sys::swapByteOrder<uint64_t>(VD[I].Value);
745 sys::swapByteOrder<uint64_t>(VD[I].Count);
746 }
747 if (getHostEndianness() == Old) {
748 sys::swapByteOrder<uint32_t>(NumValueSites);
749 sys::swapByteOrder<uint32_t>(Kind);
750 }
751}
752
753void ValueProfData::deserializeTo(InstrProfRecord &Record,
754 InstrProfRecord::ValueMapType *VMap) {
755 if (NumValueKinds == 0)
756 return;
757
758 ValueProfRecord *VR = getFirstValueProfRecord(this);
759 for (uint32_t K = 0; K < NumValueKinds; K++) {
760 VR->deserializeTo(Record, VMap);
761 VR = getValueProfRecordNext(VR);
762 }
763}
764
765template <class T>
766static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
767 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000768
Xinliang David Lie8092312015-11-25 19:13:00 +0000769 if (Orig == little)
770 return endian::readNext<T, little, unaligned>(D);
771 else
772 return endian::readNext<T, big, unaligned>(D);
773}
774
775static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
776 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
777 ValueProfData());
778}
779
Vedant Kumar9152fd12016-05-19 03:54:45 +0000780Error ValueProfData::checkIntegrity() {
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000781 if (NumValueKinds > IPVK_Last + 1)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000782 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000783 // Total size needs to be mulltiple of quadword size.
784 if (TotalSize % sizeof(uint64_t))
Vedant Kumar9152fd12016-05-19 03:54:45 +0000785 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000786
787 ValueProfRecord *VR = getFirstValueProfRecord(this);
788 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
789 if (VR->Kind > IPVK_Last)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000790 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000791 VR = getValueProfRecordNext(VR);
792 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000793 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000794 }
Vedant Kumar9152fd12016-05-19 03:54:45 +0000795 return Error::success();
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000796}
797
Vedant Kumar9152fd12016-05-19 03:54:45 +0000798Expected<std::unique_ptr<ValueProfData>>
Xinliang David Liee415892015-11-10 00:24:45 +0000799ValueProfData::getValueProfData(const unsigned char *D,
800 const unsigned char *const BufferEnd,
801 support::endianness Endianness) {
802 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000803
Xinliang David Liee415892015-11-10 00:24:45 +0000804 if (D + sizeof(ValueProfData) > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000805 return make_error<InstrProfError>(instrprof_error::truncated);
Xinliang David Liee415892015-11-10 00:24:45 +0000806
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000807 const unsigned char *Header = D;
808 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000809 if (D + TotalSize > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000810 return make_error<InstrProfError>(instrprof_error::too_large);
Xinliang David Liee415892015-11-10 00:24:45 +0000811
Xinliang David Lif47cf552015-11-25 06:23:38 +0000812 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000813 memcpy(VPD.get(), D, TotalSize);
814 // Byte swap.
815 VPD->swapBytesToHost(Endianness);
816
Vedant Kumar9152fd12016-05-19 03:54:45 +0000817 Error E = VPD->checkIntegrity();
818 if (E)
819 return std::move(E);
Xinliang David Liee415892015-11-10 00:24:45 +0000820
Xinliang David Liee415892015-11-10 00:24:45 +0000821 return std::move(VPD);
822}
823
824void ValueProfData::swapBytesToHost(support::endianness Endianness) {
825 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000826
Xinliang David Liee415892015-11-10 00:24:45 +0000827 if (Endianness == getHostEndianness())
828 return;
829
830 sys::swapByteOrder<uint32_t>(TotalSize);
831 sys::swapByteOrder<uint32_t>(NumValueKinds);
832
Xinliang David Lif47cf552015-11-25 06:23:38 +0000833 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000834 for (uint32_t K = 0; K < NumValueKinds; K++) {
835 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000836 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000837 }
838}
839
840void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
841 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000842
Xinliang David Liee415892015-11-10 00:24:45 +0000843 if (Endianness == getHostEndianness())
844 return;
845
Xinliang David Lif47cf552015-11-25 06:23:38 +0000846 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000847 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000848 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000849 VR->swapBytes(getHostEndianness(), Endianness);
850 VR = NVR;
851 }
852 sys::swapByteOrder<uint32_t>(TotalSize);
853 sys::swapByteOrder<uint32_t>(NumValueKinds);
854}
Xinliang David Lie8092312015-11-25 19:13:00 +0000855
Xinliang David Li402477d2016-02-04 19:11:43 +0000856void annotateValueSite(Module &M, Instruction &Inst,
857 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000858 InstrProfValueKind ValueKind, uint32_t SiteIdx,
859 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000860 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000861 if (!NV)
862 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000863
864 uint64_t Sum = 0;
865 std::unique_ptr<InstrProfValueData[]> VD =
866 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
867
Rong Xu311ada12016-03-30 16:56:31 +0000868 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
869 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000870}
871
872void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000873 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000874 uint64_t Sum, InstrProfValueKind ValueKind,
875 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000876 LLVMContext &Ctx = M.getContext();
877 MDBuilder MDHelper(Ctx);
878 SmallVector<Metadata *, 3> Vals;
879 // Tag
880 Vals.push_back(MDHelper.createString("VP"));
881 // Value Kind
882 Vals.push_back(MDHelper.createConstant(
883 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
884 // Total Count
885 Vals.push_back(
886 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
887
888 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000889 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000890 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000891 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000892 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000893 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000894 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000895 if (--MDCount == 0)
896 break;
897 }
898 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
899}
900
901bool getValueProfDataFromInst(const Instruction &Inst,
902 InstrProfValueKind ValueKind,
903 uint32_t MaxNumValueData,
904 InstrProfValueData ValueData[],
905 uint32_t &ActualNumValueData, uint64_t &TotalC) {
906 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
907 if (!MD)
908 return false;
909
910 unsigned NOps = MD->getNumOperands();
911
912 if (NOps < 5)
913 return false;
914
915 // Operand 0 is a string tag "VP":
916 MDString *Tag = cast<MDString>(MD->getOperand(0));
917 if (!Tag)
918 return false;
919
920 if (!Tag->getString().equals("VP"))
921 return false;
922
923 // Now check kind:
924 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
925 if (!KindInt)
926 return false;
927 if (KindInt->getZExtValue() != ValueKind)
928 return false;
929
930 // Get total count
931 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
932 if (!TotalCInt)
933 return false;
934 TotalC = TotalCInt->getZExtValue();
935
936 ActualNumValueData = 0;
937
938 for (unsigned I = 3; I < NOps; I += 2) {
939 if (ActualNumValueData >= MaxNumValueData)
940 break;
941 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
942 ConstantInt *Count =
943 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
944 if (!Value || !Count)
945 return false;
946 ValueData[ActualNumValueData].Value = Value->getZExtValue();
947 ValueData[ActualNumValueData].Count = Count->getZExtValue();
948 ActualNumValueData++;
949 }
950 return true;
951}
Rong Xu8e8fe852016-04-01 16:43:30 +0000952
Rong Xu92c2eae2016-04-01 20:15:04 +0000953MDNode *getPGOFuncNameMetadata(const Function &F) {
954 return F.getMetadata(getPGOFuncNameMetadataName());
955}
956
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000957void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
Rong Xuf8f051c2016-04-22 21:00:17 +0000958 // Only for internal linkage functions.
959 if (PGOFuncName == F.getName())
960 return;
961 // Don't create duplicated meta-data.
962 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000963 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000964 LLVMContext &C = F.getContext();
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000965 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
Rong Xu8e8fe852016-04-01 16:43:30 +0000966 F.setMetadata(getPGOFuncNameMetadataName(), N);
967}
968
Rong Xu97b68c52016-07-21 20:50:02 +0000969bool needsComdatForCounter(const Function &F, const Module &M) {
970 if (F.hasComdat())
971 return true;
972
973 Triple TT(M.getTargetTriple());
Dan Gohman1209c7a2017-01-17 20:34:09 +0000974 if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
Rong Xu97b68c52016-07-21 20:50:02 +0000975 return false;
976
977 // See createPGOFuncNameVar for more details. To avoid link errors, profile
978 // counters for function with available_externally linkage needs to be changed
979 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
980 // created. Without using comdat, duplicate entries won't be removed by the
981 // linker leading to increased data segement size and raw profile size. Even
982 // worse, since the referenced counter from profile per-function data object
983 // will be resolved to the common strong definition, the profile counts for
984 // available_externally functions will end up being duplicated in raw profile
985 // data. This can result in distorted profile as the counts of those dups
986 // will be accumulated by the profile merger.
987 GlobalValue::LinkageTypes Linkage = F.getLinkage();
988 if (Linkage != GlobalValue::ExternalWeakLinkage &&
989 Linkage != GlobalValue::AvailableExternallyLinkage)
990 return false;
991
992 return true;
993}
Rong Xu20f5df12017-01-11 20:19:41 +0000994
995// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
996bool isIRPGOFlagSet(const Module *M) {
997 auto IRInstrVar =
998 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
999 if (!IRInstrVar || IRInstrVar->isDeclaration() ||
1000 IRInstrVar->hasLocalLinkage())
1001 return false;
1002
1003 // Check if the flag is set.
1004 if (!IRInstrVar->hasInitializer())
1005 return false;
1006
1007 const Constant *InitVal = IRInstrVar->getInitializer();
1008 if (!InitVal)
1009 return false;
1010
1011 return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
1012 VARIANT_MASK_IR_PROF) != 0;
1013}
1014
1015// Check if we can safely rename this Comdat function.
1016bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
1017 if (F.getName().empty())
1018 return false;
1019 if (!needsComdatForCounter(F, *(F.getParent())))
1020 return false;
1021 // Unsafe to rename the address-taken function (which can be used in
1022 // function comparison).
1023 if (CheckAddressTaken && F.hasAddressTaken())
1024 return false;
1025 // Only safe to do if this function may be discarded if it is not used
1026 // in the compilation unit.
1027 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
1028 return false;
1029
1030 // For AvailableExternallyLinkage functions.
1031 if (!F.hasComdat()) {
1032 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
1033 return true;
1034 }
1035 return true;
1036}
Eugene Zelenkoe78d1312017-03-03 01:07:34 +00001037
Rong Xu48596b62017-04-04 16:42:20 +00001038// Parse the value profile options.
1039void getMemOPSizeRangeFromOption(std::string MemOPSizeRange,
1040 int64_t &RangeStart, int64_t &RangeLast) {
1041 static const int64_t DefaultMemOPSizeRangeStart = 0;
1042 static const int64_t DefaultMemOPSizeRangeLast = 8;
1043 RangeStart = DefaultMemOPSizeRangeStart;
1044 RangeLast = DefaultMemOPSizeRangeLast;
1045
1046 if (!MemOPSizeRange.empty()) {
1047 auto Pos = MemOPSizeRange.find(":");
1048 if (Pos != std::string::npos) {
1049 if (Pos > 0)
1050 RangeStart = atoi(MemOPSizeRange.substr(0, Pos).c_str());
1051 if (Pos < MemOPSizeRange.size() - 1)
1052 RangeLast = atoi(MemOPSizeRange.substr(Pos + 1).c_str());
1053 } else
1054 RangeLast = atoi(MemOPSizeRange.c_str());
1055 }
1056 assert(RangeLast >= RangeStart);
1057}
1058
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00001059} // end namespace llvm