Debian Codegraph @

clang/lib/CodeGen/CodeGenPGO.cpp

raw
1 //===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Instrumentation-based profile-guided optimization
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "CodeGenPGO.h"
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CoverageMappingGen.h"
17 #include "clang/AST/RecursiveASTVisitor.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/DiagnosticFrontend.h"
20 #include "llvm/IR/Intrinsics.h"
21 #include "llvm/IR/MDBuilder.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/MD5.h"
25 #include <optional>
26
27 namespace llvm {
28 extern cl::opt<bool> EnableSingleByteCoverage;
29 } // namespace llvm
30
31 static llvm::cl::opt<bool>
32 EnableValueProfiling("enable-value-profiling",
33 llvm::cl::desc("Enable value profiling"),
34 llvm::cl::Hidden, llvm::cl::init(false));
35
36 using namespace clang;
37 using namespace CodeGen;
38
39 void CodeGenPGO::setFuncName(StringRef Name,
40 llvm::GlobalValue::LinkageTypes Linkage) {
41 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
42 FuncName = llvm::getPGOFuncName(
43 Name, Linkage, CGM.getCodeGenOpts().MainFileName,
44 PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
45
46 // If we're generating a profile, create a variable for the name.
47 if (CGM.getCodeGenOpts().hasProfileClangInstr())
48 FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
49 }
50
51 void CodeGenPGO::setFuncName(llvm::Function *Fn) {
52 setFuncName(Fn->getName(), Fn->getLinkage());
53 // Create PGOFuncName meta data.
54 llvm::createPGOFuncNameMetadata(*Fn, FuncName);
55 }
56
57 /// The version of the PGO hash algorithm.
58 enum PGOHashVersion : unsigned {
59 PGO_HASH_V1,
60 PGO_HASH_V2,
61 PGO_HASH_V3,
62 PGO_HASH_V4,
63
64 // Keep this set to the latest hash version.
65 PGO_HASH_LATEST = PGO_HASH_V4
66 };
67
68 namespace {
69 /// Stable hasher for PGO region counters.
70 ///
71 /// PGOHash produces a stable hash of a given function's control flow.
72 ///
73 /// Changing the output of this hash will invalidate all previously generated
74 /// profiles -- i.e., don't do it.
75 ///
76 /// \note When this hash does eventually change (years?), we still need to
77 /// support old hashes. We'll need to pull in the version number from the
78 /// profile data format and use the matching hash function.
79 class PGOHash {
80 uint64_t Working;
81 unsigned Count;
82 PGOHashVersion HashVersion;
83 llvm::MD5 MD5;
84
85 static const int NumBitsPerType = 6;
86 static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
87 static const unsigned TooBig = 1u << NumBitsPerType;
88
89 public:
90 /// Hash values for AST nodes.
91 ///
92 /// Distinct values for AST nodes that have region counters attached.
93 ///
94 /// These values must be stable. All new members must be added at the end,
95 /// and no members should be removed. Changing the enumeration value for an
96 /// AST node will affect the hash of every function that contains that node.
97 enum HashType : unsigned char {
98 None = 0,
99 LabelStmt = 1,
100 WhileStmt,
101 DoStmt,
102 ForStmt,
103 CXXForRangeStmt,
104 ObjCForCollectionStmt,
105 SwitchStmt,
106 CaseStmt,
107 DefaultStmt,
108 IfStmt,
109 CXXTryStmt,
110 CXXCatchStmt,
111 ConditionalOperator,
112 BinaryOperatorLAnd,
113 BinaryOperatorLOr,
114 BinaryConditionalOperator,
115 // The preceding values are available with PGO_HASH_V1.
116
117 EndOfScope,
118 IfThenBranch,
119 IfElseBranch,
120 GotoStmt,
121 IndirectGotoStmt,
122 BreakStmt,
123 ContinueStmt,
124 ReturnStmt,
125 ThrowExpr,
126 UnaryOperatorLNot,
127 BinaryOperatorLT,
128 BinaryOperatorGT,
129 BinaryOperatorLE,
130 BinaryOperatorGE,
131 BinaryOperatorEQ,
132 BinaryOperatorNE,
133 // The preceding values are available since PGO_HASH_V2.
134
135 // Keep this last. It's for the static assert that follows.
136 LastHashType
137 };
138 static_assert(LastHashType <= TooBig, "Too many types in HashType");
139
140 PGOHash(PGOHashVersion HashVersion)
141 : Working(0), Count(0), HashVersion(HashVersion) {}
142 void combine(HashType Type);
143 uint64_t finalize();
144 PGOHashVersion getHashVersion() const { return HashVersion; }
145 };
146 const int PGOHash::NumBitsPerType;
147 const unsigned PGOHash::NumTypesPerWord;
148 const unsigned PGOHash::TooBig;
149
150 /// Get the PGO hash version used in the given indexed profile.
151 static PGOHashVersion getPGOHashVersion(llvm::IndexedInstrProfReader *PGOReader,
152 CodeGenModule &CGM) {
153 if (PGOReader->getVersion() <= 4)
154 return PGO_HASH_V1;
155 if (PGOReader->getVersion() <= 5)
156 return PGO_HASH_V2;
157 if (PGOReader->getVersion() <= 12)
158 return PGO_HASH_V3;
159 return PGO_HASH_V4;
160 }
161
162 /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
163 struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
164 using Base = RecursiveASTVisitor<MapRegionCounters>;
165
166 /// The next counter value to assign.
167 unsigned NextCounter;
168 /// The function hash.
169 PGOHash Hash;
170 /// The map of statements to counters.
171 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap;
172 /// The state of MC/DC Coverage in this function.
173 MCDC::State &MCDCState;
174 /// Maximum number of supported MC/DC conditions in a boolean expression.
175 unsigned MCDCMaxCond;
176 /// The profile version.
177 uint64_t ProfileVersion;
178 /// Diagnostics Engine used to report warnings.
179 DiagnosticsEngine &Diag;
180
181 MapRegionCounters(PGOHashVersion HashVersion, uint64_t ProfileVersion,
182 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap,
183 MCDC::State &MCDCState, unsigned MCDCMaxCond,
184 DiagnosticsEngine &Diag)
185 : NextCounter(0), Hash(HashVersion), CounterMap(CounterMap),
186 MCDCState(MCDCState), MCDCMaxCond(MCDCMaxCond),
187 ProfileVersion(ProfileVersion), Diag(Diag) {}
188
189 // Blocks and lambdas are handled as separate functions, so we need not
190 // traverse them in the parent context.
191 bool TraverseBlockExpr(BlockExpr *BE) { return true; }
192 bool TraverseLambdaExpr(LambdaExpr *LE) {
193 // Traverse the captures, but not the body.
194 for (auto C : zip(LE->captures(), LE->capture_inits()))
195 TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
196 return true;
197 }
198 bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
199
200 bool VisitDecl(const Decl *D) {
201 switch (D->getKind()) {
202 default:
203 break;
204 case Decl::Function:
205 case Decl::CXXMethod:
206 case Decl::CXXConstructor:
207 case Decl::CXXDestructor:
208 case Decl::CXXConversion:
209 case Decl::ObjCMethod:
210 case Decl::Block:
211 case Decl::Captured:
212 CounterMap[D->getBody()] = NextCounter++;
213 break;
214 }
215 return true;
216 }
217
218 /// If \p S gets a fresh counter, update the counter mappings. Return the
219 /// V1 hash of \p S.
220 PGOHash::HashType updateCounterMappings(Stmt *S) {
221 auto Type = getHashType(PGO_HASH_V1, S);
222 if (Type != PGOHash::None)
223 CounterMap[S] = NextCounter++;
224 return Type;
225 }
226
227 /// The following stacks are used with dataTraverseStmtPre() and
228 /// dataTraverseStmtPost() to track the depth of nested logical operators in a
229 /// boolean expression in a function. The ultimate purpose is to keep track
230 /// of the number of leaf-level conditions in the boolean expression so that a
231 /// profile bitmap can be allocated based on that number.
232 ///
233 /// The stacks are also used to find error cases and notify the user. A
234 /// standard logical operator nest for a boolean expression could be in a form
235 /// similar to this: "x = a && b && c && (d || f)"
236 unsigned NumCond = 0;
237 bool SplitNestedLogicalOp = false;
238 SmallVector<const Stmt *, 16> NonLogOpStack;
239 SmallVector<const BinaryOperator *, 16> LogOpStack;
240
241 // Hook: dataTraverseStmtPre() is invoked prior to visiting an AST Stmt node.
242 bool dataTraverseStmtPre(Stmt *S) {
243 /// If MC/DC is not enabled, MCDCMaxCond will be set to 0. Do nothing.
244 if (MCDCMaxCond == 0)
245 return true;
246
247 /// At the top of the logical operator nest, reset the number of conditions,
248 /// also forget previously seen split nesting cases.
249 if (LogOpStack.empty()) {
250 NumCond = 0;
251 SplitNestedLogicalOp = false;
252 }
253
254 if (const Expr *E = dyn_cast<Expr>(S)) {
255 if (const auto *BinOp =
256 dyn_cast<BinaryOperator>(CodeGenFunction::stripCond(E));
257 BinOp && BinOp->isLogicalOp()) {
258 /// Check for "split-nested" logical operators. This happens when a new
259 /// boolean expression logical-op nest is encountered within an existing
260 /// boolean expression, separated by a non-logical operator. For
261 /// example, in "x = (a && b && c && foo(d && f))", the "d && f" case
262 /// starts a new boolean expression that is separated from the other
263 /// conditions by the operator foo(). Split-nested cases are not
264 /// supported by MC/DC.
265 SplitNestedLogicalOp = SplitNestedLogicalOp || !NonLogOpStack.empty();
266
267 LogOpStack.push_back(BinOp);
268 return true;
269 }
270 }
271
272 /// Keep track of non-logical operators. These are OK as long as we don't
273 /// encounter a new logical operator after seeing one.
274 if (!LogOpStack.empty())
275 NonLogOpStack.push_back(S);
276
277 return true;
278 }
279
280 // Hook: dataTraverseStmtPost() is invoked by the AST visitor after visiting
281 // an AST Stmt node. MC/DC will use it to to signal when the top of a
282 // logical operation (boolean expression) nest is encountered.
283 bool dataTraverseStmtPost(Stmt *S) {
284 /// If MC/DC is not enabled, MCDCMaxCond will be set to 0. Do nothing.
285 if (MCDCMaxCond == 0)
286 return true;
287
288 if (const Expr *E = dyn_cast<Expr>(S)) {
289 const BinaryOperator *BinOp =
290 dyn_cast<BinaryOperator>(CodeGenFunction::stripCond(E));
291 if (BinOp && BinOp->isLogicalOp()) {
292 assert(LogOpStack.back() == BinOp);
293 LogOpStack.pop_back();
294
295 /// At the top of logical operator nest:
296 if (LogOpStack.empty()) {
297 /// Was the "split-nested" logical operator case encountered?
298 if (SplitNestedLogicalOp) {
299 Diag.Report(S->getBeginLoc(), diag::warn_pgo_nested_boolean_expr);
300 return true;
301 }
302
303 /// Was the maximum number of conditions encountered?
304 if (NumCond > MCDCMaxCond) {
305 Diag.Report(S->getBeginLoc(), diag::warn_pgo_condition_limit)
306 << NumCond << MCDCMaxCond;
307 return true;
308 }
309
310 // Otherwise, allocate the Decision.
311 MCDCState.DecisionByStmt[BinOp].ID = MCDCState.DecisionByStmt.size();
312 }
313 return true;
314 }
315 }
316
317 if (!LogOpStack.empty())
318 NonLogOpStack.pop_back();
319
320 return true;
321 }
322
323 /// The RHS of all logical operators gets a fresh counter in order to count
324 /// how many times the RHS evaluates to true or false, depending on the
325 /// semantics of the operator. This is only valid for ">= v7" of the profile
326 /// version so that we facilitate backward compatibility. In addition, in
327 /// order to use MC/DC, count the number of total LHS and RHS conditions.
328 bool VisitBinaryOperator(BinaryOperator *S) {
329 if (S->isLogicalOp()) {
330 if (CodeGenFunction::isInstrumentedCondition(S->getLHS()))
331 NumCond++;
332
333 if (CodeGenFunction::isInstrumentedCondition(S->getRHS())) {
334 if (ProfileVersion >= llvm::IndexedInstrProf::Version7)
335 CounterMap[S->getRHS()] = NextCounter++;
336
337 NumCond++;
338 }
339 }
340 return Base::VisitBinaryOperator(S);
341 }
342
343 bool VisitConditionalOperator(ConditionalOperator *S) {
344 if (llvm::EnableSingleByteCoverage && S->getTrueExpr())
345 CounterMap[S->getTrueExpr()] = NextCounter++;
346 if (llvm::EnableSingleByteCoverage && S->getFalseExpr())
347 CounterMap[S->getFalseExpr()] = NextCounter++;
348 return Base::VisitConditionalOperator(S);
349 }
350
351 /// Include \p S in the function hash.
352 bool VisitStmt(Stmt *S) {
353 auto Type = updateCounterMappings(S);
354 if (Hash.getHashVersion() != PGO_HASH_V1)
355 Type = getHashType(Hash.getHashVersion(), S);
356 if (Type != PGOHash::None)
357 Hash.combine(Type);
358 return true;
359 }
360
361 bool TraverseIfStmt(IfStmt *If) {
362 // If we used the V1 hash, use the default traversal.
363 if (Hash.getHashVersion() == PGO_HASH_V1)
364 return Base::TraverseIfStmt(If);
365
366 // When single byte coverage mode is enabled, add a counter to then and
367 // else.
368 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
369 for (Stmt *CS : If->children()) {
370 if (!CS || NoSingleByteCoverage)
371 continue;
372 if (CS == If->getThen())
373 CounterMap[If->getThen()] = NextCounter++;
374 else if (CS == If->getElse())
375 CounterMap[If->getElse()] = NextCounter++;
376 }
377
378 // Otherwise, keep track of which branch we're in while traversing.
379 VisitStmt(If);
380
381 for (Stmt *CS : If->children()) {
382 if (!CS)
383 continue;
384 if (CS == If->getThen())
385 Hash.combine(PGOHash::IfThenBranch);
386 else if (CS == If->getElse())
387 Hash.combine(PGOHash::IfElseBranch);
388 TraverseStmt(CS);
389 }
390 Hash.combine(PGOHash::EndOfScope);
391 return true;
392 }
393
394 bool TraverseWhileStmt(WhileStmt *While) {
395 // When single byte coverage mode is enabled, add a counter to condition and
396 // body.
397 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
398 for (Stmt *CS : While->children()) {
399 if (!CS || NoSingleByteCoverage)
400 continue;
401 if (CS == While->getCond())
402 CounterMap[While->getCond()] = NextCounter++;
403 else if (CS == While->getBody())
404 CounterMap[While->getBody()] = NextCounter++;
405 }
406
407 Base::TraverseWhileStmt(While);
408 if (Hash.getHashVersion() != PGO_HASH_V1)
409 Hash.combine(PGOHash::EndOfScope);
410 return true;
411 }
412
413 bool TraverseDoStmt(DoStmt *Do) {
414 // When single byte coverage mode is enabled, add a counter to condition and
415 // body.
416 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
417 for (Stmt *CS : Do->children()) {
418 if (!CS || NoSingleByteCoverage)
419 continue;
420 if (CS == Do->getCond())
421 CounterMap[Do->getCond()] = NextCounter++;
422 else if (CS == Do->getBody())
423 CounterMap[Do->getBody()] = NextCounter++;
424 }
425
426 Base::TraverseDoStmt(Do);
427 if (Hash.getHashVersion() != PGO_HASH_V1)
428 Hash.combine(PGOHash::EndOfScope);
429 return true;
430 }
431
432 bool TraverseForStmt(ForStmt *For) {
433 // When single byte coverage mode is enabled, add a counter to condition,
434 // increment and body.
435 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
436 for (Stmt *CS : For->children()) {
437 if (!CS || NoSingleByteCoverage)
438 continue;
439 if (CS == For->getCond())
440 CounterMap[For->getCond()] = NextCounter++;
441 else if (CS == For->getInc())
442 CounterMap[For->getInc()] = NextCounter++;
443 else if (CS == For->getBody())
444 CounterMap[For->getBody()] = NextCounter++;
445 }
446
447 Base::TraverseForStmt(For);
448 if (Hash.getHashVersion() != PGO_HASH_V1)
449 Hash.combine(PGOHash::EndOfScope);
450 return true;
451 }
452
453 bool TraverseCXXForRangeStmt(CXXForRangeStmt *ForRange) {
454 // When single byte coverage mode is enabled, add a counter to body.
455 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
456 for (Stmt *CS : ForRange->children()) {
457 if (!CS || NoSingleByteCoverage)
458 continue;
459 if (CS == ForRange->getBody())
460 CounterMap[ForRange->getBody()] = NextCounter++;
461 }
462
463 Base::TraverseCXXForRangeStmt(ForRange);
464 if (Hash.getHashVersion() != PGO_HASH_V1)
465 Hash.combine(PGOHash::EndOfScope);
466 return true;
467 }
468
469 // If the statement type \p N is nestable, and its nesting impacts profile
470 // stability, define a custom traversal which tracks the end of the statement
471 // in the hash (provided we're not using the V1 hash).
472 #define DEFINE_NESTABLE_TRAVERSAL(N) \
473 bool Traverse##N(N *S) { \
474 Base::Traverse##N(S); \
475 if (Hash.getHashVersion() != PGO_HASH_V1) \
476 Hash.combine(PGOHash::EndOfScope); \
477 return true; \
478 }
479
480 DEFINE_NESTABLE_TRAVERSAL(ObjCForCollectionStmt)
481 DEFINE_NESTABLE_TRAVERSAL(CXXTryStmt)
482 DEFINE_NESTABLE_TRAVERSAL(CXXCatchStmt)
483
484 /// Get version \p HashVersion of the PGO hash for \p S.
485 PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
486 switch (S->getStmtClass()) {
487 default:
488 break;
489 case Stmt::LabelStmtClass:
490 return PGOHash::LabelStmt;
491 case Stmt::WhileStmtClass:
492 return PGOHash::WhileStmt;
493 case Stmt::DoStmtClass:
494 return PGOHash::DoStmt;
495 case Stmt::ForStmtClass:
496 return PGOHash::ForStmt;
497 case Stmt::CXXForRangeStmtClass:
498 return PGOHash::CXXForRangeStmt;
499 case Stmt::ObjCForCollectionStmtClass:
500 return PGOHash::ObjCForCollectionStmt;
501 case Stmt::SwitchStmtClass:
502 return PGOHash::SwitchStmt;
503 case Stmt::CaseStmtClass:
504 return PGOHash::CaseStmt;
505 case Stmt::DefaultStmtClass:
506 return PGOHash::DefaultStmt;
507 case Stmt::IfStmtClass:
508 return PGOHash::IfStmt;
509 case Stmt::CXXTryStmtClass:
510 return PGOHash::CXXTryStmt;
511 case Stmt::CXXCatchStmtClass:
512 return PGOHash::CXXCatchStmt;
513 case Stmt::ConditionalOperatorClass:
514 return PGOHash::ConditionalOperator;
515 case Stmt::BinaryConditionalOperatorClass:
516 return PGOHash::BinaryConditionalOperator;
517 case Stmt::BinaryOperatorClass: {
518 const BinaryOperator *BO = cast<BinaryOperator>(S);
519 if (BO->getOpcode() == BO_LAnd)
520 return PGOHash::BinaryOperatorLAnd;
521 if (BO->getOpcode() == BO_LOr)
522 return PGOHash::BinaryOperatorLOr;
523 if (HashVersion >= PGO_HASH_V2) {
524 switch (BO->getOpcode()) {
525 default:
526 break;
527 case BO_LT:
528 return PGOHash::BinaryOperatorLT;
529 case BO_GT:
530 return PGOHash::BinaryOperatorGT;
531 case BO_LE:
532 return PGOHash::BinaryOperatorLE;
533 case BO_GE:
534 return PGOHash::BinaryOperatorGE;
535 case BO_EQ:
536 return PGOHash::BinaryOperatorEQ;
537 case BO_NE:
538 return PGOHash::BinaryOperatorNE;
539 }
540 }
541 break;
542 }
543 }
544
545 if (HashVersion >= PGO_HASH_V2) {
546 switch (S->getStmtClass()) {
547 default:
548 break;
549 case Stmt::GotoStmtClass:
550 return PGOHash::GotoStmt;
551 case Stmt::IndirectGotoStmtClass:
552 return PGOHash::IndirectGotoStmt;
553 case Stmt::BreakStmtClass:
554 return PGOHash::BreakStmt;
555 case Stmt::ContinueStmtClass:
556 return PGOHash::ContinueStmt;
557 case Stmt::ReturnStmtClass:
558 return PGOHash::ReturnStmt;
559 case Stmt::CXXThrowExprClass:
560 return PGOHash::ThrowExpr;
561 case Stmt::UnaryOperatorClass: {
562 const UnaryOperator *UO = cast<UnaryOperator>(S);
563 if (UO->getOpcode() == UO_LNot)
564 return PGOHash::UnaryOperatorLNot;
565 break;
566 }
567 }
568 }
569
570 return PGOHash::None;
571 }
572 };
573
574 /// A StmtVisitor that propagates the raw counts through the AST and
575 /// records the count at statements where the value may change.
576 struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
577 /// PGO state.
578 CodeGenPGO &PGO;
579
580 /// A flag that is set when the current count should be recorded on the
581 /// next statement, such as at the exit of a loop.
582 bool RecordNextStmtCount;
583
584 /// The count at the current location in the traversal.
585 uint64_t CurrentCount;
586
587 /// The map of statements to count values.
588 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
589
590 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
591 struct BreakContinue {
592 uint64_t BreakCount = 0;
593 uint64_t ContinueCount = 0;
594 BreakContinue() = default;
595 };
596 SmallVector<BreakContinue, 8> BreakContinueStack;
597
598 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
599 CodeGenPGO &PGO)
600 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
601
602 void RecordStmtCount(const Stmt *S) {
603 if (RecordNextStmtCount) {
604 CountMap[S] = CurrentCount;
605 RecordNextStmtCount = false;
606 }
607 }
608
609 /// Set and return the current count.
610 uint64_t setCount(uint64_t Count) {
611 CurrentCount = Count;
612 return Count;
613 }
614
615 void VisitStmt(const Stmt *S) {
616 RecordStmtCount(S);
617 for (const Stmt *Child : S->children())
618 if (Child)
619 this->Visit(Child);
620 }
621
622 void VisitFunctionDecl(const FunctionDecl *D) {
623 // Counter tracks entry to the function body.
624 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
625 CountMap[D->getBody()] = BodyCount;
626 Visit(D->getBody());
627 }
628
629 // Skip lambda expressions. We visit these as FunctionDecls when we're
630 // generating them and aren't interested in the body when generating a
631 // parent context.
632 void VisitLambdaExpr(const LambdaExpr *LE) {}
633
634 void VisitCapturedDecl(const CapturedDecl *D) {
635 // Counter tracks entry to the capture body.
636 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
637 CountMap[D->getBody()] = BodyCount;
638 Visit(D->getBody());
639 }
640
641 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
642 // Counter tracks entry to the method body.
643 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
644 CountMap[D->getBody()] = BodyCount;
645 Visit(D->getBody());
646 }
647
648 void VisitBlockDecl(const BlockDecl *D) {
649 // Counter tracks entry to the block body.
650 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
651 CountMap[D->getBody()] = BodyCount;
652 Visit(D->getBody());
653 }
654
655 void VisitReturnStmt(const ReturnStmt *S) {
656 RecordStmtCount(S);
657 if (S->getRetValue())
658 Visit(S->getRetValue());
659 CurrentCount = 0;
660 RecordNextStmtCount = true;
661 }
662
663 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
664 RecordStmtCount(E);
665 if (E->getSubExpr())
666 Visit(E->getSubExpr());
667 CurrentCount = 0;
668 RecordNextStmtCount = true;
669 }
670
671 void VisitGotoStmt(const GotoStmt *S) {
672 RecordStmtCount(S);
673 CurrentCount = 0;
674 RecordNextStmtCount = true;
675 }
676
677 void VisitLabelStmt(const LabelStmt *S) {
678 RecordNextStmtCount = false;
679 // Counter tracks the block following the label.
680 uint64_t BlockCount = setCount(PGO.getRegionCount(S));
681 CountMap[S] = BlockCount;
682 Visit(S->getSubStmt());
683 }
684
685 void VisitBreakStmt(const BreakStmt *S) {
686 RecordStmtCount(S);
687 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
688 BreakContinueStack.back().BreakCount += CurrentCount;
689 CurrentCount = 0;
690 RecordNextStmtCount = true;
691 }
692
693 void VisitContinueStmt(const ContinueStmt *S) {
694 RecordStmtCount(S);
695 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
696 BreakContinueStack.back().ContinueCount += CurrentCount;
697 CurrentCount = 0;
698 RecordNextStmtCount = true;
699 }
700
701 void VisitWhileStmt(const WhileStmt *S) {
702 RecordStmtCount(S);
703 uint64_t ParentCount = CurrentCount;
704
705 BreakContinueStack.push_back(BreakContinue());
706 // Visit the body region first so the break/continue adjustments can be
707 // included when visiting the condition.
708 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
709 CountMap[S->getBody()] = CurrentCount;
710 Visit(S->getBody());
711 uint64_t BackedgeCount = CurrentCount;
712
713 // ...then go back and propagate counts through the condition. The count
714 // at the start of the condition is the sum of the incoming edges,
715 // the backedge from the end of the loop body, and the edges from
716 // continue statements.
717 BreakContinue BC = BreakContinueStack.pop_back_val();
718 uint64_t CondCount =
719 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
720 CountMap[S->getCond()] = CondCount;
721 Visit(S->getCond());
722 setCount(BC.BreakCount + CondCount - BodyCount);
723 RecordNextStmtCount = true;
724 }
725
726 void VisitDoStmt(const DoStmt *S) {
727 RecordStmtCount(S);
728 uint64_t LoopCount = PGO.getRegionCount(S);
729
730 BreakContinueStack.push_back(BreakContinue());
731 // The count doesn't include the fallthrough from the parent scope. Add it.
732 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
733 CountMap[S->getBody()] = BodyCount;
734 Visit(S->getBody());
735 uint64_t BackedgeCount = CurrentCount;
736
737 BreakContinue BC = BreakContinueStack.pop_back_val();
738 // The count at the start of the condition is equal to the count at the
739 // end of the body, plus any continues.
740 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
741 CountMap[S->getCond()] = CondCount;
742 Visit(S->getCond());
743 setCount(BC.BreakCount + CondCount - LoopCount);
744 RecordNextStmtCount = true;
745 }
746
747 void VisitForStmt(const ForStmt *S) {
748 RecordStmtCount(S);
749 if (S->getInit())
750 Visit(S->getInit());
751
752 uint64_t ParentCount = CurrentCount;
753
754 BreakContinueStack.push_back(BreakContinue());
755 // Visit the body region first. (This is basically the same as a while
756 // loop; see further comments in VisitWhileStmt.)
757 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
758 CountMap[S->getBody()] = BodyCount;
759 Visit(S->getBody());
760 uint64_t BackedgeCount = CurrentCount;
761 BreakContinue BC = BreakContinueStack.pop_back_val();
762
763 // The increment is essentially part of the body but it needs to include
764 // the count for all the continue statements.
765 if (S->getInc()) {
766 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
767 CountMap[S->getInc()] = IncCount;
768 Visit(S->getInc());
769 }
770
771 // ...then go back and propagate counts through the condition.
772 uint64_t CondCount =
773 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
774 if (S->getCond()) {
775 CountMap[S->getCond()] = CondCount;
776 Visit(S->getCond());
777 }
778 setCount(BC.BreakCount + CondCount - BodyCount);
779 RecordNextStmtCount = true;
780 }
781
782 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
783 RecordStmtCount(S);
784 if (S->getInit())
785 Visit(S->getInit());
786 Visit(S->getLoopVarStmt());
787 Visit(S->getRangeStmt());
788 Visit(S->getBeginStmt());
789 Visit(S->getEndStmt());
790
791 uint64_t ParentCount = CurrentCount;
792 BreakContinueStack.push_back(BreakContinue());
793 // Visit the body region first. (This is basically the same as a while
794 // loop; see further comments in VisitWhileStmt.)
795 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
796 CountMap[S->getBody()] = BodyCount;
797 Visit(S->getBody());
798 uint64_t BackedgeCount = CurrentCount;
799 BreakContinue BC = BreakContinueStack.pop_back_val();
800
801 // The increment is essentially part of the body but it needs to include
802 // the count for all the continue statements.
803 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
804 CountMap[S->getInc()] = IncCount;
805 Visit(S->getInc());
806
807 // ...then go back and propagate counts through the condition.
808 uint64_t CondCount =
809 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
810 CountMap[S->getCond()] = CondCount;
811 Visit(S->getCond());
812 setCount(BC.BreakCount + CondCount - BodyCount);
813 RecordNextStmtCount = true;
814 }
815
816 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
817 RecordStmtCount(S);
818 Visit(S->getElement());
819 uint64_t ParentCount = CurrentCount;
820 BreakContinueStack.push_back(BreakContinue());
821 // Counter tracks the body of the loop.
822 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
823 CountMap[S->getBody()] = BodyCount;
824 Visit(S->getBody());
825 uint64_t BackedgeCount = CurrentCount;
826 BreakContinue BC = BreakContinueStack.pop_back_val();
827
828 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
829 BodyCount);
830 RecordNextStmtCount = true;
831 }
832
833 void VisitSwitchStmt(const SwitchStmt *S) {
834 RecordStmtCount(S);
835 if (S->getInit())
836 Visit(S->getInit());
837 Visit(S->getCond());
838 CurrentCount = 0;
839 BreakContinueStack.push_back(BreakContinue());
840 Visit(S->getBody());
841 // If the switch is inside a loop, add the continue counts.
842 BreakContinue BC = BreakContinueStack.pop_back_val();
843 if (!BreakContinueStack.empty())
844 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
845 // Counter tracks the exit block of the switch.
846 setCount(PGO.getRegionCount(S));
847 RecordNextStmtCount = true;
848 }
849
850 void VisitSwitchCase(const SwitchCase *S) {
851 RecordNextStmtCount = false;
852 // Counter for this particular case. This counts only jumps from the
853 // switch header and does not include fallthrough from the case before
854 // this one.
855 uint64_t CaseCount = PGO.getRegionCount(S);
856 setCount(CurrentCount + CaseCount);
857 // We need the count without fallthrough in the mapping, so it's more useful
858 // for branch probabilities.
859 CountMap[S] = CaseCount;
860 RecordNextStmtCount = true;
861 Visit(S->getSubStmt());
862 }
863
864 void VisitIfStmt(const IfStmt *S) {
865 RecordStmtCount(S);
866
867 if (S->isConsteval()) {
868 const Stmt *Stm = S->isNegatedConsteval() ? S->getThen() : S->getElse();
869 if (Stm)
870 Visit(Stm);
871 return;
872 }
873
874 uint64_t ParentCount = CurrentCount;
875 if (S->getInit())
876 Visit(S->getInit());
877 Visit(S->getCond());
878
879 // Counter tracks the "then" part of an if statement. The count for
880 // the "else" part, if it exists, will be calculated from this counter.
881 uint64_t ThenCount = setCount(PGO.getRegionCount(S));
882 CountMap[S->getThen()] = ThenCount;
883 Visit(S->getThen());
884 uint64_t OutCount = CurrentCount;
885
886 uint64_t ElseCount = ParentCount - ThenCount;
887 if (S->getElse()) {
888 setCount(ElseCount);
889 CountMap[S->getElse()] = ElseCount;
890 Visit(S->getElse());
891 OutCount += CurrentCount;
892 } else
893 OutCount += ElseCount;
894 setCount(OutCount);
895 RecordNextStmtCount = true;
896 }
897
898 void VisitCXXTryStmt(const CXXTryStmt *S) {
899 RecordStmtCount(S);
900 Visit(S->getTryBlock());
901 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
902 Visit(S->getHandler(I));
903 // Counter tracks the continuation block of the try statement.
904 setCount(PGO.getRegionCount(S));
905 RecordNextStmtCount = true;
906 }
907
908 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
909 RecordNextStmtCount = false;
910 // Counter tracks the catch statement's handler block.
911 uint64_t CatchCount = setCount(PGO.getRegionCount(S));
912 CountMap[S] = CatchCount;
913 Visit(S->getHandlerBlock());
914 }
915
916 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
917 RecordStmtCount(E);
918 uint64_t ParentCount = CurrentCount;
919 Visit(E->getCond());
920
921 // Counter tracks the "true" part of a conditional operator. The
922 // count in the "false" part will be calculated from this counter.
923 uint64_t TrueCount = setCount(PGO.getRegionCount(E));
924 CountMap[E->getTrueExpr()] = TrueCount;
925 Visit(E->getTrueExpr());
926 uint64_t OutCount = CurrentCount;
927
928 uint64_t FalseCount = setCount(ParentCount - TrueCount);
929 CountMap[E->getFalseExpr()] = FalseCount;
930 Visit(E->getFalseExpr());
931 OutCount += CurrentCount;
932
933 setCount(OutCount);
934 RecordNextStmtCount = true;
935 }
936
937 void VisitBinLAnd(const BinaryOperator *E) {
938 RecordStmtCount(E);
939 uint64_t ParentCount = CurrentCount;
940 Visit(E->getLHS());
941 // Counter tracks the right hand side of a logical and operator.
942 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
943 CountMap[E->getRHS()] = RHSCount;
944 Visit(E->getRHS());
945 setCount(ParentCount + RHSCount - CurrentCount);
946 RecordNextStmtCount = true;
947 }
948
949 void VisitBinLOr(const BinaryOperator *E) {
950 RecordStmtCount(E);
951 uint64_t ParentCount = CurrentCount;
952 Visit(E->getLHS());
953 // Counter tracks the right hand side of a logical or operator.
954 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
955 CountMap[E->getRHS()] = RHSCount;
956 Visit(E->getRHS());
957 setCount(ParentCount + RHSCount - CurrentCount);
958 RecordNextStmtCount = true;
959 }
960 };
961 } // end anonymous namespace
962
963 void PGOHash::combine(HashType Type) {
964 // Check that we never combine 0 and only have six bits.
965 assert(Type && "Hash is invalid: unexpected type 0");
966 assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
967
968 // Pass through MD5 if enough work has built up.
969 if (Count && Count % NumTypesPerWord == 0) {
970 using namespace llvm::support;
971 uint64_t Swapped =
972 endian::byte_swap<uint64_t>(Working, llvm::endianness::little);
973 MD5.update(llvm::ArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
974 Working = 0;
975 }
976
977 // Accumulate the current type.
978 ++Count;
979 Working = Working << NumBitsPerType | Type;
980 }
981
982 uint64_t PGOHash::finalize() {
983 // Use Working as the hash directly if we never used MD5.
984 if (Count <= NumTypesPerWord)
985 // No need to byte swap here, since none of the math was endian-dependent.
986 // This number will be byte-swapped as required on endianness transitions,
987 // so we will see the same value on the other side.
988 return Working;
989
990 // Check for remaining work in Working.
991 if (Working) {
992 // Keep the buggy behavior from v1 and v2 for backward-compatibility. This
993 // is buggy because it converts a uint64_t into an array of uint8_t.
994 if (HashVersion < PGO_HASH_V3) {
995 MD5.update({(uint8_t)Working});
996 } else {
997 using namespace llvm::support;
998 uint64_t Swapped =
999 endian::byte_swap<uint64_t>(Working, llvm::endianness::little);
1000 MD5.update(llvm::ArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
1001 }
1002 }
1003
1004 // Finalize the MD5 and return the hash.
1005 llvm::MD5::MD5Result Result;
1006 MD5.final(Result);
1007 return Result.low();
1008 }
1009
1010 void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
1011 const Decl *D = GD.getDecl();
1012 if (!D->hasBody())
1013 return;
1014
1015 // Skip CUDA/HIP kernel launch stub functions.
1016 if (CGM.getLangOpts().CUDA && !CGM.getLangOpts().CUDAIsDevice &&
1017 D->hasAttr<CUDAGlobalAttr>())
1018 return;
1019
1020 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1021 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
1022 if (!InstrumentRegions && !PGOReader)
1023 return;
1024 if (D->isImplicit())
1025 return;
1026 // Constructors and destructors may be represented by several functions in IR.
1027 // If so, instrument only base variant, others are implemented by delegation
1028 // to the base one, it would be counted twice otherwise.
1029 if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1030 if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
1031 if (GD.getCtorType() != Ctor_Base &&
1032 CodeGenFunction::IsConstructorDelegationValid(CCD))
1033 return;
1034 }
1035 if (isa<CXXDestructorDecl>(D) && GD.getDtorType() != Dtor_Base)
1036 return;
1037
1038 CGM.ClearUnusedCoverageMapping(D);
1039 if (Fn->hasFnAttribute(llvm::Attribute::NoProfile))
1040 return;
1041 if (Fn->hasFnAttribute(llvm::Attribute::SkipProfile))
1042 return;
1043
1044 SourceManager &SM = CGM.getContext().getSourceManager();
1045 if (!llvm::coverage::SystemHeadersCoverage &&
1046 SM.isInSystemHeader(D->getLocation()))
1047 return;
1048
1049 setFuncName(Fn);
1050
1051 mapRegionCounters(D);
1052 if (CGM.getCodeGenOpts().CoverageMapping)
1053 emitCounterRegionMapping(D);
1054 if (PGOReader) {
1055 loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
1056 computeRegionCounts(D);
1057 applyFunctionAttributes(PGOReader, Fn);
1058 }
1059 }
1060
1061 void CodeGenPGO::mapRegionCounters(const Decl *D) {
1062 // Use the latest hash version when inserting instrumentation, but use the
1063 // version in the indexed profile if we're reading PGO data.
1064 PGOHashVersion HashVersion = PGO_HASH_LATEST;
1065 uint64_t ProfileVersion = llvm::IndexedInstrProf::Version;
1066 if (auto *PGOReader = CGM.getPGOReader()) {
1067 HashVersion = getPGOHashVersion(PGOReader, CGM);
1068 ProfileVersion = PGOReader->getVersion();
1069 }
1070
1071 // If MC/DC is enabled, set the MaxConditions to a preset value. Otherwise,
1072 // set it to zero. This value impacts the number of conditions accepted in a
1073 // given boolean expression, which impacts the size of the bitmap used to
1074 // track test vector execution for that boolean expression. Because the
1075 // bitmap scales exponentially (2^n) based on the number of conditions seen,
1076 // the maximum value is hard-coded at 6 conditions, which is more than enough
1077 // for most embedded applications. Setting a maximum value prevents the
1078 // bitmap footprint from growing too large without the user's knowledge. In
1079 // the future, this value could be adjusted with a command-line option.
1080 unsigned MCDCMaxConditions =
1081 (CGM.getCodeGenOpts().MCDCCoverage ? CGM.getCodeGenOpts().MCDCMaxConds
1082 : 0);
1083
1084 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, CounterPair>);
1085 RegionMCDCState.reset(new MCDC::State);
1086 MapRegionCounters Walker(HashVersion, ProfileVersion, *RegionCounterMap,
1087 *RegionMCDCState, MCDCMaxConditions, CGM.getDiags());
1088 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1089 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
1090 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1091 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
1092 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
1093 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
1094 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
1095 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
1096 assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
1097 NumRegionCounters = Walker.NextCounter;
1098 FunctionHash = Walker.Hash.finalize();
1099 if (HashVersion >= PGO_HASH_V4)
1100 FunctionHash &= llvm::NamedInstrProfRecord::FUNC_HASH_MASK;
1101 }
1102
1103 bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
1104 if (!D->getBody())
1105 return true;
1106
1107 // Skip host-only functions in the CUDA device compilation and device-only
1108 // functions in the host compilation. Just roughly filter them out based on
1109 // the function attributes. If there are effectively host-only or device-only
1110 // ones, their coverage mapping may still be generated.
1111 if (CGM.getLangOpts().CUDA &&
1112 ((CGM.getLangOpts().CUDAIsDevice && !D->hasAttr<CUDADeviceAttr>() &&
1113 !D->hasAttr<CUDAGlobalAttr>()) ||
1114 (!CGM.getLangOpts().CUDAIsDevice &&
1115 (D->hasAttr<CUDAGlobalAttr>() ||
1116 (!D->hasAttr<CUDAHostAttr>() && D->hasAttr<CUDADeviceAttr>())))))
1117 return true;
1118
1119 // Don't map the functions in system headers.
1120 const auto &SM = CGM.getContext().getSourceManager();
1121 auto Loc = D->getBody()->getBeginLoc();
1122 return !llvm::coverage::SystemHeadersCoverage && SM.isInSystemHeader(Loc);
1123 }
1124
1125 void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
1126 if (skipRegionMappingForDecl(D))
1127 return;
1128
1129 std::string CoverageMapping;
1130 llvm::raw_string_ostream OS(CoverageMapping);
1131 RegionMCDCState->BranchByStmt.clear();
1132 CoverageMappingGen MappingGen(
1133 *CGM.getCoverageMapping(), CGM.getContext().getSourceManager(),
1134 CGM.getLangOpts(), RegionCounterMap.get(), RegionMCDCState.get());
1135 MappingGen.emitCounterMapping(D, OS);
1136
1137 if (CoverageMapping.empty())
1138 return;
1139
1140 // Scan max(FalseCnt) and update NumRegionCounters.
1141 unsigned MaxNumCounters = NumRegionCounters;
1142 for (const auto &[_, V] : *RegionCounterMap) {
1143 assert((!V.Executed.hasValue() || MaxNumCounters > V.Executed) &&
1144 "TrueCnt should not be reassigned");
1145 if (V.Skipped.hasValue())
1146 MaxNumCounters = std::max(MaxNumCounters, V.Skipped + 1);
1147 }
1148 NumRegionCounters = MaxNumCounters;
1149
1150 CGM.getCoverageMapping()->addFunctionMappingRecord(
1151 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
1152 }
1153
1154 void
1155 CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
1156 llvm::GlobalValue::LinkageTypes Linkage) {
1157 if (skipRegionMappingForDecl(D))
1158 return;
1159
1160 std::string CoverageMapping;
1161 llvm::raw_string_ostream OS(CoverageMapping);
1162 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
1163 CGM.getContext().getSourceManager(),
1164 CGM.getLangOpts());
1165 MappingGen.emitEmptyMapping(D, OS);
1166
1167 if (CoverageMapping.empty())
1168 return;
1169
1170 setFuncName(Name, Linkage);
1171 CGM.getCoverageMapping()->addFunctionMappingRecord(
1172 FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
1173 }
1174
1175 void CodeGenPGO::computeRegionCounts(const Decl *D) {
1176 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
1177 ComputeRegionCounts Walker(*StmtCountMap, *this);
1178 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1179 Walker.VisitFunctionDecl(FD);
1180 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1181 Walker.VisitObjCMethodDecl(MD);
1182 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
1183 Walker.VisitBlockDecl(BD);
1184 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
1185 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
1186 }
1187
1188 void
1189 CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
1190 llvm::Function *Fn) {
1191 if (!haveRegionCounts())
1192 return;
1193
1194 uint64_t FunctionCount = getRegionCount(nullptr);
1195 Fn->setEntryCount(FunctionCount);
1196 }
1197
1198 std::pair<bool, bool> CodeGenPGO::getIsCounterPair(const Stmt *S) const {
1199 if (!RegionCounterMap)
1200 return {false, false};
1201
1202 auto I = RegionCounterMap->find(S);
1203 if (I == RegionCounterMap->end())
1204 return {false, false};
1205
1206 return {I->second.Executed.hasValue(), I->second.Skipped.hasValue()};
1207 }
1208
1209 void CodeGenPGO::emitCounterSetOrIncrement(CGBuilderTy &Builder, const Stmt *S,
1210 bool UseSkipPath, bool UseBoth,
1211 llvm::Value *StepV) {
1212 if (!RegionCounterMap)
1213 return;
1214
1215 // Allocate S in the Map regardless of emission.
1216 const auto &TheCounterPair = (*RegionCounterMap)[S];
1217
1218 if (!Builder.GetInsertBlock())
1219 return;
1220
1221 const CounterPair::ValueOpt &Counter =
1222 (UseSkipPath ? TheCounterPair.Skipped : TheCounterPair.Executed);
1223 if (!Counter.hasValue())
1224 return;
1225
1226 // Make sure that pointer to global is passed in with zero addrspace
1227 // This is relevant during GPU profiling
1228 auto *NormalizedFuncNameVarPtr =
1229 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1230 FuncNameVar, llvm::PointerType::get(CGM.getLLVMContext(), 0));
1231
1232 llvm::Value *Args[] = {
1233 NormalizedFuncNameVarPtr, Builder.getInt64(FunctionHash),
1234 Builder.getInt32(NumRegionCounters), Builder.getInt32(Counter), StepV};
1235
1236 if (llvm::EnableSingleByteCoverage)
1237 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_cover),
1238 ArrayRef(Args, 4));
1239 else if (!StepV)
1240 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
1241 ArrayRef(Args, 4));
1242 else
1243 Builder.CreateCall(
1244 CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step), Args);
1245 }
1246
1247 bool CodeGenPGO::canEmitMCDCCoverage(const CGBuilderTy &Builder) {
1248 return (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1249 CGM.getCodeGenOpts().MCDCCoverage && Builder.GetInsertBlock());
1250 }
1251
1252 void CodeGenPGO::emitMCDCParameters(CGBuilderTy &Builder) {
1253 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1254 return;
1255
1256 auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
1257
1258 // Emit intrinsic representing MCDC bitmap parameters at function entry.
1259 // This is used by the instrumentation pass, but it isn't actually lowered to
1260 // anything.
1261 llvm::Value *Args[3] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1262 Builder.getInt64(FunctionHash),
1263 Builder.getInt32(RegionMCDCState->BitmapBits)};
1264 Builder.CreateCall(
1265 CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_parameters), Args);
1266 }
1267
1268 void CodeGenPGO::emitMCDCTestVectorBitmapUpdate(CGBuilderTy &Builder,
1269 const Expr *S,
1270 Address MCDCCondBitmapAddr,
1271 CodeGenFunction &CGF) {
1272 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1273 return;
1274
1275 S = S->IgnoreParens();
1276
1277 auto DecisionStateIter = RegionMCDCState->DecisionByStmt.find(S);
1278 if (DecisionStateIter == RegionMCDCState->DecisionByStmt.end())
1279 return;
1280
1281 // Don't create tvbitmap_update if the record is allocated but excluded.
1282 // Or `bitmap |= (1 << 0)` would be wrongly executed to the next bitmap.
1283 if (DecisionStateIter->second.Indices.size() == 0)
1284 return;
1285
1286 // Extract the offset of the global bitmap associated with this expression.
1287 unsigned MCDCTestVectorBitmapOffset = DecisionStateIter->second.BitmapIdx;
1288 auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
1289
1290 // Emit intrinsic responsible for updating the global bitmap corresponding to
1291 // a boolean expression. The index being set is based on the value loaded
1292 // from a pointer to a dedicated temporary value on the stack that is itself
1293 // updated via emitMCDCCondBitmapReset() and emitMCDCCondBitmapUpdate(). The
1294 // index represents an executed test vector.
1295 llvm::Value *Args[4] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1296 Builder.getInt64(FunctionHash),
1297 Builder.getInt32(MCDCTestVectorBitmapOffset),
1298 MCDCCondBitmapAddr.emitRawPointer(CGF)};
1299 Builder.CreateCall(
1300 CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_tvbitmap_update), Args);
1301 }
1302
1303 void CodeGenPGO::emitMCDCCondBitmapReset(CGBuilderTy &Builder, const Expr *S,
1304 Address MCDCCondBitmapAddr) {
1305 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1306 return;
1307
1308 S = S->IgnoreParens();
1309
1310 if (!RegionMCDCState->DecisionByStmt.contains(S))
1311 return;
1312
1313 // Emit intrinsic that resets a dedicated temporary value on the stack to 0.
1314 Builder.CreateStore(Builder.getInt32(0), MCDCCondBitmapAddr);
1315 }
1316
1317 void CodeGenPGO::emitMCDCCondBitmapUpdate(CGBuilderTy &Builder, const Expr *S,
1318 Address MCDCCondBitmapAddr,
1319 llvm::Value *Val,
1320 CodeGenFunction &CGF) {
1321 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1322 return;
1323
1324 // Even though, for simplicity, parentheses and unary logical-NOT operators
1325 // are considered part of their underlying condition for both MC/DC and
1326 // branch coverage, the condition IDs themselves are assigned and tracked
1327 // using the underlying condition itself. This is done solely for
1328 // consistency since parentheses and logical-NOTs are ignored when checking
1329 // whether the condition is actually an instrumentable condition. This can
1330 // also make debugging a bit easier.
1331 S = CodeGenFunction::stripCond(S);
1332
1333 auto BranchStateIter = RegionMCDCState->BranchByStmt.find(S);
1334 if (BranchStateIter == RegionMCDCState->BranchByStmt.end())
1335 return;
1336
1337 // Extract the ID of the condition we are setting in the bitmap.
1338 const auto &Branch = BranchStateIter->second;
1339 assert(Branch.ID >= 0 && "Condition has no ID!");
1340 assert(Branch.DecisionStmt);
1341
1342 // Cancel the emission if the Decision is erased after the allocation.
1343 const auto DecisionIter =
1344 RegionMCDCState->DecisionByStmt.find(Branch.DecisionStmt);
1345 if (DecisionIter == RegionMCDCState->DecisionByStmt.end())
1346 return;
1347
1348 const auto &TVIdxs = DecisionIter->second.Indices[Branch.ID];
1349
1350 auto *CurTV = Builder.CreateLoad(MCDCCondBitmapAddr,
1351 "mcdc." + Twine(Branch.ID + 1) + ".cur");
1352 auto *NewTV = Builder.CreateAdd(CurTV, Builder.getInt32(TVIdxs[true]));
1353 NewTV = Builder.CreateSelect(
1354 Val, NewTV, Builder.CreateAdd(CurTV, Builder.getInt32(TVIdxs[false])));
1355 Builder.CreateStore(NewTV, MCDCCondBitmapAddr);
1356 }
1357
1358 void CodeGenPGO::setValueProfilingFlag(llvm::Module &M) {
1359 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1360 M.addModuleFlag(llvm::Module::Warning, "EnableValueProfiling",
1361 uint32_t(EnableValueProfiling));
1362 }
1363
1364 void CodeGenPGO::setProfileVersion(llvm::Module &M) {
1365 if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1366 llvm::EnableSingleByteCoverage) {
1367 const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1368 llvm::Type *IntTy64 = llvm::Type::getInt64Ty(M.getContext());
1369 uint64_t ProfileVersion =
1370 (INSTR_PROF_RAW_VERSION | VARIANT_MASK_BYTE_COVERAGE);
1371
1372 auto IRLevelVersionVariable = new llvm::GlobalVariable(
1373 M, IntTy64, true, llvm::GlobalValue::WeakAnyLinkage,
1374 llvm::Constant::getIntegerValue(IntTy64,
1375 llvm::APInt(64, ProfileVersion)),
1376 VarName);
1377
1378 IRLevelVersionVariable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1379 llvm::Triple TT(M.getTargetTriple());
1380 if (TT.isGPU())
1381 IRLevelVersionVariable->setVisibility(
1382 llvm::GlobalValue::ProtectedVisibility);
1383 if (TT.supportsCOMDAT()) {
1384 IRLevelVersionVariable->setLinkage(llvm::GlobalValue::ExternalLinkage);
1385 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
1386 }
1387 IRLevelVersionVariable->setDSOLocal(true);
1388 }
1389 }
1390
1391 // This method either inserts a call to the profile run-time during
1392 // instrumentation or puts profile data into metadata for PGO use.
1393 void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
1394 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
1395
1396 if (!EnableValueProfiling)
1397 return;
1398
1399 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
1400 return;
1401
1402 if (isa<llvm::Constant>(ValuePtr))
1403 return;
1404
1405 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
1406 if (InstrumentValueSites && RegionCounterMap) {
1407 auto BuilderInsertPoint = Builder.saveIP();
1408 Builder.SetInsertPoint(ValueSite);
1409 llvm::Value *Args[5] = {
1410 FuncNameVar,
1411 Builder.getInt64(FunctionHash),
1412 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
1413 Builder.getInt32(ValueKind),
1414 Builder.getInt32(NumValueSites[ValueKind]++)
1415 };
1416 Builder.CreateCall(
1417 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
1418 Builder.restoreIP(BuilderInsertPoint);
1419 return;
1420 }
1421
1422 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
1423 if (PGOReader && haveRegionCounts()) {
1424 // We record the top most called three functions at each call site.
1425 // Profile metadata contains "VP" string identifying this metadata
1426 // as value profiling data, then a uint32_t value for the value profiling
1427 // kind, a uint64_t value for the total number of times the call is
1428 // executed, followed by the function hash and execution count (uint64_t)
1429 // pairs for each function.
1430 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
1431 return;
1432
1433 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
1434 (llvm::InstrProfValueKind)ValueKind,
1435 NumValueSites[ValueKind]);
1436
1437 NumValueSites[ValueKind]++;
1438 }
1439 }
1440
1441 void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
1442 bool IsInMainFile) {
1443 CGM.getPGOStats().addVisited(IsInMainFile);
1444 RegionCounts.clear();
1445 auto RecordExpected = PGOReader->getInstrProfRecord(FuncName, FunctionHash);
1446 if (auto E = RecordExpected.takeError()) {
1447 auto IPE = std::get<0>(llvm::InstrProfError::take(std::move(E)));
1448 if (IPE == llvm::instrprof_error::unknown_function)
1449 CGM.getPGOStats().addMissing(IsInMainFile);
1450 else if (IPE == llvm::instrprof_error::hash_mismatch)
1451 CGM.getPGOStats().addMismatched(IsInMainFile);
1452 else if (IPE == llvm::instrprof_error::malformed)
1453 // TODO: Consider a more specific warning for this case.
1454 CGM.getPGOStats().addMismatched(IsInMainFile);
1455 return;
1456 }
1457 ProfRecord =
1458 std::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
1459 RegionCounts = ProfRecord->Counts;
1460 }
1461
1462 /// Calculate what to divide by to scale weights.
1463 ///
1464 /// Given the maximum weight, calculate a divisor that will scale all the
1465 /// weights to strictly less than UINT32_MAX.
1466 static uint64_t calculateWeightScale(uint64_t MaxWeight) {
1467 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
1468 }
1469
1470 /// Scale an individual branch weight (and add 1).
1471 ///
1472 /// Scale a 64-bit weight down to 32-bits using \c Scale.
1473 ///
1474 /// According to Laplace's Rule of Succession, it is better to compute the
1475 /// weight based on the count plus 1, so universally add 1 to the value.
1476 ///
1477 /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
1478 /// greater than \c Weight.
1479 static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
1480 assert(Scale && "scale by 0?");
1481 uint64_t Scaled = Weight / Scale + 1;
1482 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
1483 return Scaled;
1484 }
1485
1486 llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1487 uint64_t FalseCount) const {
1488 // Check for empty weights.
1489 if (!TrueCount && !FalseCount)
1490 return nullptr;
1491
1492 // Calculate how to scale down to 32-bits.
1493 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
1494
1495 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1496 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
1497 scaleBranchWeight(FalseCount, Scale));
1498 }
1499
1500 llvm::MDNode *
1501 CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) const {
1502 // We need at least two elements to create meaningful weights.
1503 if (Weights.size() < 2)
1504 return nullptr;
1505
1506 // Check for empty weights.
1507 uint64_t MaxWeight = *llvm::max_element(Weights);
1508 if (MaxWeight == 0)
1509 return nullptr;
1510
1511 // Calculate how to scale down to 32-bits.
1512 uint64_t Scale = calculateWeightScale(MaxWeight);
1513
1514 SmallVector<uint32_t, 16> ScaledWeights;
1515 ScaledWeights.reserve(Weights.size());
1516 for (uint64_t W : Weights)
1517 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1518
1519 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1520 return MDHelper.createBranchWeights(ScaledWeights);
1521 }
1522
1523 llvm::MDNode *
1524 CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
1525 uint64_t LoopCount) const {
1526 if (!PGO->haveRegionCounts())
1527 return nullptr;
1528 std::optional<uint64_t> CondCount = PGO->getStmtCount(Cond);
1529 if (!CondCount || *CondCount == 0)
1530 return nullptr;
1531 return createProfileWeights(LoopCount,
1532 std::max(*CondCount, LoopCount) - LoopCount);
1533 }
1534
1535 void CodeGenFunction::incrementProfileCounter(CounterForIncrement ExecSkip,
1536 const Stmt *S, bool UseBoth,
1537 llvm::Value *StepV) {
1538 if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1539 !CurFn->hasFnAttribute(llvm::Attribute::NoProfile) &&
1540 !CurFn->hasFnAttribute(llvm::Attribute::SkipProfile)) {
1541 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1542 PGO->emitCounterSetOrIncrement(Builder, S, (ExecSkip == UseSkipPath),
1543 UseBoth, StepV);
1544 }
1545 PGO->setCurrentStmt(S);
1546 }
1547
1548 std::pair<bool, bool> CodeGenFunction::getIsCounterPair(const Stmt *S) const {
1549 return PGO->getIsCounterPair(S);
1550 }
1551 void CodeGenFunction::markStmtAsUsed(bool Skipped, const Stmt *S) {
1552 PGO->markStmtAsUsed(Skipped, S);
1553 }
1554 void CodeGenFunction::markStmtMaybeUsed(const Stmt *S) {
1555 PGO->markStmtMaybeUsed(S);
1556 }
1557
1558 void CodeGenFunction::maybeCreateMCDCCondBitmap() {
1559 if (isMCDCCoverageEnabled()) {
1560 PGO->emitMCDCParameters(Builder);
1561 MCDCCondBitmapAddr = CreateIRTemp(getContext().UnsignedIntTy, "mcdc.addr");
1562 }
1563 }
1564 void CodeGenFunction::maybeResetMCDCCondBitmap(const Expr *E) {
1565 if (isMCDCCoverageEnabled() && isBinaryLogicalOp(E)) {
1566 PGO->emitMCDCCondBitmapReset(Builder, E, MCDCCondBitmapAddr);
1567 PGO->setCurrentStmt(E);
1568 }
1569 }
1570 void CodeGenFunction::maybeUpdateMCDCTestVectorBitmap(const Expr *E) {
1571 if (isMCDCCoverageEnabled() && isBinaryLogicalOp(E)) {
1572 PGO->emitMCDCTestVectorBitmapUpdate(Builder, E, MCDCCondBitmapAddr, *this);
1573 PGO->setCurrentStmt(E);
1574 }
1575 }
1576
1577 void CodeGenFunction::maybeUpdateMCDCCondBitmap(const Expr *E,
1578 llvm::Value *Val) {
1579 if (isMCDCCoverageEnabled()) {
1580 PGO->emitMCDCCondBitmapUpdate(Builder, E, MCDCCondBitmapAddr, Val, *this);
1581 PGO->setCurrentStmt(E);
1582 }
1583 }
1584
1585 uint64_t CodeGenFunction::getProfileCount(const Stmt *S) {
1586 return PGO->getStmtCount(S).value_or(0);
1587 }
1588
1589 /// Set the profiler's current count.
1590 void CodeGenFunction::setCurrentProfileCount(uint64_t Count) {
1591 PGO->setCurrentRegionCount(Count);
1592 }
1593
1594 /// Get the profiler's current count. This is generally the count for the most
1595 /// recently incremented counter.
1596 uint64_t CodeGenFunction::getCurrentProfileCount() {
1597 return PGO->getCurrentRegionCount();
1598 }