clang 23.0.0git
CodeGenPGO.cpp
Go to the documentation of this file.
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"
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
27namespace llvm {
28extern cl::opt<bool> EnableSingleByteCoverage;
29} // namespace llvm
30
31static 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
36using namespace clang;
37using namespace CodeGen;
38
39void CodeGenPGO::setFuncName(StringRef Name,
40 llvm::GlobalValue::LinkageTypes Linkage) {
41 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
42 FuncName = llvm::getPGOFuncName(
44 PGOReader ? PGOReader->getVersion() : llvm::IndexedInstrProf::Version);
45
46 // If we're generating a profile, create a variable for the name.
48 FuncNameVar = llvm::createPGOFuncNameVar(CGM.getModule(), Linkage, FuncName);
49}
50
51void 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.
58enum PGOHashVersion : unsigned {
63
64 // Keep this set to the latest hash version.
66};
67
68namespace {
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.
79class 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
89public:
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);
144 PGOHashVersion getHashVersion() const { return HashVersion; }
145};
146const int PGOHash::NumBitsPerType;
147const unsigned PGOHash::NumTypesPerWord;
148const unsigned PGOHash::TooBig;
149
150/// Get the PGO hash version used in the given indexed profile.
151static 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.
163struct 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()) {
331 NumCond++;
332
334 if (ProfileVersion >= llvm::IndexedInstrProf::Version7)
335 CounterMap[S->getRHS()] = NextCounter++;
336
337 NumCond++;
338 }
339 }
340 return Base::VisitBinaryOperator(S);
341 }
342
343 /// Include \p S in the function hash.
344 bool VisitStmt(Stmt *S) {
345 auto Type = updateCounterMappings(S);
346 if (Hash.getHashVersion() != PGO_HASH_V1)
347 Type = getHashType(Hash.getHashVersion(), S);
348 if (Type != PGOHash::None)
349 Hash.combine(Type);
350 return true;
351 }
352
353 bool TraverseIfStmt(IfStmt *If) {
354 // If we used the V1 hash, use the default traversal.
355 if (Hash.getHashVersion() == PGO_HASH_V1)
356 return Base::TraverseIfStmt(If);
357
358 // When single byte coverage mode is enabled, add a counter to then and
359 // else.
360 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
361 for (Stmt *CS : If->children()) {
362 if (!CS || NoSingleByteCoverage)
363 continue;
364 if (CS == If->getThen())
365 CounterMap[If->getThen()] = NextCounter++;
366 else if (CS == If->getElse())
367 CounterMap[If->getElse()] = NextCounter++;
368 }
369
370 // Otherwise, keep track of which branch we're in while traversing.
371 VisitStmt(If);
372
373 for (Stmt *CS : If->children()) {
374 if (!CS)
375 continue;
376 if (CS == If->getThen())
377 Hash.combine(PGOHash::IfThenBranch);
378 else if (CS == If->getElse())
379 Hash.combine(PGOHash::IfElseBranch);
380 TraverseStmt(CS);
381 }
382 Hash.combine(PGOHash::EndOfScope);
383 return true;
384 }
385
386 bool TraverseWhileStmt(WhileStmt *While) {
387 // When single byte coverage mode is enabled, add a counter to condition and
388 // body.
389 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
390 for (Stmt *CS : While->children()) {
391 if (!CS || NoSingleByteCoverage)
392 continue;
393 if (CS == While->getCond())
394 CounterMap[While->getCond()] = NextCounter++;
395 else if (CS == While->getBody())
396 CounterMap[While->getBody()] = NextCounter++;
397 }
398
399 Base::TraverseWhileStmt(While);
400 if (Hash.getHashVersion() != PGO_HASH_V1)
401 Hash.combine(PGOHash::EndOfScope);
402 return true;
403 }
404
405 bool TraverseDoStmt(DoStmt *Do) {
406 // When single byte coverage mode is enabled, add a counter to condition and
407 // body.
408 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
409 for (Stmt *CS : Do->children()) {
410 if (!CS || NoSingleByteCoverage)
411 continue;
412 if (CS == Do->getCond())
413 CounterMap[Do->getCond()] = NextCounter++;
414 else if (CS == Do->getBody())
415 CounterMap[Do->getBody()] = NextCounter++;
416 }
417
418 Base::TraverseDoStmt(Do);
419 if (Hash.getHashVersion() != PGO_HASH_V1)
420 Hash.combine(PGOHash::EndOfScope);
421 return true;
422 }
423
424 bool TraverseForStmt(ForStmt *For) {
425 // When single byte coverage mode is enabled, add a counter to condition,
426 // increment and body.
427 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
428 for (Stmt *CS : For->children()) {
429 if (!CS || NoSingleByteCoverage)
430 continue;
431 if (CS == For->getCond())
432 CounterMap[For->getCond()] = NextCounter++;
433 else if (CS == For->getInc())
434 CounterMap[For->getInc()] = NextCounter++;
435 else if (CS == For->getBody())
436 CounterMap[For->getBody()] = NextCounter++;
437 }
438
439 Base::TraverseForStmt(For);
440 if (Hash.getHashVersion() != PGO_HASH_V1)
441 Hash.combine(PGOHash::EndOfScope);
442 return true;
443 }
444
445 bool TraverseCXXForRangeStmt(CXXForRangeStmt *ForRange) {
446 // When single byte coverage mode is enabled, add a counter to body.
447 bool NoSingleByteCoverage = !llvm::EnableSingleByteCoverage;
448 for (Stmt *CS : ForRange->children()) {
449 if (!CS || NoSingleByteCoverage)
450 continue;
451 if (CS == ForRange->getBody())
452 CounterMap[ForRange->getBody()] = NextCounter++;
453 }
454
455 Base::TraverseCXXForRangeStmt(ForRange);
456 if (Hash.getHashVersion() != PGO_HASH_V1)
457 Hash.combine(PGOHash::EndOfScope);
458 return true;
459 }
460
461// If the statement type \p N is nestable, and its nesting impacts profile
462// stability, define a custom traversal which tracks the end of the statement
463// in the hash (provided we're not using the V1 hash).
464#define DEFINE_NESTABLE_TRAVERSAL(N) \
465 bool Traverse##N(N *S) { \
466 Base::Traverse##N(S); \
467 if (Hash.getHashVersion() != PGO_HASH_V1) \
468 Hash.combine(PGOHash::EndOfScope); \
469 return true; \
470 }
471
475
476 /// Get version \p HashVersion of the PGO hash for \p S.
477 PGOHash::HashType getHashType(PGOHashVersion HashVersion, const Stmt *S) {
478 switch (S->getStmtClass()) {
479 default:
480 break;
481 case Stmt::LabelStmtClass:
482 return PGOHash::LabelStmt;
483 case Stmt::WhileStmtClass:
484 return PGOHash::WhileStmt;
485 case Stmt::DoStmtClass:
486 return PGOHash::DoStmt;
487 case Stmt::ForStmtClass:
488 return PGOHash::ForStmt;
489 case Stmt::CXXForRangeStmtClass:
490 return PGOHash::CXXForRangeStmt;
491 case Stmt::ObjCForCollectionStmtClass:
492 return PGOHash::ObjCForCollectionStmt;
493 case Stmt::SwitchStmtClass:
494 return PGOHash::SwitchStmt;
495 case Stmt::CaseStmtClass:
496 return PGOHash::CaseStmt;
497 case Stmt::DefaultStmtClass:
498 return PGOHash::DefaultStmt;
499 case Stmt::IfStmtClass:
500 return PGOHash::IfStmt;
501 case Stmt::CXXTryStmtClass:
502 return PGOHash::CXXTryStmt;
503 case Stmt::CXXCatchStmtClass:
504 return PGOHash::CXXCatchStmt;
505 case Stmt::ConditionalOperatorClass:
506 return PGOHash::ConditionalOperator;
507 case Stmt::BinaryConditionalOperatorClass:
508 return PGOHash::BinaryConditionalOperator;
509 case Stmt::BinaryOperatorClass: {
511 if (BO->getOpcode() == BO_LAnd)
512 return PGOHash::BinaryOperatorLAnd;
513 if (BO->getOpcode() == BO_LOr)
514 return PGOHash::BinaryOperatorLOr;
515 if (HashVersion >= PGO_HASH_V2) {
516 switch (BO->getOpcode()) {
517 default:
518 break;
519 case BO_LT:
520 return PGOHash::BinaryOperatorLT;
521 case BO_GT:
522 return PGOHash::BinaryOperatorGT;
523 case BO_LE:
524 return PGOHash::BinaryOperatorLE;
525 case BO_GE:
526 return PGOHash::BinaryOperatorGE;
527 case BO_EQ:
528 return PGOHash::BinaryOperatorEQ;
529 case BO_NE:
530 return PGOHash::BinaryOperatorNE;
531 }
532 }
533 break;
534 }
535 }
536
537 if (HashVersion >= PGO_HASH_V2) {
538 switch (S->getStmtClass()) {
539 default:
540 break;
541 case Stmt::GotoStmtClass:
542 return PGOHash::GotoStmt;
543 case Stmt::IndirectGotoStmtClass:
544 return PGOHash::IndirectGotoStmt;
545 case Stmt::BreakStmtClass:
546 return PGOHash::BreakStmt;
547 case Stmt::ContinueStmtClass:
548 return PGOHash::ContinueStmt;
549 case Stmt::ReturnStmtClass:
550 return PGOHash::ReturnStmt;
551 case Stmt::CXXThrowExprClass:
552 return PGOHash::ThrowExpr;
553 case Stmt::UnaryOperatorClass: {
554 const UnaryOperator *UO = cast<UnaryOperator>(S);
555 if (UO->getOpcode() == UO_LNot)
556 return PGOHash::UnaryOperatorLNot;
557 break;
558 }
559 }
560 }
561
562 return PGOHash::None;
563 }
564};
565
566/// A StmtVisitor that propagates the raw counts through the AST and
567/// records the count at statements where the value may change.
568struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
569 /// PGO state.
570 CodeGenPGO &PGO;
571
572 /// A flag that is set when the current count should be recorded on the
573 /// next statement, such as at the exit of a loop.
574 bool RecordNextStmtCount;
575
576 /// The count at the current location in the traversal.
577 uint64_t CurrentCount;
578
579 /// The map of statements to count values.
580 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
581
582 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
583 struct BreakContinue {
584 uint64_t BreakCount = 0;
585 uint64_t ContinueCount = 0;
586 BreakContinue() = default;
587 };
588 SmallVector<BreakContinue, 8> BreakContinueStack;
589
590 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
591 CodeGenPGO &PGO)
592 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
593
594 void RecordStmtCount(const Stmt *S) {
595 if (RecordNextStmtCount) {
596 CountMap[S] = CurrentCount;
597 RecordNextStmtCount = false;
598 }
599 }
600
601 /// Set and return the current count.
602 uint64_t setCount(uint64_t Count) {
603 CurrentCount = Count;
604 return Count;
605 }
606
607 void VisitStmt(const Stmt *S) {
608 RecordStmtCount(S);
609 for (const Stmt *Child : S->children())
610 if (Child)
611 this->Visit(Child);
612 }
613
614 void VisitFunctionDecl(const FunctionDecl *D) {
615 // Counter tracks entry to the function body.
616 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
617 CountMap[D->getBody()] = BodyCount;
618 Visit(D->getBody());
619 }
620
621 // Skip lambda expressions. We visit these as FunctionDecls when we're
622 // generating them and aren't interested in the body when generating a
623 // parent context.
624 void VisitLambdaExpr(const LambdaExpr *LE) {}
625
626 void VisitCapturedDecl(const CapturedDecl *D) {
627 // Counter tracks entry to the capture body.
628 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
629 CountMap[D->getBody()] = BodyCount;
630 Visit(D->getBody());
631 }
632
633 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
634 // Counter tracks entry to the method body.
635 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
636 CountMap[D->getBody()] = BodyCount;
637 Visit(D->getBody());
638 }
639
640 void VisitBlockDecl(const BlockDecl *D) {
641 // Counter tracks entry to the block body.
642 uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
643 CountMap[D->getBody()] = BodyCount;
644 Visit(D->getBody());
645 }
646
647 void VisitReturnStmt(const ReturnStmt *S) {
648 RecordStmtCount(S);
649 if (S->getRetValue())
650 Visit(S->getRetValue());
651 CurrentCount = 0;
652 RecordNextStmtCount = true;
653 }
654
655 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
656 RecordStmtCount(E);
657 if (E->getSubExpr())
658 Visit(E->getSubExpr());
659 CurrentCount = 0;
660 RecordNextStmtCount = true;
661 }
662
663 void VisitGotoStmt(const GotoStmt *S) {
664 RecordStmtCount(S);
665 CurrentCount = 0;
666 RecordNextStmtCount = true;
667 }
668
669 void VisitLabelStmt(const LabelStmt *S) {
670 RecordNextStmtCount = false;
671 // Counter tracks the block following the label.
672 uint64_t BlockCount = setCount(PGO.getRegionCount(S));
673 CountMap[S] = BlockCount;
674 Visit(S->getSubStmt());
675 }
676
677 void VisitBreakStmt(const BreakStmt *S) {
678 RecordStmtCount(S);
679 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
680 BreakContinueStack.back().BreakCount += CurrentCount;
681 CurrentCount = 0;
682 RecordNextStmtCount = true;
683 }
684
685 void VisitContinueStmt(const ContinueStmt *S) {
686 RecordStmtCount(S);
687 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
688 BreakContinueStack.back().ContinueCount += CurrentCount;
689 CurrentCount = 0;
690 RecordNextStmtCount = true;
691 }
692
693 void VisitWhileStmt(const WhileStmt *S) {
694 RecordStmtCount(S);
695 uint64_t ParentCount = CurrentCount;
696
697 BreakContinueStack.push_back(BreakContinue());
698 // Visit the body region first so the break/continue adjustments can be
699 // included when visiting the condition.
700 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
701 CountMap[S->getBody()] = CurrentCount;
702 Visit(S->getBody());
703 uint64_t BackedgeCount = CurrentCount;
704
705 // ...then go back and propagate counts through the condition. The count
706 // at the start of the condition is the sum of the incoming edges,
707 // the backedge from the end of the loop body, and the edges from
708 // continue statements.
709 BreakContinue BC = BreakContinueStack.pop_back_val();
710 uint64_t CondCount =
711 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
712 CountMap[S->getCond()] = CondCount;
713 Visit(S->getCond());
714 setCount(BC.BreakCount + CondCount - BodyCount);
715 RecordNextStmtCount = true;
716 }
717
718 void VisitDoStmt(const DoStmt *S) {
719 RecordStmtCount(S);
720 uint64_t LoopCount = PGO.getRegionCount(S);
721
722 BreakContinueStack.push_back(BreakContinue());
723 // The count doesn't include the fallthrough from the parent scope. Add it.
724 uint64_t BodyCount = setCount(LoopCount + CurrentCount);
725 CountMap[S->getBody()] = BodyCount;
726 Visit(S->getBody());
727 uint64_t BackedgeCount = CurrentCount;
728
729 BreakContinue BC = BreakContinueStack.pop_back_val();
730 // The count at the start of the condition is equal to the count at the
731 // end of the body, plus any continues.
732 uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
733 CountMap[S->getCond()] = CondCount;
734 Visit(S->getCond());
735 setCount(BC.BreakCount + CondCount - LoopCount);
736 RecordNextStmtCount = true;
737 }
738
739 void VisitForStmt(const ForStmt *S) {
740 RecordStmtCount(S);
741 if (S->getInit())
742 Visit(S->getInit());
743
744 uint64_t ParentCount = CurrentCount;
745
746 BreakContinueStack.push_back(BreakContinue());
747 // Visit the body region first. (This is basically the same as a while
748 // loop; see further comments in VisitWhileStmt.)
749 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
750 CountMap[S->getBody()] = BodyCount;
751 Visit(S->getBody());
752 uint64_t BackedgeCount = CurrentCount;
753 BreakContinue BC = BreakContinueStack.pop_back_val();
754
755 // The increment is essentially part of the body but it needs to include
756 // the count for all the continue statements.
757 if (S->getInc()) {
758 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
759 CountMap[S->getInc()] = IncCount;
760 Visit(S->getInc());
761 }
762
763 // ...then go back and propagate counts through the condition.
764 uint64_t CondCount =
765 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
766 if (S->getCond()) {
767 CountMap[S->getCond()] = CondCount;
768 Visit(S->getCond());
769 }
770 setCount(BC.BreakCount + CondCount - BodyCount);
771 RecordNextStmtCount = true;
772 }
773
774 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
775 RecordStmtCount(S);
776 if (S->getInit())
777 Visit(S->getInit());
778 Visit(S->getLoopVarStmt());
779 Visit(S->getRangeStmt());
780 Visit(S->getBeginStmt());
781 Visit(S->getEndStmt());
782
783 uint64_t ParentCount = CurrentCount;
784 BreakContinueStack.push_back(BreakContinue());
785 // Visit the body region first. (This is basically the same as a while
786 // loop; see further comments in VisitWhileStmt.)
787 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
788 CountMap[S->getBody()] = BodyCount;
789 Visit(S->getBody());
790 uint64_t BackedgeCount = CurrentCount;
791 BreakContinue BC = BreakContinueStack.pop_back_val();
792
793 // The increment is essentially part of the body but it needs to include
794 // the count for all the continue statements.
795 uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
796 CountMap[S->getInc()] = IncCount;
797 Visit(S->getInc());
798
799 // ...then go back and propagate counts through the condition.
800 uint64_t CondCount =
801 setCount(ParentCount + BackedgeCount + BC.ContinueCount);
802 CountMap[S->getCond()] = CondCount;
803 Visit(S->getCond());
804 setCount(BC.BreakCount + CondCount - BodyCount);
805 RecordNextStmtCount = true;
806 }
807
808 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
809 RecordStmtCount(S);
810 Visit(S->getElement());
811 uint64_t ParentCount = CurrentCount;
812 BreakContinueStack.push_back(BreakContinue());
813 // Counter tracks the body of the loop.
814 uint64_t BodyCount = setCount(PGO.getRegionCount(S));
815 CountMap[S->getBody()] = BodyCount;
816 Visit(S->getBody());
817 uint64_t BackedgeCount = CurrentCount;
818 BreakContinue BC = BreakContinueStack.pop_back_val();
819
820 setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
821 BodyCount);
822 RecordNextStmtCount = true;
823 }
824
825 void VisitSwitchStmt(const SwitchStmt *S) {
826 RecordStmtCount(S);
827 if (S->getInit())
828 Visit(S->getInit());
829 Visit(S->getCond());
830 CurrentCount = 0;
831 BreakContinueStack.push_back(BreakContinue());
832 Visit(S->getBody());
833 // If the switch is inside a loop, add the continue counts.
834 BreakContinue BC = BreakContinueStack.pop_back_val();
835 if (!BreakContinueStack.empty())
836 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
837 // Counter tracks the exit block of the switch.
838 setCount(PGO.getRegionCount(S));
839 RecordNextStmtCount = true;
840 }
841
842 void VisitSwitchCase(const SwitchCase *S) {
843 RecordNextStmtCount = false;
844 // Counter for this particular case. This counts only jumps from the
845 // switch header and does not include fallthrough from the case before
846 // this one.
847 uint64_t CaseCount = PGO.getRegionCount(S);
848 setCount(CurrentCount + CaseCount);
849 // We need the count without fallthrough in the mapping, so it's more useful
850 // for branch probabilities.
851 CountMap[S] = CaseCount;
852 RecordNextStmtCount = true;
853 Visit(S->getSubStmt());
854 }
855
856 void VisitIfStmt(const IfStmt *S) {
857 RecordStmtCount(S);
858
859 if (S->isConsteval()) {
860 const Stmt *Stm = S->isNegatedConsteval() ? S->getThen() : S->getElse();
861 if (Stm)
862 Visit(Stm);
863 return;
864 }
865
866 uint64_t ParentCount = CurrentCount;
867 if (S->getInit())
868 Visit(S->getInit());
869 Visit(S->getCond());
870
871 // Counter tracks the "then" part of an if statement. The count for
872 // the "else" part, if it exists, will be calculated from this counter.
873 uint64_t ThenCount = setCount(PGO.getRegionCount(S));
874 CountMap[S->getThen()] = ThenCount;
875 Visit(S->getThen());
876 uint64_t OutCount = CurrentCount;
877
878 uint64_t ElseCount = ParentCount - ThenCount;
879 if (S->getElse()) {
880 setCount(ElseCount);
881 CountMap[S->getElse()] = ElseCount;
882 Visit(S->getElse());
883 OutCount += CurrentCount;
884 } else
885 OutCount += ElseCount;
886 setCount(OutCount);
887 RecordNextStmtCount = true;
888 }
889
890 void VisitCXXTryStmt(const CXXTryStmt *S) {
891 RecordStmtCount(S);
892 Visit(S->getTryBlock());
893 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
894 Visit(S->getHandler(I));
895 // Counter tracks the continuation block of the try statement.
896 setCount(PGO.getRegionCount(S));
897 RecordNextStmtCount = true;
898 }
899
900 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
901 RecordNextStmtCount = false;
902 // Counter tracks the catch statement's handler block.
903 uint64_t CatchCount = setCount(PGO.getRegionCount(S));
904 CountMap[S] = CatchCount;
905 Visit(S->getHandlerBlock());
906 }
907
908 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
909 RecordStmtCount(E);
910 uint64_t ParentCount = CurrentCount;
911 Visit(E->getCond());
912
913 // Counter tracks the "true" part of a conditional operator. The
914 // count in the "false" part will be calculated from this counter.
915 uint64_t TrueCount = setCount(PGO.getRegionCount(E));
916 CountMap[E->getTrueExpr()] = TrueCount;
917 Visit(E->getTrueExpr());
918 uint64_t OutCount = CurrentCount;
919
920 uint64_t FalseCount = setCount(ParentCount - TrueCount);
921 CountMap[E->getFalseExpr()] = FalseCount;
922 Visit(E->getFalseExpr());
923 OutCount += CurrentCount;
924
925 setCount(OutCount);
926 RecordNextStmtCount = true;
927 }
928
929 void VisitBinLAnd(const BinaryOperator *E) {
930 RecordStmtCount(E);
931 uint64_t ParentCount = CurrentCount;
932 Visit(E->getLHS());
933 // Counter tracks the right hand side of a logical and operator.
934 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
935 CountMap[E->getRHS()] = RHSCount;
936 Visit(E->getRHS());
937 setCount(ParentCount + RHSCount - CurrentCount);
938 RecordNextStmtCount = true;
939 }
940
941 void VisitBinLOr(const BinaryOperator *E) {
942 RecordStmtCount(E);
943 uint64_t ParentCount = CurrentCount;
944 Visit(E->getLHS());
945 // Counter tracks the right hand side of a logical or operator.
946 uint64_t RHSCount = setCount(PGO.getRegionCount(E));
947 CountMap[E->getRHS()] = RHSCount;
948 Visit(E->getRHS());
949 setCount(ParentCount + RHSCount - CurrentCount);
950 RecordNextStmtCount = true;
951 }
952};
953} // end anonymous namespace
954
955void PGOHash::combine(HashType Type) {
956 // Check that we never combine 0 and only have six bits.
957 assert(Type && "Hash is invalid: unexpected type 0");
958 assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
959
960 // Pass through MD5 if enough work has built up.
961 if (Count && Count % NumTypesPerWord == 0) {
962 using namespace llvm::support;
963 uint64_t Swapped =
964 endian::byte_swap<uint64_t>(Working, llvm::endianness::little);
965 MD5.update(llvm::ArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
966 Working = 0;
967 }
968
969 // Accumulate the current type.
970 ++Count;
971 Working = Working << NumBitsPerType | Type;
972}
973
974uint64_t PGOHash::finalize() {
975 // Use Working as the hash directly if we never used MD5.
976 if (Count <= NumTypesPerWord)
977 // No need to byte swap here, since none of the math was endian-dependent.
978 // This number will be byte-swapped as required on endianness transitions,
979 // so we will see the same value on the other side.
980 return Working;
981
982 // Check for remaining work in Working.
983 if (Working) {
984 // Keep the buggy behavior from v1 and v2 for backward-compatibility. This
985 // is buggy because it converts a uint64_t into an array of uint8_t.
986 if (HashVersion < PGO_HASH_V3) {
987 MD5.update({(uint8_t)Working});
988 } else {
989 using namespace llvm::support;
990 uint64_t Swapped =
991 endian::byte_swap<uint64_t>(Working, llvm::endianness::little);
992 MD5.update(llvm::ArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
993 }
994 }
995
996 // Finalize the MD5 and return the hash.
997 llvm::MD5::MD5Result Result;
998 MD5.final(Result);
999 return Result.low();
1000}
1001
1002void CodeGenPGO::assignRegionCounters(GlobalDecl GD, llvm::Function *Fn) {
1003 const Decl *D = GD.getDecl();
1004 if (!D->hasBody())
1005 return;
1006
1007 // Skip CUDA/HIP kernel launch stub functions.
1008 if (CGM.getLangOpts().CUDA && !CGM.getLangOpts().CUDAIsDevice &&
1009 D->hasAttr<CUDAGlobalAttr>())
1010 return;
1011
1012 bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr();
1013 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
1014 if (!InstrumentRegions && !PGOReader)
1015 return;
1016 if (D->isImplicit())
1017 return;
1018 // Constructors and destructors may be represented by several functions in IR.
1019 // If so, instrument only base variant, others are implemented by delegation
1020 // to the base one, it would be counted twice otherwise.
1021 if (CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1022 if (const auto *CCD = dyn_cast<CXXConstructorDecl>(D))
1023 if (GD.getCtorType() != Ctor_Base &&
1025 return;
1026 }
1028 return;
1029
1030 CGM.ClearUnusedCoverageMapping(D);
1031 if (Fn->hasFnAttribute(llvm::Attribute::NoProfile))
1032 return;
1033 if (Fn->hasFnAttribute(llvm::Attribute::SkipProfile))
1034 return;
1035
1036 SourceManager &SM = CGM.getContext().getSourceManager();
1038 SM.isInSystemHeader(D->getLocation()))
1039 return;
1040
1041 setFuncName(Fn);
1042
1043 mapRegionCounters(D);
1044 if (CGM.getCodeGenOpts().CoverageMapping)
1045 emitCounterRegionMapping(D);
1046 if (PGOReader) {
1047 loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
1048 computeRegionCounts(D);
1049 applyFunctionAttributes(PGOReader, Fn);
1050 }
1051}
1052
1053void CodeGenPGO::mapRegionCounters(const Decl *D) {
1054 // Use the latest hash version when inserting instrumentation, but use the
1055 // version in the indexed profile if we're reading PGO data.
1056 PGOHashVersion HashVersion = PGO_HASH_LATEST;
1057 uint64_t ProfileVersion = llvm::IndexedInstrProf::Version;
1058 if (auto *PGOReader = CGM.getPGOReader()) {
1059 HashVersion = getPGOHashVersion(PGOReader, CGM);
1060 ProfileVersion = PGOReader->getVersion();
1061 }
1062
1063 // If MC/DC is enabled, set the MaxConditions to a preset value. Otherwise,
1064 // set it to zero. This value impacts the number of conditions accepted in a
1065 // given boolean expression, which impacts the size of the bitmap used to
1066 // track test vector execution for that boolean expression. Because the
1067 // bitmap scales exponentially (2^n) based on the number of conditions seen,
1068 // the maximum value is hard-coded at 6 conditions, which is more than enough
1069 // for most embedded applications. Setting a maximum value prevents the
1070 // bitmap footprint from growing too large without the user's knowledge. In
1071 // the future, this value could be adjusted with a command-line option.
1072 unsigned MCDCMaxConditions =
1073 (CGM.getCodeGenOpts().MCDCCoverage ? CGM.getCodeGenOpts().MCDCMaxConds
1074 : 0);
1075
1076 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, CounterPair>);
1077 RegionMCDCState.reset(new MCDC::State);
1078 MapRegionCounters Walker(HashVersion, ProfileVersion, *RegionCounterMap,
1079 *RegionMCDCState, MCDCMaxConditions, CGM.getDiags());
1080 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1081 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
1082 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1083 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
1084 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
1085 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
1086 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
1087 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
1088 assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
1089 NumRegionCounters = Walker.NextCounter;
1090 FunctionHash = Walker.Hash.finalize();
1091 if (HashVersion >= PGO_HASH_V4)
1092 FunctionHash &= llvm::NamedInstrProfRecord::FUNC_HASH_MASK;
1093}
1094
1095bool CodeGenPGO::skipRegionMappingForDecl(const Decl *D) {
1096 if (!D->getBody())
1097 return true;
1098
1099 // Skip host-only functions in the CUDA device compilation and device-only
1100 // functions in the host compilation. Just roughly filter them out based on
1101 // the function attributes. If there are effectively host-only or device-only
1102 // ones, their coverage mapping may still be generated.
1103 if (CGM.getLangOpts().CUDA &&
1104 ((CGM.getLangOpts().CUDAIsDevice && !D->hasAttr<CUDADeviceAttr>() &&
1105 !D->hasAttr<CUDAGlobalAttr>()) ||
1106 (!CGM.getLangOpts().CUDAIsDevice &&
1107 (D->hasAttr<CUDAGlobalAttr>() ||
1108 (!D->hasAttr<CUDAHostAttr>() && D->hasAttr<CUDADeviceAttr>())))))
1109 return true;
1110
1111 // Don't map the functions in system headers.
1112 const auto &SM = CGM.getContext().getSourceManager();
1113 auto Loc = D->getBody()->getBeginLoc();
1114 return !llvm::coverage::SystemHeadersCoverage && SM.isInSystemHeader(Loc);
1115}
1116
1117void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
1118 if (skipRegionMappingForDecl(D))
1119 return;
1120
1121 std::string CoverageMapping;
1122 llvm::raw_string_ostream OS(CoverageMapping);
1123 RegionMCDCState->BranchByStmt.clear();
1124 CoverageMappingGen MappingGen(
1125 *CGM.getCoverageMapping(), CGM.getContext().getSourceManager(),
1126 CGM.getLangOpts(), RegionCounterMap.get(), RegionMCDCState.get());
1127 MappingGen.emitCounterMapping(D, OS);
1128
1129 if (CoverageMapping.empty())
1130 return;
1131
1132 // Scan max(FalseCnt) and update NumRegionCounters.
1133 unsigned MaxNumCounters = NumRegionCounters;
1134 for (const auto &[_, V] : *RegionCounterMap) {
1135 assert((!V.Executed.hasValue() || MaxNumCounters > V.Executed) &&
1136 "TrueCnt should not be reassigned");
1137 if (V.Skipped.hasValue())
1138 MaxNumCounters = std::max(MaxNumCounters, V.Skipped + 1);
1139 }
1140 NumRegionCounters = MaxNumCounters;
1141
1142 CGM.getCoverageMapping()->addFunctionMappingRecord(
1143 FuncNameVar, FuncName, FunctionHash, CoverageMapping);
1144}
1145
1146void
1148 llvm::GlobalValue::LinkageTypes Linkage) {
1149 if (skipRegionMappingForDecl(D))
1150 return;
1151
1152 std::string CoverageMapping;
1153 llvm::raw_string_ostream OS(CoverageMapping);
1154 CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
1155 CGM.getContext().getSourceManager(),
1156 CGM.getLangOpts());
1157 MappingGen.emitEmptyMapping(D, OS);
1158
1159 if (CoverageMapping.empty())
1160 return;
1161
1162 setFuncName(Name, Linkage);
1163 CGM.getCoverageMapping()->addFunctionMappingRecord(
1164 FuncNameVar, FuncName, FunctionHash, CoverageMapping, false);
1165}
1166
1167void CodeGenPGO::computeRegionCounts(const Decl *D) {
1168 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
1169 ComputeRegionCounts Walker(*StmtCountMap, *this);
1170 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
1171 Walker.VisitFunctionDecl(FD);
1172 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
1173 Walker.VisitObjCMethodDecl(MD);
1174 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
1175 Walker.VisitBlockDecl(BD);
1176 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
1177 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
1178}
1179
1180void
1181CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
1182 llvm::Function *Fn) {
1183 if (!haveRegionCounts())
1184 return;
1185
1186 uint64_t FunctionCount = getRegionCount(nullptr);
1187 Fn->setEntryCount(FunctionCount);
1188}
1189
1190std::pair<bool, bool> CodeGenPGO::getIsCounterPair(const Stmt *S) const {
1191 if (!RegionCounterMap)
1192 return {false, false};
1193
1194 auto I = RegionCounterMap->find(S);
1195 if (I == RegionCounterMap->end())
1196 return {false, false};
1197
1198 return {I->second.Executed.hasValue(), I->second.Skipped.hasValue()};
1199}
1200
1202 bool UseSkipPath, bool UseBoth,
1203 llvm::Value *StepV) {
1204 if (!RegionCounterMap)
1205 return;
1206
1207 // Allocate S in the Map regardless of emission.
1208 const auto &TheCounterPair = (*RegionCounterMap)[S];
1209
1210 if (!Builder.GetInsertBlock())
1211 return;
1212
1213 const CounterPair::ValueOpt &Counter =
1214 (UseSkipPath ? TheCounterPair.Skipped : TheCounterPair.Executed);
1215 if (!Counter.hasValue())
1216 return;
1217
1218 // Make sure that pointer to global is passed in with zero addrspace
1219 // This is relevant during GPU profiling
1220 auto *NormalizedFuncNameVarPtr =
1221 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1222 FuncNameVar, llvm::PointerType::get(CGM.getLLVMContext(), 0));
1223
1224 llvm::Value *Args[] = {
1225 NormalizedFuncNameVarPtr, Builder.getInt64(FunctionHash),
1226 Builder.getInt32(NumRegionCounters), Builder.getInt32(Counter), StepV};
1227
1229 assert(!StepV && "StepV is not supported in single byte counter mode");
1230 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_cover),
1231 ArrayRef(Args, 4));
1232 } else if (!StepV)
1233 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
1234 ArrayRef(Args, 4));
1235 else
1236 Builder.CreateCall(
1237 CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment_step), Args);
1238}
1239
1240bool CodeGenPGO::canEmitMCDCCoverage(const CGBuilderTy &Builder) {
1241 return (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1242 CGM.getCodeGenOpts().MCDCCoverage && Builder.GetInsertBlock());
1243}
1244
1246 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1247 return;
1248
1249 auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
1250
1251 // Emit intrinsic representing MCDC bitmap parameters at function entry.
1252 // This is used by the instrumentation pass, but it isn't actually lowered to
1253 // anything.
1254 llvm::Value *Args[3] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1255 Builder.getInt64(FunctionHash),
1256 Builder.getInt32(RegionMCDCState->BitmapBits)};
1257 Builder.CreateCall(
1258 CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_parameters), Args);
1259}
1260
1261/// Fill mcdc.addr order by ID.
1262std::vector<Address *>
1264 std::vector<Address *> Result;
1265
1266 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1267 return Result;
1268
1270 for (auto &[_, V] : RegionMCDCState->DecisionByStmt)
1271 if (V.isValid())
1272 SortedPair.emplace_back(V.ID, &V.MCDCCondBitmapAddr);
1273
1274 llvm::sort(SortedPair);
1275
1276 for (auto &[_, MCDCCondBitmapAddr] : SortedPair)
1277 Result.push_back(MCDCCondBitmapAddr);
1278
1279 return Result;
1280}
1281
1283 const Expr *S,
1284 CodeGenFunction &CGF) {
1285 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1286 return;
1287
1288 S = S->IgnoreParens();
1289
1290 auto DecisionStateIter = RegionMCDCState->DecisionByStmt.find(S);
1291 if (DecisionStateIter == RegionMCDCState->DecisionByStmt.end())
1292 return;
1293
1294 auto &MCDCCondBitmapAddr = DecisionStateIter->second.MCDCCondBitmapAddr;
1295 if (!MCDCCondBitmapAddr.isValid())
1296 return;
1297
1298 // Don't create tvbitmap_update if the record is allocated but excluded.
1299 // Or `bitmap |= (1 << 0)` would be wrongly executed to the next bitmap.
1300 if (DecisionStateIter->second.Indices.size() == 0)
1301 return;
1302
1303 // Extract the offset of the global bitmap associated with this expression.
1304 unsigned MCDCTestVectorBitmapOffset = DecisionStateIter->second.BitmapIdx;
1305 auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
1306
1307 // Emit intrinsic responsible for updating the global bitmap corresponding to
1308 // a boolean expression. The index being set is based on the value loaded
1309 // from a pointer to a dedicated temporary value on the stack that is itself
1310 // updated via emitMCDCCondBitmapReset() and emitMCDCCondBitmapUpdate(). The
1311 // index represents an executed test vector.
1312 llvm::Value *Args[4] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
1313 Builder.getInt64(FunctionHash),
1314 Builder.getInt32(MCDCTestVectorBitmapOffset),
1315 MCDCCondBitmapAddr.emitRawPointer(CGF)};
1316 Builder.CreateCall(
1317 CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_tvbitmap_update), Args);
1318}
1319
1321 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1322 return;
1323
1324 auto I = RegionMCDCState->DecisionByStmt.find(S->IgnoreParens());
1325 if (I == RegionMCDCState->DecisionByStmt.end())
1326 return;
1327
1328 auto &MCDCCondBitmapAddr = I->second.MCDCCondBitmapAddr;
1329 if (!MCDCCondBitmapAddr.isValid())
1330 return;
1331
1332 // Emit intrinsic that resets a dedicated temporary value on the stack to 0.
1333 Builder.CreateStore(Builder.getInt32(0), MCDCCondBitmapAddr);
1334}
1335
1337 llvm::Value *Val,
1338 CodeGenFunction &CGF) {
1339 if (!canEmitMCDCCoverage(Builder) || !RegionMCDCState)
1340 return;
1341
1342 // Even though, for simplicity, parentheses and unary logical-NOT operators
1343 // are considered part of their underlying condition for both MC/DC and
1344 // branch coverage, the condition IDs themselves are assigned and tracked
1345 // using the underlying condition itself. This is done solely for
1346 // consistency since parentheses and logical-NOTs are ignored when checking
1347 // whether the condition is actually an instrumentable condition. This can
1348 // also make debugging a bit easier.
1350
1351 auto BranchStateIter = RegionMCDCState->BranchByStmt.find(S);
1352 if (BranchStateIter == RegionMCDCState->BranchByStmt.end())
1353 return;
1354
1355 // Extract the ID of the condition we are setting in the bitmap.
1356 const auto &Branch = BranchStateIter->second;
1357 assert(Branch.ID >= 0 && "Condition has no ID!");
1358 assert(Branch.DecisionStmt);
1359
1360 // Cancel the emission if the Decision is erased after the allocation.
1361 const auto DecisionIter =
1362 RegionMCDCState->DecisionByStmt.find(Branch.DecisionStmt);
1363 if (DecisionIter == RegionMCDCState->DecisionByStmt.end())
1364 return;
1365
1366 auto &MCDCCondBitmapAddr = DecisionIter->second.MCDCCondBitmapAddr;
1367 if (!MCDCCondBitmapAddr.isValid())
1368 return;
1369
1370 const auto &TVIdxs = DecisionIter->second.Indices[Branch.ID];
1371
1372 auto *CurTV = Builder.CreateLoad(MCDCCondBitmapAddr,
1373 "mcdc." + Twine(Branch.ID + 1) + ".cur");
1374 auto *NewTV = Builder.CreateAdd(CurTV, Builder.getInt32(TVIdxs[true]));
1375 NewTV = Builder.CreateSelect(
1376 Val, NewTV, Builder.CreateAdd(CurTV, Builder.getInt32(TVIdxs[false])));
1377 Builder.CreateStore(NewTV, MCDCCondBitmapAddr);
1378}
1379
1381 if (CGM.getCodeGenOpts().hasProfileClangInstr())
1382 M.addModuleFlag(llvm::Module::Warning, "EnableValueProfiling",
1383 uint32_t(EnableValueProfiling));
1384}
1385
1386void CodeGenPGO::setProfileVersion(llvm::Module &M) {
1387 if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1389 const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
1390 llvm::Type *IntTy64 = llvm::Type::getInt64Ty(M.getContext());
1391 uint64_t ProfileVersion =
1392 (INSTR_PROF_RAW_VERSION | VARIANT_MASK_BYTE_COVERAGE);
1393
1394 auto IRLevelVersionVariable = new llvm::GlobalVariable(
1395 M, IntTy64, true, llvm::GlobalValue::WeakAnyLinkage,
1396 llvm::Constant::getIntegerValue(IntTy64,
1397 llvm::APInt(64, ProfileVersion)),
1398 VarName);
1399
1400 IRLevelVersionVariable->setVisibility(llvm::GlobalValue::HiddenVisibility);
1401 llvm::Triple TT(M.getTargetTriple());
1402 if (TT.isGPU())
1403 IRLevelVersionVariable->setVisibility(
1404 llvm::GlobalValue::ProtectedVisibility);
1405 if (TT.supportsCOMDAT()) {
1406 IRLevelVersionVariable->setLinkage(llvm::GlobalValue::ExternalLinkage);
1407 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
1408 }
1409 IRLevelVersionVariable->setDSOLocal(true);
1410 }
1411}
1412
1413// This method either inserts a call to the profile run-time during
1414// instrumentation or puts profile data into metadata for PGO use.
1415void CodeGenPGO::valueProfile(CGBuilderTy &Builder, uint32_t ValueKind,
1416 llvm::Instruction *ValueSite, llvm::Value *ValuePtr) {
1417
1419 return;
1420
1421 if (!ValuePtr || !ValueSite || !Builder.GetInsertBlock())
1422 return;
1423
1424 if (isa<llvm::Constant>(ValuePtr))
1425 return;
1426
1427 bool InstrumentValueSites = CGM.getCodeGenOpts().hasProfileClangInstr();
1428 if (InstrumentValueSites && RegionCounterMap) {
1429 auto BuilderInsertPoint = Builder.saveIP();
1430 Builder.SetInsertPoint(ValueSite);
1431 llvm::Value *Args[5] = {
1432 FuncNameVar,
1433 Builder.getInt64(FunctionHash),
1434 Builder.CreatePtrToInt(ValuePtr, Builder.getInt64Ty()),
1435 Builder.getInt32(ValueKind),
1436 Builder.getInt32(NumValueSites[ValueKind]++)
1437 };
1438 Builder.CreateCall(
1439 CGM.getIntrinsic(llvm::Intrinsic::instrprof_value_profile), Args);
1440 Builder.restoreIP(BuilderInsertPoint);
1441 return;
1442 }
1443
1444 llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
1445 if (PGOReader && haveRegionCounts()) {
1446 // We record the top most called three functions at each call site.
1447 // Profile metadata contains "VP" string identifying this metadata
1448 // as value profiling data, then a uint32_t value for the value profiling
1449 // kind, a uint64_t value for the total number of times the call is
1450 // executed, followed by the function hash and execution count (uint64_t)
1451 // pairs for each function.
1452 if (NumValueSites[ValueKind] >= ProfRecord->getNumValueSites(ValueKind))
1453 return;
1454
1455 llvm::annotateValueSite(CGM.getModule(), *ValueSite, *ProfRecord,
1456 (llvm::InstrProfValueKind)ValueKind,
1457 NumValueSites[ValueKind]);
1458
1459 NumValueSites[ValueKind]++;
1460 }
1461}
1462
1463void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
1464 bool IsInMainFile) {
1465 CGM.getPGOStats().addVisited(IsInMainFile);
1466 RegionCounts.clear();
1467 auto RecordExpected = PGOReader->getInstrProfRecord(FuncName, FunctionHash);
1468 if (auto E = RecordExpected.takeError()) {
1469 auto IPE = std::get<0>(llvm::InstrProfError::take(std::move(E)));
1470 if (IPE == llvm::instrprof_error::unknown_function)
1471 CGM.getPGOStats().addMissing(IsInMainFile);
1472 else if (IPE == llvm::instrprof_error::hash_mismatch)
1473 CGM.getPGOStats().addMismatched(IsInMainFile);
1474 else if (IPE == llvm::instrprof_error::malformed)
1475 // TODO: Consider a more specific warning for this case.
1476 CGM.getPGOStats().addMismatched(IsInMainFile);
1477 return;
1478 }
1479 ProfRecord =
1480 std::make_unique<llvm::InstrProfRecord>(std::move(RecordExpected.get()));
1481 RegionCounts = ProfRecord->Counts;
1482}
1483
1484/// Calculate what to divide by to scale weights.
1485///
1486/// Given the maximum weight, calculate a divisor that will scale all the
1487/// weights to strictly less than UINT32_MAX.
1488static uint64_t calculateWeightScale(uint64_t MaxWeight) {
1489 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
1490}
1491
1492/// Scale an individual branch weight (and add 1).
1493///
1494/// Scale a 64-bit weight down to 32-bits using \c Scale.
1495///
1496/// According to Laplace's Rule of Succession, it is better to compute the
1497/// weight based on the count plus 1, so universally add 1 to the value.
1498///
1499/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
1500/// greater than \c Weight.
1501static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
1502 assert(Scale && "scale by 0?");
1503 uint64_t Scaled = Weight / Scale + 1;
1504 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
1505 return Scaled;
1506}
1507
1508llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
1509 uint64_t FalseCount) const {
1510 // Check for empty weights.
1511 if (!TrueCount && !FalseCount)
1512 return nullptr;
1513
1514 // Calculate how to scale down to 32-bits.
1515 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
1516
1517 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1518 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
1519 scaleBranchWeight(FalseCount, Scale));
1520}
1521
1522llvm::MDNode *
1523CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) const {
1524 // We need at least two elements to create meaningful weights.
1525 if (Weights.size() < 2)
1526 return nullptr;
1527
1528 // Check for empty weights.
1529 uint64_t MaxWeight = *llvm::max_element(Weights);
1530 if (MaxWeight == 0)
1531 return nullptr;
1532
1533 // Calculate how to scale down to 32-bits.
1534 uint64_t Scale = calculateWeightScale(MaxWeight);
1535
1536 SmallVector<uint32_t, 16> ScaledWeights;
1537 ScaledWeights.reserve(Weights.size());
1538 for (uint64_t W : Weights)
1539 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1540
1541 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
1542 return MDHelper.createBranchWeights(ScaledWeights);
1543}
1544
1545llvm::MDNode *
1546CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
1547 uint64_t LoopCount) const {
1548 if (!PGO->haveRegionCounts())
1549 return nullptr;
1550 std::optional<uint64_t> CondCount = PGO->getStmtCount(Cond);
1551 if (!CondCount || *CondCount == 0)
1552 return nullptr;
1553 return createProfileWeights(LoopCount,
1554 std::max(*CondCount, LoopCount) - LoopCount);
1555}
1556
1558 const Stmt *S, bool UseBoth,
1559 llvm::Value *StepV) {
1560 if (CGM.getCodeGenOpts().hasProfileClangInstr() &&
1561 !CurFn->hasFnAttribute(llvm::Attribute::NoProfile) &&
1562 !CurFn->hasFnAttribute(llvm::Attribute::SkipProfile)) {
1563 auto AL = ApplyDebugLocation::CreateArtificial(*this);
1564 PGO->emitCounterSetOrIncrement(Builder, S, (ExecSkip == UseSkipPath),
1565 UseBoth, StepV);
1566 }
1567 PGO->setCurrentStmt(S);
1568}
1569
1570std::pair<bool, bool> CodeGenFunction::getIsCounterPair(const Stmt *S) const {
1571 return PGO->getIsCounterPair(S);
1572}
1573void CodeGenFunction::markStmtAsUsed(bool Skipped, const Stmt *S) {
1574 PGO->markStmtAsUsed(Skipped, S);
1575}
1577 PGO->markStmtMaybeUsed(S);
1578}
1579
1581 if (isMCDCCoverageEnabled()) {
1582 PGO->emitMCDCParameters(Builder);
1583
1584 // Set up MCDCCondBitmapAddr for each Decision.
1585 // Note: This doesn't initialize Addrs in invalidated Decisions.
1586 for (auto *MCDCCondBitmapAddr : PGO->getMCDCCondBitmapAddrArray(Builder))
1587 *MCDCCondBitmapAddr =
1588 CreateIRTemp(getContext().UnsignedIntTy, "mcdc.addr");
1589 }
1590}
1592 return PGO->isMCDCDecisionExpr(E);
1593}
1595 return PGO->isMCDCBranchExpr(E);
1596}
1599 PGO->emitMCDCCondBitmapReset(Builder, E);
1600 PGO->setCurrentStmt(E);
1601 }
1602}
1605 PGO->emitMCDCTestVectorBitmapUpdate(Builder, E, *this);
1606 PGO->setCurrentStmt(E);
1607 }
1608}
1609
1611 llvm::Value *Val) {
1612 if (isMCDCCoverageEnabled()) {
1613 PGO->emitMCDCCondBitmapUpdate(Builder, E, Val, *this);
1614 PGO->setCurrentStmt(E);
1615 }
1616}
1617
1619 return PGO->getStmtCount(S).value_or(0);
1620}
1621
1622/// Set the profiler's current count.
1624 PGO->setCurrentRegionCount(Count);
1625}
1626
1627/// Get the profiler's current count. This is generally the count for the most
1628/// recently incremented counter.
1630 return PGO->getCurrentRegionCount();
1631}
#define V(N, I)
llvm::ImmutableMap< CountKey, unsigned > CountMap
#define DEFINE_NESTABLE_TRAVERSAL(N)
static llvm::cl::opt< bool > EnableValueProfiling("enable-value-profiling", llvm::cl::desc("Enable value profiling"), llvm::cl::Hidden, llvm::cl::init(false))
PGOHashVersion
The version of the PGO hash algorithm.
@ PGO_HASH_LATEST
@ PGO_HASH_V1
@ PGO_HASH_V4
@ PGO_HASH_V3
@ PGO_HASH_V2
static uint64_t calculateWeightScale(uint64_t MaxWeight)
Calculate what to divide by to scale weights.
static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale)
Scale an individual branch weight (and add 1).
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
#define SM(sm)
SourceManager & getSourceManager()
Definition ASTContext.h:851
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4531
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4537
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4543
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4171
Expr * getLHS() const
Definition Expr.h:4088
Expr * getRHS() const
Definition Expr.h:4090
Opcode getOpcode() const
Definition Expr.h:4083
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4671
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition Decl.h:4750
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:28
Stmt * getHandlerBlock() const
Definition StmtCXX.h:51
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
child_range children()
Definition StmtCXX.h:217
const Expr * getSubExpr() const
Definition ExprCXX.h:1228
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CXXCatchStmt * getHandler(unsigned i)
Definition StmtCXX.h:108
unsigned getNumHandlers() const
Definition StmtCXX.h:107
CompoundStmt * getTryBlock()
Definition StmtCXX.h:100
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition Decl.h:4943
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition Decl.cpp:5693
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
std::string MainFileName
The user provided name for the "main file", if non-empty.
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
bool isBinaryLogicalOp(const Expr *E) const
CounterForIncrement
Used to specify which counter in a pair shall be incremented.
RawAddress CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
Definition CGExpr.cpp:184
void maybeUpdateMCDCTestVectorBitmap(const Expr *E)
Increment the profiler's counter for the given expression by StepV.
static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor)
Checks whether the given constructor is a valid subject for the complete-to-base constructor delegati...
Definition CGClass.cpp:706
void maybeCreateMCDCCondBitmap()
Allocate a temp value on the stack that MCDC can use to track condition results.
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
void maybeResetMCDCCondBitmap(const Expr *E)
Zero-init the MCDC temp value.
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
bool isMCDCBranchExpr(const Expr *E) const
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
uint64_t getCurrentProfileCount()
Get the profiler's current count.
void markStmtMaybeUsed(const Stmt *S)
std::pair< bool, bool > getIsCounterPair(const Stmt *S) const
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
void markStmtAsUsed(bool Skipped, const Stmt *S)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
bool isMCDCDecisionExpr(const Expr *E) const
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
DiagnosticsEngine & getDiags() const
const LangOptions & getLangOpts() const
llvm::IndexedInstrProfReader * getPGOReader() const
InstrProfStats & getPGOStats()
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
void assignRegionCounters(GlobalDecl GD, llvm::Function *Fn)
Assign counters to regions and configure them for PGO of a given function.
std::pair< bool, bool > getIsCounterPair(const Stmt *S) const
uint64_t getRegionCount(const Stmt *S)
Return the region count for the counter at the given index.
Definition CodeGenPGO.h:152
void setValueProfilingFlag(llvm::Module &M)
void valueProfile(CGBuilderTy &Builder, uint32_t ValueKind, llvm::Instruction *ValueSite, llvm::Value *ValuePtr)
void emitMCDCCondBitmapUpdate(CGBuilderTy &Builder, const Expr *S, llvm::Value *Val, CodeGenFunction &CGF)
void emitMCDCCondBitmapReset(CGBuilderTy &Builder, const Expr *S)
std::vector< Address * > getMCDCCondBitmapAddrArray(CGBuilderTy &Builder)
Fill mcdc.addr order by ID.
void setProfileVersion(llvm::Module &M)
void emitEmptyCounterMapping(const Decl *D, StringRef FuncName, llvm::GlobalValue::LinkageTypes Linkage)
Emit a coverage mapping range with a counter zero for an unused declaration.
void emitCounterSetOrIncrement(CGBuilderTy &Builder, const Stmt *S, bool UseFalsePath, bool UseBoth, llvm::Value *StepV)
void emitMCDCTestVectorBitmapUpdate(CGBuilderTy &Builder, const Expr *S, CodeGenFunction &CGF)
void emitMCDCParameters(CGBuilderTy &Builder)
bool haveRegionCounts() const
Whether or not we have PGO region data for the current function.
Definition CodeGenPGO.h:53
Organizes the per-function state that is used while generating code coverage mapping data.
void emitEmptyMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data for an unused function.
void addMissing(bool MainFile)
Record that a function we've visited has no profile data.
void addMismatched(bool MainFile)
Record that a function we've visited has mismatched profile data.
void addVisited(bool MainFile)
Record that we've visited a function and whether or not that function was in the main source file.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1087
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition DeclBase.h:1093
SourceLocation getLocation() const
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:577
Kind getKind() const
Definition DeclBase.h:442
Stmt * getBody()
Definition Stmt.h:2849
Expr * getCond()
Definition Stmt.h:2842
child_range children()
Definition Stmt.h:2868
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
Stmt * getInit()
Definition Stmt.h:2895
child_range children()
Definition Stmt.h:2951
Stmt * getBody()
Definition Stmt.h:2924
Expr * getInc()
Definition Stmt.h:2923
Expr * getCond()
Definition Stmt.h:2922
Represents a function declaration or definition.
Definition Decl.h:2000
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3279
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
CXXCtorType getCtorType() const
Definition GlobalDecl.h:108
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
Stmt * getThen()
Definition Stmt.h:2340
Stmt * getInit()
Definition Stmt.h:2401
Expr * getCond()
Definition Stmt.h:2328
bool isNegatedConsteval() const
Definition Stmt.h:2440
Stmt * getElse()
Definition Stmt.h:2349
bool isConsteval() const
Definition Stmt.h:2431
Stmt * getSubStmt()
Definition Stmt.h:2160
Represents Objective-C's collection statement.
Definition StmtObjC.h:23
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition DeclObjC.cpp:906
Expr * getRetValue()
Definition Stmt.h:3179
This class handles loading and caching of source files into memory.
Stmt - This represents one statement.
Definition Stmt.h:86
child_range children()
Definition Stmt.cpp:299
StmtClass getStmtClass() const
Definition Stmt.h:1485
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
Stmt * getSubStmt()
Definition Stmt.h:2105
Expr * getCond()
Definition Stmt.h:2564
Stmt * getBody()
Definition Stmt.h:2576
Stmt * getInit()
Definition Stmt.h:2581
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Opcode getOpcode() const
Definition Expr.h:2280
Expr * getCond()
Definition Stmt.h:2741
child_range children()
Definition Stmt.h:2812
Stmt * getBody()
Definition Stmt.h:2753
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1310
The JSON file list parser is used to communicate input to InstallAPI.
@ Ctor_Base
Base object ctor.
Definition ABI.h:26
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
Expr * Cond
};
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ Dtor_Base
Base object dtor.
Definition ABI.h:37
@ Type
The name was classified as a type.
Definition Sema.h:564
void finalize(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema)
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
unsigned long uint64_t
cl::opt< bool > SystemHeadersCoverage
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
cl::opt< bool > EnableSingleByteCoverage
Definition CGStmt.cpp:48
#define false
Definition stdbool.h:26
Per-Function MC/DC state.
Definition MCDCState.h:32
llvm::DenseMap< const Stmt *, Decision > DecisionByStmt
Definition MCDCState.h:53