blob: 0ec3fce4b2377da275fea8959ab7cacb730841af [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
139namespace llvm {
140
Vedant Kumar42369db2016-05-11 19:42:19 +0000141void SoftInstrProfErrors::addError(instrprof_error IE) {
142 if (IE == instrprof_error::success)
143 return;
144
145 if (FirstError == instrprof_error::success)
146 FirstError = IE;
147
148 switch (IE) {
149 case instrprof_error::hash_mismatch:
150 ++NumHashMismatches;
151 break;
152 case instrprof_error::count_mismatch:
153 ++NumCountMismatches;
154 break;
155 case instrprof_error::counter_overflow:
156 ++NumCounterOverflows;
157 break;
158 case instrprof_error::value_site_count_mismatch:
159 ++NumValueSiteCountMismatches;
160 break;
161 default:
162 llvm_unreachable("Not a soft error");
163 }
164}
165
Vedant Kumar9152fd12016-05-19 03:54:45 +0000166std::string InstrProfError::message() const {
167 return getInstrProfErrString(Err);
168}
169
170char InstrProfError::ID = 0;
171
Xinliang David Li441959d2015-11-09 00:01:22 +0000172std::string getPGOFuncName(StringRef RawFuncName,
173 GlobalValue::LinkageTypes Linkage,
Xinliang David Lia86545b2015-12-11 20:23:22 +0000174 StringRef FileName,
175 uint64_t Version LLVM_ATTRIBUTE_UNUSED) {
Teresa Johnsonb43027d2016-03-15 02:13:19 +0000176 return GlobalValue::getGlobalIdentifier(RawFuncName, Linkage, FileName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000177}
178
Rong Xua1a9f702017-02-25 00:00:36 +0000179// Strip NumPrefix level of directory name from PathNameStr. If the number of
180// directory separators is less than NumPrefix, strip all the directories and
181// leave base file name only.
182static StringRef stripDirPrefix(StringRef PathNameStr, uint32_t NumPrefix) {
183 uint32_t Count = NumPrefix;
184 uint32_t Pos = 0, LastPos = 0;
185 for (auto & CI : PathNameStr) {
186 ++Pos;
187 if (llvm::sys::path::is_separator(CI)) {
188 LastPos = Pos;
189 --Count;
190 }
191 if (Count == 0)
192 break;
193 }
194 return PathNameStr.substr(LastPos);
195}
196
Rong Xub5341662016-03-30 18:37:52 +0000197// Return the PGOFuncName. This function has some special handling when called
198// in LTO optimization. The following only applies when calling in LTO passes
199// (when \c InLTO is true): LTO's internalization privatizes many global linkage
200// symbols. This happens after value profile annotation, but those internal
201// linkage functions should not have a source prefix.
Teresa Johnson8c1bc982016-08-29 22:46:56 +0000202// Additionally, for ThinLTO mode, exported internal functions are promoted
203// and renamed. We need to ensure that the original internal PGO name is
204// used when computing the GUID that is compared against the profiled GUIDs.
Rong Xub5341662016-03-30 18:37:52 +0000205// To differentiate compiler generated internal symbols from original ones,
206// PGOFuncName meta data are created and attached to the original internal
207// symbols in the value profile annotation step
208// (PGOUseFunc::annotateIndirectCallSites). If a symbol does not have the meta
209// data, its original linkage must be non-internal.
210std::string getPGOFuncName(const Function &F, bool InLTO, uint64_t Version) {
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000211 if (!InLTO) {
212 StringRef FileName = (StaticFuncFullModulePrefix
213 ? F.getParent()->getName()
214 : sys::path::filename(F.getParent()->getName()));
Rong Xua1a9f702017-02-25 00:00:36 +0000215 if (StaticFuncFullModulePrefix && StaticFuncStripDirNamePrefix != 0)
216 FileName = stripDirPrefix(FileName, StaticFuncStripDirNamePrefix);
Xinliang David Li9eb472b2016-07-12 17:14:51 +0000217 return getPGOFuncName(F.getName(), F.getLinkage(), FileName, Version);
218 }
Rong Xub5341662016-03-30 18:37:52 +0000219
Rong Xu8e8fe852016-04-01 16:43:30 +0000220 // In LTO mode (when InLTO is true), first check if there is a meta data.
221 if (MDNode *MD = getPGOFuncNameMetadata(F)) {
Rong Xub5341662016-03-30 18:37:52 +0000222 StringRef S = cast<MDString>(MD->getOperand(0))->getString();
223 return S.str();
224 }
225
226 // If there is no meta data, the function must be a global before the value
227 // profile annotation pass. Its current linkage may be internal if it is
228 // internalized in LTO mode.
Rong Xu8e8fe852016-04-01 16:43:30 +0000229 return getPGOFuncName(F.getName(), GlobalValue::ExternalLinkage, "");
Xinliang David Li441959d2015-11-09 00:01:22 +0000230}
231
Xinliang David Li4ec40142015-12-15 19:44:45 +0000232StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName) {
233 if (FileName.empty())
Vedant Kumar43a85652016-03-28 15:49:08 +0000234 return PGOFuncName;
Xinliang David Li4ec40142015-12-15 19:44:45 +0000235 // Drop the file name including ':'. See also getPGOFuncName.
236 if (PGOFuncName.startswith(FileName))
237 PGOFuncName = PGOFuncName.drop_front(FileName.size() + 1);
238 return PGOFuncName;
239}
240
Xinliang David Lid1bab962015-12-12 17:28:03 +0000241// \p FuncName is the string used as profile lookup key for the function. A
242// symbol is created to hold the name. Return the legalized symbol name.
Vedant Kumaraa0cae62016-03-16 20:49:26 +0000243std::string getPGOFuncNameVarName(StringRef FuncName,
244 GlobalValue::LinkageTypes Linkage) {
Xinliang David Lid1bab962015-12-12 17:28:03 +0000245 std::string VarName = getInstrProfNameVarPrefix();
246 VarName += FuncName;
247
248 if (!GlobalValue::isLocalLinkage(Linkage))
249 return VarName;
250
251 // Now fix up illegal chars in local VarName that may upset the assembler.
Xinliang David Lieeaf0bc2016-06-10 06:32:26 +0000252 const char *InvalidChars = "-:<>/\"'";
Xinliang David Lid1bab962015-12-12 17:28:03 +0000253 size_t found = VarName.find_first_of(InvalidChars);
254 while (found != std::string::npos) {
255 VarName[found] = '_';
256 found = VarName.find_first_of(InvalidChars, found + 1);
257 }
258 return VarName;
259}
260
Xinliang David Li441959d2015-11-09 00:01:22 +0000261GlobalVariable *createPGOFuncNameVar(Module &M,
262 GlobalValue::LinkageTypes Linkage,
Xinliang David Li897d2922016-03-16 22:13:41 +0000263 StringRef PGOFuncName) {
Xinliang David Li441959d2015-11-09 00:01:22 +0000264 // We generally want to match the function's linkage, but available_externally
265 // and extern_weak both have the wrong semantics, and anything that doesn't
266 // need to link across compilation units doesn't need to be visible at all.
267 if (Linkage == GlobalValue::ExternalWeakLinkage)
268 Linkage = GlobalValue::LinkOnceAnyLinkage;
269 else if (Linkage == GlobalValue::AvailableExternallyLinkage)
270 Linkage = GlobalValue::LinkOnceODRLinkage;
271 else if (Linkage == GlobalValue::InternalLinkage ||
272 Linkage == GlobalValue::ExternalLinkage)
273 Linkage = GlobalValue::PrivateLinkage;
274
Xinliang David Li897d2922016-03-16 22:13:41 +0000275 auto *Value =
276 ConstantDataArray::getString(M.getContext(), PGOFuncName, false);
Xinliang David Li441959d2015-11-09 00:01:22 +0000277 auto FuncNameVar =
278 new GlobalVariable(M, Value->getType(), true, Linkage, Value,
Xinliang David Li897d2922016-03-16 22:13:41 +0000279 getPGOFuncNameVarName(PGOFuncName, Linkage));
Xinliang David Li441959d2015-11-09 00:01:22 +0000280
281 // Hide the symbol so that we correctly get a copy for each executable.
282 if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
283 FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);
284
285 return FuncNameVar;
286}
287
Xinliang David Li897d2922016-03-16 22:13:41 +0000288GlobalVariable *createPGOFuncNameVar(Function &F, StringRef PGOFuncName) {
289 return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), PGOFuncName);
Xinliang David Li441959d2015-11-09 00:01:22 +0000290}
Xinliang David Liee415892015-11-10 00:24:45 +0000291
Rong Xub5341662016-03-30 18:37:52 +0000292void InstrProfSymtab::create(Module &M, bool InLTO) {
293 for (Function &F : M) {
294 // Function may not have a name: like using asm("") to overwrite the name.
295 // Ignore in this case.
296 if (!F.hasName())
297 continue;
298 const std::string &PGOFuncName = getPGOFuncName(F, InLTO);
299 addFuncName(PGOFuncName);
Rong Xud5a57b52016-03-31 17:39:33 +0000300 MD5FuncMap.emplace_back(Function::getGUID(PGOFuncName), &F);
Dehao Chen4a435e02017-03-14 17:33:01 +0000301 // In ThinLTO, local function may have been promoted to global and have
302 // suffix added to the function name. We need to add the stripped function
303 // name to the symbol table so that we can find a match from profile.
304 if (InLTO) {
305 auto pos = PGOFuncName.find('.');
306 if (pos != std::string::npos) {
307 const std::string &OtherFuncName = PGOFuncName.substr(0, pos);
308 addFuncName(OtherFuncName);
309 MD5FuncMap.emplace_back(Function::getGUID(OtherFuncName), &F);
310 }
311 }
Rong Xub5341662016-03-30 18:37:52 +0000312 }
Xinliang David Li59411db2016-01-20 01:26:34 +0000313
314 finalizeSymtab();
315}
316
Vedant Kumar9152fd12016-05-19 03:54:45 +0000317Error collectPGOFuncNameStrings(const std::vector<std::string> &NameStrs,
318 bool doCompression, std::string &Result) {
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000319 assert(!NameStrs.empty() && "No name data to emit");
Vedant Kumar86705ba2016-03-28 21:06:42 +0000320
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000321 uint8_t Header[16], *P = Header;
Xinliang David Li0c677872016-01-04 21:31:09 +0000322 std::string UncompressedNameStrings =
Vedant Kumar86705ba2016-03-28 21:06:42 +0000323 join(NameStrs.begin(), NameStrs.end(), getInstrProfNameSeparator());
324
325 assert(StringRef(UncompressedNameStrings)
326 .count(getInstrProfNameSeparator()) == (NameStrs.size() - 1) &&
327 "PGO name is invalid (contains separator token)");
Xinliang David Li13ea29b2016-01-04 20:26:05 +0000328
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000329 unsigned EncLen = encodeULEB128(UncompressedNameStrings.length(), P);
330 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000331
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000332 auto WriteStringToResult = [&](size_t CompressedLen, StringRef InputStr) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000333 EncLen = encodeULEB128(CompressedLen, P);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000334 P += EncLen;
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000335 char *HeaderStr = reinterpret_cast<char *>(&Header[0]);
336 unsigned HeaderLen = P - &Header[0];
337 Result.append(HeaderStr, HeaderLen);
338 Result += InputStr;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000339 return Error::success();
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000340 };
341
Vedant Kumar9152fd12016-05-19 03:54:45 +0000342 if (!doCompression) {
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000343 return WriteStringToResult(0, UncompressedNameStrings);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000344 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000345
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000346 SmallString<128> CompressedNameStrings;
George Rimar167ca4a2017-01-17 15:45:07 +0000347 Error E = zlib::compress(StringRef(UncompressedNameStrings),
348 CompressedNameStrings, zlib::BestSizeCompression);
349 if (E) {
350 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000351 return make_error<InstrProfError>(instrprof_error::compress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000352 }
Xinliang David Li120fe2e2016-01-04 22:01:02 +0000353
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000354 return WriteStringToResult(CompressedNameStrings.size(),
355 CompressedNameStrings);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000356}
357
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000358StringRef getPGOFuncNameVarInitializer(GlobalVariable *NameVar) {
Xinliang David Li37c1fa02016-01-03 04:38:13 +0000359 auto *Arr = cast<ConstantDataArray>(NameVar->getInitializer());
360 StringRef NameStr =
361 Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
362 return NameStr;
363}
364
Vedant Kumar9152fd12016-05-19 03:54:45 +0000365Error collectPGOFuncNameStrings(const std::vector<GlobalVariable *> &NameVars,
366 std::string &Result, bool doCompression) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000367 std::vector<std::string> NameStrs;
368 for (auto *NameVar : NameVars) {
Xinliang David Lieb7d7f82016-02-04 23:59:09 +0000369 NameStrs.push_back(getPGOFuncNameVarInitializer(NameVar));
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000370 }
Xinliang David Li73163752016-01-26 23:13:00 +0000371 return collectPGOFuncNameStrings(
372 NameStrs, zlib::isAvailable() && doCompression, Result);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000373}
374
Vedant Kumar9152fd12016-05-19 03:54:45 +0000375Error readPGOFuncNameStrings(StringRef NameStrings, InstrProfSymtab &Symtab) {
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000376 const uint8_t *P = reinterpret_cast<const uint8_t *>(NameStrings.data());
377 const uint8_t *EndP = reinterpret_cast<const uint8_t *>(NameStrings.data() +
378 NameStrings.size());
379 while (P < EndP) {
380 uint32_t N;
381 uint64_t UncompressedSize = decodeULEB128(P, &N);
382 P += N;
383 uint64_t CompressedSize = decodeULEB128(P, &N);
384 P += N;
385 bool isCompressed = (CompressedSize != 0);
386 SmallString<128> UncompressedNameStrings;
387 StringRef NameStrings;
388 if (isCompressed) {
389 StringRef CompressedNameStrings(reinterpret_cast<const char *>(P),
390 CompressedSize);
George Rimar167ca4a2017-01-17 15:45:07 +0000391 if (Error E =
392 zlib::uncompress(CompressedNameStrings, UncompressedNameStrings,
393 UncompressedSize)) {
394 consumeError(std::move(E));
Vedant Kumar9152fd12016-05-19 03:54:45 +0000395 return make_error<InstrProfError>(instrprof_error::uncompress_failed);
George Rimar167ca4a2017-01-17 15:45:07 +0000396 }
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000397 P += CompressedSize;
398 NameStrings = StringRef(UncompressedNameStrings.data(),
399 UncompressedNameStrings.size());
400 } else {
401 NameStrings =
402 StringRef(reinterpret_cast<const char *>(P), UncompressedSize);
403 P += UncompressedSize;
404 }
405 // Now parse the name strings.
Xinliang David Li204efe22016-01-04 22:09:26 +0000406 SmallVector<StringRef, 0> Names;
Vedant Kumar86705ba2016-03-28 21:06:42 +0000407 NameStrings.split(Names, getInstrProfNameSeparator());
Xinliang David Li204efe22016-01-04 22:09:26 +0000408 for (StringRef &Name : Names)
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000409 Symtab.addFuncName(Name);
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000410
411 while (P < EndP && *P == 0)
412 P++;
413 }
414 Symtab.finalizeSymtab();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000415 return Error::success();
Xinliang David Lie413f1a2015-12-31 07:57:16 +0000416}
417
Vedant Kumar42369db2016-05-11 19:42:19 +0000418void InstrProfValueSiteRecord::merge(SoftInstrProfErrors &SIPE,
419 InstrProfValueSiteRecord &Input,
420 uint64_t Weight) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000421 this->sortByTargetValues();
422 Input.sortByTargetValues();
423 auto I = ValueData.begin();
424 auto IE = ValueData.end();
Xinliang David Li5c24da52015-12-20 05:15:45 +0000425 for (auto J = Input.ValueData.begin(), JE = Input.ValueData.end(); J != JE;
426 ++J) {
427 while (I != IE && I->Value < J->Value)
428 ++I;
429 if (I != IE && I->Value == J->Value) {
Xinliang David Li5c24da52015-12-20 05:15:45 +0000430 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000431 I->Count = SaturatingMultiplyAdd(J->Count, Weight, I->Count, &Overflowed);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000432 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000433 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li5c24da52015-12-20 05:15:45 +0000434 ++I;
435 continue;
436 }
437 ValueData.insert(I, *J);
438 }
Xinliang David Li5c24da52015-12-20 05:15:45 +0000439}
440
Vedant Kumar42369db2016-05-11 19:42:19 +0000441void InstrProfValueSiteRecord::scale(SoftInstrProfErrors &SIPE,
442 uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000443 for (auto I = ValueData.begin(), IE = ValueData.end(); I != IE; ++I) {
444 bool Overflowed;
445 I->Count = SaturatingMultiply(I->Count, Weight, &Overflowed);
446 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000447 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000448 }
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000449}
450
Xinliang David Li020f22d2015-12-18 23:06:37 +0000451// Merge Value Profile data from Src record to this record for ValueKind.
452// Scale merged value counts by \p Weight.
Vedant Kumar42369db2016-05-11 19:42:19 +0000453void InstrProfRecord::mergeValueProfData(uint32_t ValueKind,
454 InstrProfRecord &Src,
455 uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000456 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
457 uint32_t OtherNumValueSites = Src.getNumValueSites(ValueKind);
Vedant Kumar42369db2016-05-11 19:42:19 +0000458 if (ThisNumValueSites != OtherNumValueSites) {
459 SIPE.addError(instrprof_error::value_site_count_mismatch);
460 return;
461 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000462 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
463 getValueSitesForKind(ValueKind);
464 std::vector<InstrProfValueSiteRecord> &OtherSiteRecords =
465 Src.getValueSitesForKind(ValueKind);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000466 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000467 ThisSiteRecords[I].merge(SIPE, OtherSiteRecords[I], Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000468}
469
Vedant Kumar42369db2016-05-11 19:42:19 +0000470void InstrProfRecord::merge(InstrProfRecord &Other, uint64_t Weight) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000471 // If the number of counters doesn't match we either have bad data
472 // or a hash collision.
Vedant Kumar42369db2016-05-11 19:42:19 +0000473 if (Counts.size() != Other.Counts.size()) {
474 SIPE.addError(instrprof_error::count_mismatch);
475 return;
476 }
Xinliang David Li020f22d2015-12-18 23:06:37 +0000477
478 for (size_t I = 0, E = Other.Counts.size(); I < E; ++I) {
479 bool Overflowed;
Nathan Slingerland7bee3162016-01-12 22:34:00 +0000480 Counts[I] =
481 SaturatingMultiplyAdd(Other.Counts[I], Weight, Counts[I], &Overflowed);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000482 if (Overflowed)
Vedant Kumar42369db2016-05-11 19:42:19 +0000483 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000484 }
485
486 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000487 mergeValueProfData(Kind, Other, Weight);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000488}
Xinliang David Lia716cc52015-12-20 06:22:13 +0000489
Vedant Kumar42369db2016-05-11 19:42:19 +0000490void InstrProfRecord::scaleValueProfData(uint32_t ValueKind, uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000491 uint32_t ThisNumValueSites = getNumValueSites(ValueKind);
492 std::vector<InstrProfValueSiteRecord> &ThisSiteRecords =
493 getValueSitesForKind(ValueKind);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000494 for (uint32_t I = 0; I < ThisNumValueSites; I++)
Vedant Kumar42369db2016-05-11 19:42:19 +0000495 ThisSiteRecords[I].scale(SIPE, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000496}
497
Vedant Kumar42369db2016-05-11 19:42:19 +0000498void InstrProfRecord::scale(uint64_t Weight) {
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000499 for (auto &Count : this->Counts) {
500 bool Overflowed;
501 Count = SaturatingMultiply(Count, Weight, &Overflowed);
Vedant Kumar42369db2016-05-11 19:42:19 +0000502 if (Overflowed)
503 SIPE.addError(instrprof_error::counter_overflow);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000504 }
505 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
Vedant Kumar42369db2016-05-11 19:42:19 +0000506 scaleValueProfData(Kind, Weight);
Xinliang David Li51dc04c2016-01-08 03:49:59 +0000507}
508
Xinliang David Li020f22d2015-12-18 23:06:37 +0000509// Map indirect call target name hash to name string.
510uint64_t InstrProfRecord::remapValue(uint64_t Value, uint32_t ValueKind,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000511 ValueMapType *ValueMap) {
512 if (!ValueMap)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000513 return Value;
514 switch (ValueKind) {
515 case IPVK_IndirectCallTarget: {
516 auto Result =
Xinliang David Lia716cc52015-12-20 06:22:13 +0000517 std::lower_bound(ValueMap->begin(), ValueMap->end(), Value,
518 [](const std::pair<uint64_t, uint64_t> &LHS,
Xinliang David Li020f22d2015-12-18 23:06:37 +0000519 uint64_t RHS) { return LHS.first < RHS; });
Xinliang David Li8dd4ca82016-04-11 17:13:08 +0000520 // Raw function pointer collected by value profiler may be from
521 // external functions that are not instrumented. They won't have
522 // mapping data to be used by the deserializer. Force the value to
523 // be 0 in this case.
Xinliang David Li28464482016-04-10 03:32:02 +0000524 if (Result != ValueMap->end() && Result->first == Value)
Xinliang David Li020f22d2015-12-18 23:06:37 +0000525 Value = (uint64_t)Result->second;
Xinliang David Li28464482016-04-10 03:32:02 +0000526 else
527 Value = 0;
Xinliang David Li020f22d2015-12-18 23:06:37 +0000528 break;
529 }
530 }
531 return Value;
532}
533
Xinliang David Li020f22d2015-12-18 23:06:37 +0000534void InstrProfRecord::addValueData(uint32_t ValueKind, uint32_t Site,
535 InstrProfValueData *VData, uint32_t N,
Xinliang David Lia716cc52015-12-20 06:22:13 +0000536 ValueMapType *ValueMap) {
Xinliang David Li020f22d2015-12-18 23:06:37 +0000537 for (uint32_t I = 0; I < N; I++) {
Xinliang David Lia716cc52015-12-20 06:22:13 +0000538 VData[I].Value = remapValue(VData[I].Value, ValueKind, ValueMap);
Xinliang David Li020f22d2015-12-18 23:06:37 +0000539 }
540 std::vector<InstrProfValueSiteRecord> &ValueSites =
541 getValueSitesForKind(ValueKind);
542 if (N == 0)
Vedant Kumar6b22ba62016-05-11 16:03:02 +0000543 ValueSites.emplace_back();
Xinliang David Li020f22d2015-12-18 23:06:37 +0000544 else
545 ValueSites.emplace_back(VData, VData + N);
546}
547
Xinliang David Lib75544a2015-11-28 19:07:09 +0000548#define INSTR_PROF_COMMON_API_IMPL
549#include "llvm/ProfileData/InstrProfData.inc"
Xinliang David Liee415892015-11-10 00:24:45 +0000550
Xinliang David Li020f22d2015-12-18 23:06:37 +0000551/*!
Xinliang David Lib75544a2015-11-28 19:07:09 +0000552 * \brief ValueProfRecordClosure Interface implementation for InstrProfRecord
Xinliang David Lied966772015-11-25 23:31:18 +0000553 * class. These C wrappers are used as adaptors so that C++ code can be
554 * invoked as callbacks.
555 */
Xinliang David Lif47cf552015-11-25 06:23:38 +0000556uint32_t getNumValueKindsInstrProf(const void *Record) {
557 return reinterpret_cast<const InstrProfRecord *>(Record)->getNumValueKinds();
558}
559
560uint32_t getNumValueSitesInstrProf(const void *Record, uint32_t VKind) {
561 return reinterpret_cast<const InstrProfRecord *>(Record)
562 ->getNumValueSites(VKind);
563}
564
565uint32_t getNumValueDataInstrProf(const void *Record, uint32_t VKind) {
566 return reinterpret_cast<const InstrProfRecord *>(Record)
567 ->getNumValueData(VKind);
568}
569
570uint32_t getNumValueDataForSiteInstrProf(const void *R, uint32_t VK,
571 uint32_t S) {
572 return reinterpret_cast<const InstrProfRecord *>(R)
573 ->getNumValueDataForSite(VK, S);
574}
575
576void getValueForSiteInstrProf(const void *R, InstrProfValueData *Dst,
Xinliang David Li1e4c8092016-02-04 05:29:51 +0000577 uint32_t K, uint32_t S) {
578 reinterpret_cast<const InstrProfRecord *>(R)->getValueForSite(Dst, K, S);
Xinliang David Lie8092312015-11-25 19:13:00 +0000579}
580
Xinliang David Lif47cf552015-11-25 06:23:38 +0000581ValueProfData *allocValueProfDataInstrProf(size_t TotalSizeInBytes) {
Xinliang David Li38b9a322015-12-15 21:57:08 +0000582 ValueProfData *VD =
583 (ValueProfData *)(new (::operator new(TotalSizeInBytes)) ValueProfData());
584 memset(VD, 0, TotalSizeInBytes);
585 return VD;
Xinliang David Lif47cf552015-11-25 06:23:38 +0000586}
587
588static ValueProfRecordClosure InstrProfRecordClosure = {
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000589 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000590 getNumValueKindsInstrProf,
591 getNumValueSitesInstrProf,
592 getNumValueDataInstrProf,
593 getNumValueDataForSiteInstrProf,
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000594 nullptr,
Xinliang David Lif47cf552015-11-25 06:23:38 +0000595 getValueForSiteInstrProf,
Xinliang David Li38b9a322015-12-15 21:57:08 +0000596 allocValueProfDataInstrProf};
Xinliang David Lif47cf552015-11-25 06:23:38 +0000597
Xinliang David Lie8092312015-11-25 19:13:00 +0000598// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000599uint32_t ValueProfData::getSize(const InstrProfRecord &Record) {
600 InstrProfRecordClosure.Record = &Record;
601 return getValueProfDataSize(&InstrProfRecordClosure);
602}
603
Xinliang David Lie8092312015-11-25 19:13:00 +0000604// Wrapper implementation using the closure mechanism.
Xinliang David Lif47cf552015-11-25 06:23:38 +0000605std::unique_ptr<ValueProfData>
606ValueProfData::serializeFrom(const InstrProfRecord &Record) {
607 InstrProfRecordClosure.Record = &Record;
608
609 std::unique_ptr<ValueProfData> VPD(
Xinliang David Li0e6a36e2015-12-01 19:47:32 +0000610 serializeValueProfDataFrom(&InstrProfRecordClosure, nullptr));
Xinliang David Lif47cf552015-11-25 06:23:38 +0000611 return VPD;
612}
613
Xinliang David Lie8092312015-11-25 19:13:00 +0000614void ValueProfRecord::deserializeTo(InstrProfRecord &Record,
615 InstrProfRecord::ValueMapType *VMap) {
616 Record.reserveSites(Kind, NumValueSites);
617
618 InstrProfValueData *ValueData = getValueProfRecordValueData(this);
619 for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {
620 uint8_t ValueDataCount = this->SiteCountArray[VSite];
621 Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);
622 ValueData += ValueDataCount;
623 }
624}
Xinliang David Lied966772015-11-25 23:31:18 +0000625
Xinliang David Lie8092312015-11-25 19:13:00 +0000626// For writing/serializing, Old is the host endianness, and New is
627// byte order intended on disk. For Reading/deserialization, Old
628// is the on-disk source endianness, and New is the host endianness.
629void ValueProfRecord::swapBytes(support::endianness Old,
630 support::endianness New) {
631 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000632
Xinliang David Lie8092312015-11-25 19:13:00 +0000633 if (Old == New)
634 return;
635
636 if (getHostEndianness() != Old) {
637 sys::swapByteOrder<uint32_t>(NumValueSites);
638 sys::swapByteOrder<uint32_t>(Kind);
639 }
640 uint32_t ND = getValueProfRecordNumValueData(this);
641 InstrProfValueData *VD = getValueProfRecordValueData(this);
642
643 // No need to swap byte array: SiteCountArrray.
644 for (uint32_t I = 0; I < ND; I++) {
645 sys::swapByteOrder<uint64_t>(VD[I].Value);
646 sys::swapByteOrder<uint64_t>(VD[I].Count);
647 }
648 if (getHostEndianness() == Old) {
649 sys::swapByteOrder<uint32_t>(NumValueSites);
650 sys::swapByteOrder<uint32_t>(Kind);
651 }
652}
653
654void ValueProfData::deserializeTo(InstrProfRecord &Record,
655 InstrProfRecord::ValueMapType *VMap) {
656 if (NumValueKinds == 0)
657 return;
658
659 ValueProfRecord *VR = getFirstValueProfRecord(this);
660 for (uint32_t K = 0; K < NumValueKinds; K++) {
661 VR->deserializeTo(Record, VMap);
662 VR = getValueProfRecordNext(VR);
663 }
664}
665
666template <class T>
667static T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {
668 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000669
Xinliang David Lie8092312015-11-25 19:13:00 +0000670 if (Orig == little)
671 return endian::readNext<T, little, unaligned>(D);
672 else
673 return endian::readNext<T, big, unaligned>(D);
674}
675
676static std::unique_ptr<ValueProfData> allocValueProfData(uint32_t TotalSize) {
677 return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))
678 ValueProfData());
679}
680
Vedant Kumar9152fd12016-05-19 03:54:45 +0000681Error ValueProfData::checkIntegrity() {
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000682 if (NumValueKinds > IPVK_Last + 1)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000683 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000684 // Total size needs to be mulltiple of quadword size.
685 if (TotalSize % sizeof(uint64_t))
Vedant Kumar9152fd12016-05-19 03:54:45 +0000686 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000687
688 ValueProfRecord *VR = getFirstValueProfRecord(this);
689 for (uint32_t K = 0; K < this->NumValueKinds; K++) {
690 if (VR->Kind > IPVK_Last)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000691 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000692 VR = getValueProfRecordNext(VR);
693 if ((char *)VR - (char *)this > (ptrdiff_t)TotalSize)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000694 return make_error<InstrProfError>(instrprof_error::malformed);
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000695 }
Vedant Kumar9152fd12016-05-19 03:54:45 +0000696 return Error::success();
Xinliang David Li8e32f4d2015-11-28 04:56:07 +0000697}
698
Vedant Kumar9152fd12016-05-19 03:54:45 +0000699Expected<std::unique_ptr<ValueProfData>>
Xinliang David Liee415892015-11-10 00:24:45 +0000700ValueProfData::getValueProfData(const unsigned char *D,
701 const unsigned char *const BufferEnd,
702 support::endianness Endianness) {
703 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000704
Xinliang David Liee415892015-11-10 00:24:45 +0000705 if (D + sizeof(ValueProfData) > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000706 return make_error<InstrProfError>(instrprof_error::truncated);
Xinliang David Liee415892015-11-10 00:24:45 +0000707
Xinliang David Lib8c3ad12015-11-17 03:47:21 +0000708 const unsigned char *Header = D;
709 uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);
Xinliang David Liee415892015-11-10 00:24:45 +0000710 if (D + TotalSize > BufferEnd)
Vedant Kumar9152fd12016-05-19 03:54:45 +0000711 return make_error<InstrProfError>(instrprof_error::too_large);
Xinliang David Liee415892015-11-10 00:24:45 +0000712
Xinliang David Lif47cf552015-11-25 06:23:38 +0000713 std::unique_ptr<ValueProfData> VPD = allocValueProfData(TotalSize);
Xinliang David Liee415892015-11-10 00:24:45 +0000714 memcpy(VPD.get(), D, TotalSize);
715 // Byte swap.
716 VPD->swapBytesToHost(Endianness);
717
Vedant Kumar9152fd12016-05-19 03:54:45 +0000718 Error E = VPD->checkIntegrity();
719 if (E)
720 return std::move(E);
Xinliang David Liee415892015-11-10 00:24:45 +0000721
Xinliang David Liee415892015-11-10 00:24:45 +0000722 return std::move(VPD);
723}
724
725void ValueProfData::swapBytesToHost(support::endianness Endianness) {
726 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000727
Xinliang David Liee415892015-11-10 00:24:45 +0000728 if (Endianness == getHostEndianness())
729 return;
730
731 sys::swapByteOrder<uint32_t>(TotalSize);
732 sys::swapByteOrder<uint32_t>(NumValueKinds);
733
Xinliang David Lif47cf552015-11-25 06:23:38 +0000734 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000735 for (uint32_t K = 0; K < NumValueKinds; K++) {
736 VR->swapBytes(Endianness, getHostEndianness());
Xinliang David Liac5b8602015-11-25 04:29:24 +0000737 VR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000738 }
739}
740
741void ValueProfData::swapBytesFromHost(support::endianness Endianness) {
742 using namespace support;
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000743
Xinliang David Liee415892015-11-10 00:24:45 +0000744 if (Endianness == getHostEndianness())
745 return;
746
Xinliang David Lif47cf552015-11-25 06:23:38 +0000747 ValueProfRecord *VR = getFirstValueProfRecord(this);
Xinliang David Liee415892015-11-10 00:24:45 +0000748 for (uint32_t K = 0; K < NumValueKinds; K++) {
Xinliang David Liac5b8602015-11-25 04:29:24 +0000749 ValueProfRecord *NVR = getValueProfRecordNext(VR);
Xinliang David Liee415892015-11-10 00:24:45 +0000750 VR->swapBytes(getHostEndianness(), Endianness);
751 VR = NVR;
752 }
753 sys::swapByteOrder<uint32_t>(TotalSize);
754 sys::swapByteOrder<uint32_t>(NumValueKinds);
755}
Xinliang David Lie8092312015-11-25 19:13:00 +0000756
Xinliang David Li402477d2016-02-04 19:11:43 +0000757void annotateValueSite(Module &M, Instruction &Inst,
758 const InstrProfRecord &InstrProfR,
Rong Xu69683f12016-02-10 22:19:43 +0000759 InstrProfValueKind ValueKind, uint32_t SiteIdx,
760 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000761 uint32_t NV = InstrProfR.getNumValueDataForSite(ValueKind, SiteIdx);
Betul Buyukkurt4f1e8c92016-04-14 16:25:45 +0000762 if (!NV)
763 return;
Xinliang David Li402477d2016-02-04 19:11:43 +0000764
765 uint64_t Sum = 0;
766 std::unique_ptr<InstrProfValueData[]> VD =
767 InstrProfR.getValueForSite(ValueKind, SiteIdx, &Sum);
768
Rong Xu311ada12016-03-30 16:56:31 +0000769 ArrayRef<InstrProfValueData> VDs(VD.get(), NV);
770 annotateValueSite(M, Inst, VDs, Sum, ValueKind, MaxMDCount);
Rong Xubb494902016-02-12 21:36:17 +0000771}
772
773void annotateValueSite(Module &M, Instruction &Inst,
Rong Xu311ada12016-03-30 16:56:31 +0000774 ArrayRef<InstrProfValueData> VDs,
Rong Xubb494902016-02-12 21:36:17 +0000775 uint64_t Sum, InstrProfValueKind ValueKind,
776 uint32_t MaxMDCount) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000777 LLVMContext &Ctx = M.getContext();
778 MDBuilder MDHelper(Ctx);
779 SmallVector<Metadata *, 3> Vals;
780 // Tag
781 Vals.push_back(MDHelper.createString("VP"));
782 // Value Kind
783 Vals.push_back(MDHelper.createConstant(
784 ConstantInt::get(Type::getInt32Ty(Ctx), ValueKind)));
785 // Total Count
786 Vals.push_back(
787 MDHelper.createConstant(ConstantInt::get(Type::getInt64Ty(Ctx), Sum)));
788
789 // Value Profile Data
Rong Xu69683f12016-02-10 22:19:43 +0000790 uint32_t MDCount = MaxMDCount;
Rong Xu311ada12016-03-30 16:56:31 +0000791 for (auto &VD : VDs) {
Xinliang David Li402477d2016-02-04 19:11:43 +0000792 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000793 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Value)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000794 Vals.push_back(MDHelper.createConstant(
Rong Xu311ada12016-03-30 16:56:31 +0000795 ConstantInt::get(Type::getInt64Ty(Ctx), VD.Count)));
Xinliang David Li402477d2016-02-04 19:11:43 +0000796 if (--MDCount == 0)
797 break;
798 }
799 Inst.setMetadata(LLVMContext::MD_prof, MDNode::get(Ctx, Vals));
800}
801
802bool getValueProfDataFromInst(const Instruction &Inst,
803 InstrProfValueKind ValueKind,
804 uint32_t MaxNumValueData,
805 InstrProfValueData ValueData[],
806 uint32_t &ActualNumValueData, uint64_t &TotalC) {
807 MDNode *MD = Inst.getMetadata(LLVMContext::MD_prof);
808 if (!MD)
809 return false;
810
811 unsigned NOps = MD->getNumOperands();
812
813 if (NOps < 5)
814 return false;
815
816 // Operand 0 is a string tag "VP":
817 MDString *Tag = cast<MDString>(MD->getOperand(0));
818 if (!Tag)
819 return false;
820
821 if (!Tag->getString().equals("VP"))
822 return false;
823
824 // Now check kind:
825 ConstantInt *KindInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
826 if (!KindInt)
827 return false;
828 if (KindInt->getZExtValue() != ValueKind)
829 return false;
830
831 // Get total count
832 ConstantInt *TotalCInt = mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
833 if (!TotalCInt)
834 return false;
835 TotalC = TotalCInt->getZExtValue();
836
837 ActualNumValueData = 0;
838
839 for (unsigned I = 3; I < NOps; I += 2) {
840 if (ActualNumValueData >= MaxNumValueData)
841 break;
842 ConstantInt *Value = mdconst::dyn_extract<ConstantInt>(MD->getOperand(I));
843 ConstantInt *Count =
844 mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1));
845 if (!Value || !Count)
846 return false;
847 ValueData[ActualNumValueData].Value = Value->getZExtValue();
848 ValueData[ActualNumValueData].Count = Count->getZExtValue();
849 ActualNumValueData++;
850 }
851 return true;
852}
Rong Xu8e8fe852016-04-01 16:43:30 +0000853
Rong Xu92c2eae2016-04-01 20:15:04 +0000854MDNode *getPGOFuncNameMetadata(const Function &F) {
855 return F.getMetadata(getPGOFuncNameMetadataName());
856}
857
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000858void createPGOFuncNameMetadata(Function &F, StringRef PGOFuncName) {
Rong Xuf8f051c2016-04-22 21:00:17 +0000859 // Only for internal linkage functions.
860 if (PGOFuncName == F.getName())
861 return;
862 // Don't create duplicated meta-data.
863 if (getPGOFuncNameMetadata(F))
Rong Xu8e8fe852016-04-01 16:43:30 +0000864 return;
Rong Xu8e8fe852016-04-01 16:43:30 +0000865 LLVMContext &C = F.getContext();
Benjamin Kramer0da23a22016-05-29 10:31:00 +0000866 MDNode *N = MDNode::get(C, MDString::get(C, PGOFuncName));
Rong Xu8e8fe852016-04-01 16:43:30 +0000867 F.setMetadata(getPGOFuncNameMetadataName(), N);
868}
869
Rong Xu97b68c52016-07-21 20:50:02 +0000870bool needsComdatForCounter(const Function &F, const Module &M) {
871 if (F.hasComdat())
872 return true;
873
874 Triple TT(M.getTargetTriple());
Dan Gohman1209c7a2017-01-17 20:34:09 +0000875 if (!TT.isOSBinFormatELF() && !TT.isOSBinFormatWasm())
Rong Xu97b68c52016-07-21 20:50:02 +0000876 return false;
877
878 // See createPGOFuncNameVar for more details. To avoid link errors, profile
879 // counters for function with available_externally linkage needs to be changed
880 // to linkonce linkage. On ELF based systems, this leads to weak symbols to be
881 // created. Without using comdat, duplicate entries won't be removed by the
882 // linker leading to increased data segement size and raw profile size. Even
883 // worse, since the referenced counter from profile per-function data object
884 // will be resolved to the common strong definition, the profile counts for
885 // available_externally functions will end up being duplicated in raw profile
886 // data. This can result in distorted profile as the counts of those dups
887 // will be accumulated by the profile merger.
888 GlobalValue::LinkageTypes Linkage = F.getLinkage();
889 if (Linkage != GlobalValue::ExternalWeakLinkage &&
890 Linkage != GlobalValue::AvailableExternallyLinkage)
891 return false;
892
893 return true;
894}
Rong Xu20f5df12017-01-11 20:19:41 +0000895
896// Check if INSTR_PROF_RAW_VERSION_VAR is defined.
897bool isIRPGOFlagSet(const Module *M) {
898 auto IRInstrVar =
899 M->getNamedGlobal(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
900 if (!IRInstrVar || IRInstrVar->isDeclaration() ||
901 IRInstrVar->hasLocalLinkage())
902 return false;
903
904 // Check if the flag is set.
905 if (!IRInstrVar->hasInitializer())
906 return false;
907
908 const Constant *InitVal = IRInstrVar->getInitializer();
909 if (!InitVal)
910 return false;
911
912 return (dyn_cast<ConstantInt>(InitVal)->getZExtValue() &
913 VARIANT_MASK_IR_PROF) != 0;
914}
915
916// Check if we can safely rename this Comdat function.
917bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken) {
918 if (F.getName().empty())
919 return false;
920 if (!needsComdatForCounter(F, *(F.getParent())))
921 return false;
922 // Unsafe to rename the address-taken function (which can be used in
923 // function comparison).
924 if (CheckAddressTaken && F.hasAddressTaken())
925 return false;
926 // Only safe to do if this function may be discarded if it is not used
927 // in the compilation unit.
928 if (!GlobalValue::isDiscardableIfUnused(F.getLinkage()))
929 return false;
930
931 // For AvailableExternallyLinkage functions.
932 if (!F.hasComdat()) {
933 assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
934 return true;
935 }
936 return true;
937}
Eugene Zelenkoe78d1312017-03-03 01:07:34 +0000938
Rong Xu48596b62017-04-04 16:42:20 +0000939// Parse the value profile options.
940void getMemOPSizeRangeFromOption(std::string MemOPSizeRange,
941 int64_t &RangeStart, int64_t &RangeLast) {
942 static const int64_t DefaultMemOPSizeRangeStart = 0;
943 static const int64_t DefaultMemOPSizeRangeLast = 8;
944 RangeStart = DefaultMemOPSizeRangeStart;
945 RangeLast = DefaultMemOPSizeRangeLast;
946
947 if (!MemOPSizeRange.empty()) {
948 auto Pos = MemOPSizeRange.find(":");
949 if (Pos != std::string::npos) {
950 if (Pos > 0)
951 RangeStart = atoi(MemOPSizeRange.substr(0, Pos).c_str());
952 if (Pos < MemOPSizeRange.size() - 1)
953 RangeLast = atoi(MemOPSizeRange.substr(Pos + 1).c_str());
954 } else
955 RangeLast = atoi(MemOPSizeRange.c_str());
956 }
957 assert(RangeLast >= RangeStart);
958}
959
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000960} // end namespace llvm