LLVM  8.0.0svn
GCOVProfiling.cpp
Go to the documentation of this file.
1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements GCOV-style profiling. When this pass is run it emits
11 // "gcno" files next to the existing source, and instruments the code that runs
12 // to records the edges between blocks that run and emit a complementary "gcda"
13 // file on exit.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/Hashing.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Sequence.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
26 #include "llvm/IR/CFG.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InstIterator.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/Pass.h"
36 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Path.h"
43 #include <algorithm>
44 #include <memory>
45 #include <string>
46 #include <utility>
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "insert-gcov-profiling"
50 
52 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
54 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
55  cl::init(false), cl::Hidden);
56 
58  GCOVOptions Options;
59  Options.EmitNotes = true;
60  Options.EmitData = true;
61  Options.UseCfgChecksum = false;
62  Options.NoRedZone = false;
63  Options.FunctionNamesInData = true;
65 
66  if (DefaultGCOVVersion.size() != 4) {
67  llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
69  }
70  memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
71  return Options;
72 }
73 
74 namespace {
75 class GCOVFunction;
76 
77 class GCOVProfiler {
78 public:
79  GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
80  GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
81  assert((Options.EmitNotes || Options.EmitData) &&
82  "GCOVProfiler asked to do nothing?");
83  ReversedVersion[0] = Options.Version[3];
84  ReversedVersion[1] = Options.Version[2];
85  ReversedVersion[2] = Options.Version[1];
86  ReversedVersion[3] = Options.Version[0];
87  ReversedVersion[4] = '\0';
88  }
89  bool runOnModule(Module &M, const TargetLibraryInfo &TLI);
90 
91 private:
92  // Create the .gcno files for the Module based on DebugInfo.
93  void emitProfileNotes();
94 
95  // Modify the program to track transitions along edges and call into the
96  // profiling runtime to emit .gcda files when run.
97  bool emitProfileArcs();
98 
99  // Get pointers to the functions in the runtime library.
100  Constant *getStartFileFunc();
101  Constant *getEmitFunctionFunc();
102  Constant *getEmitArcsFunc();
103  Constant *getSummaryInfoFunc();
104  Constant *getEndFileFunc();
105 
106  // Add the function to write out all our counters to the global destructor
107  // list.
108  Function *
109  insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
110  Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
111 
112  enum class GCovFileType { GCNO, GCDA };
113  std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
114 
115  GCOVOptions Options;
116 
117  // Reversed, NUL-terminated copy of Options.Version.
118  char ReversedVersion[5];
119  // Checksum, produced by hash of EdgeDestinations
120  SmallVector<uint32_t, 4> FileChecksums;
121 
122  Module *M;
123  const TargetLibraryInfo *TLI;
124  LLVMContext *Ctx;
126 };
127 
128 class GCOVProfilerLegacyPass : public ModulePass {
129 public:
130  static char ID;
131  GCOVProfilerLegacyPass()
132  : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
133  GCOVProfilerLegacyPass(const GCOVOptions &Opts)
134  : ModulePass(ID), Profiler(Opts) {
136  }
137  StringRef getPassName() const override { return "GCOV Profiler"; }
138 
139  bool runOnModule(Module &M) override {
140  auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
141  return Profiler.runOnModule(M, TLI);
142  }
143 
144  void getAnalysisUsage(AnalysisUsage &AU) const override {
146  }
147 
148 private:
149  GCOVProfiler Profiler;
150 };
151 }
152 
155  GCOVProfilerLegacyPass, "insert-gcov-profiling",
156  "Insert instrumentation for GCOV profiling", false, false)
159  GCOVProfilerLegacyPass, "insert-gcov-profiling",
160  "Insert instrumentation for GCOV profiling", false, false)
161 
163  return new GCOVProfilerLegacyPass(Options);
164 }
165 
167  if (!SP->getLinkageName().empty())
168  return SP->getLinkageName();
169  return SP->getName();
170 }
171 
172 namespace {
173  class GCOVRecord {
174  protected:
175  static const char *const LinesTag;
176  static const char *const FunctionTag;
177  static const char *const BlockTag;
178  static const char *const EdgeTag;
179 
180  GCOVRecord() = default;
181 
182  void writeBytes(const char *Bytes, int Size) {
183  os->write(Bytes, Size);
184  }
185 
186  void write(uint32_t i) {
187  writeBytes(reinterpret_cast<char*>(&i), 4);
188  }
189 
190  // Returns the length measured in 4-byte blocks that will be used to
191  // represent this string in a GCOV file
192  static unsigned lengthOfGCOVString(StringRef s) {
193  // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
194  // padding out to the next 4-byte word. The length is measured in 4-byte
195  // words including padding, not bytes of actual string.
196  return (s.size() / 4) + 1;
197  }
198 
199  void writeGCOVString(StringRef s) {
200  uint32_t Len = lengthOfGCOVString(s);
201  write(Len);
202  writeBytes(s.data(), s.size());
203 
204  // Write 1 to 4 bytes of NUL padding.
205  assert((unsigned)(4 - (s.size() % 4)) > 0);
206  assert((unsigned)(4 - (s.size() % 4)) <= 4);
207  writeBytes("\0\0\0\0", 4 - (s.size() % 4));
208  }
209 
210  raw_ostream *os;
211  };
212  const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
213  const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
214  const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
215  const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
216 
217  class GCOVFunction;
218  class GCOVBlock;
219 
220  // Constructed only by requesting it from a GCOVBlock, this object stores a
221  // list of line numbers and a single filename, representing lines that belong
222  // to the block.
223  class GCOVLines : public GCOVRecord {
224  public:
225  void addLine(uint32_t Line) {
226  assert(Line != 0 && "Line zero is not a valid real line number.");
227  Lines.push_back(Line);
228  }
229 
230  uint32_t length() const {
231  // Here 2 = 1 for string length + 1 for '0' id#.
232  return lengthOfGCOVString(Filename) + 2 + Lines.size();
233  }
234 
235  void writeOut() {
236  write(0);
237  writeGCOVString(Filename);
238  for (int i = 0, e = Lines.size(); i != e; ++i)
239  write(Lines[i]);
240  }
241 
242  GCOVLines(StringRef F, raw_ostream *os)
243  : Filename(F) {
244  this->os = os;
245  }
246 
247  private:
248  StringRef Filename;
250  };
251 
252 
253  // Represent a basic block in GCOV. Each block has a unique number in the
254  // function, number of lines belonging to each block, and a set of edges to
255  // other blocks.
256  class GCOVBlock : public GCOVRecord {
257  public:
258  GCOVLines &getFile(StringRef Filename) {
259  return LinesByFile.try_emplace(Filename, Filename, os).first->second;
260  }
261 
262  void addEdge(GCOVBlock &Successor) {
263  OutEdges.push_back(&Successor);
264  }
265 
266  void writeOut() {
267  uint32_t Len = 3;
268  SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
269  for (auto &I : LinesByFile) {
270  Len += I.second.length();
271  SortedLinesByFile.push_back(&I);
272  }
273 
274  writeBytes(LinesTag, 4);
275  write(Len);
276  write(Number);
277 
278  llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
280  return LHS->getKey() < RHS->getKey();
281  });
282  for (auto &I : SortedLinesByFile)
283  I->getValue().writeOut();
284  write(0);
285  write(0);
286  }
287 
288  GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
289  // Only allow copy before edges and lines have been added. After that,
290  // there are inter-block pointers (eg: edges) that won't take kindly to
291  // blocks being copied or moved around.
292  assert(LinesByFile.empty());
293  assert(OutEdges.empty());
294  }
295 
296  private:
297  friend class GCOVFunction;
298 
300  : Number(Number) {
301  this->os = os;
302  }
303 
305  StringMap<GCOVLines> LinesByFile;
307  };
308 
309  // A function has a unique identifier, a checksum (we leave as zero) and a
310  // set of blocks and a map of edges between blocks. This is the only GCOV
311  // object users can construct, the blocks and lines will be rooted here.
312  class GCOVFunction : public GCOVRecord {
313  public:
315  uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
316  : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
317  ReturnBlock(1, os) {
318  this->os = os;
319 
320  LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
321 
322  uint32_t i = 0;
323  for (auto &BB : *F) {
324  // Skip index 1 if it's assigned to the ReturnBlock.
325  if (i == 1 && ExitBlockBeforeBody)
326  ++i;
327  Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
328  }
329  if (!ExitBlockBeforeBody)
330  ReturnBlock.Number = i;
331 
332  std::string FunctionNameAndLine;
333  raw_string_ostream FNLOS(FunctionNameAndLine);
334  FNLOS << getFunctionName(SP) << SP->getLine();
335  FNLOS.flush();
336  FuncChecksum = hash_value(FunctionNameAndLine);
337  }
338 
339  GCOVBlock &getBlock(BasicBlock *BB) {
340  return Blocks.find(BB)->second;
341  }
342 
343  GCOVBlock &getReturnBlock() {
344  return ReturnBlock;
345  }
346 
347  std::string getEdgeDestinations() {
348  std::string EdgeDestinations;
349  raw_string_ostream EDOS(EdgeDestinations);
350  Function *F = Blocks.begin()->first->getParent();
351  for (BasicBlock &I : *F) {
352  GCOVBlock &Block = getBlock(&I);
353  for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
354  EDOS << Block.OutEdges[i]->Number;
355  }
356  return EdgeDestinations;
357  }
358 
359  uint32_t getFuncChecksum() {
360  return FuncChecksum;
361  }
362 
363  void setCfgChecksum(uint32_t Checksum) {
364  CfgChecksum = Checksum;
365  }
366 
367  void writeOut() {
368  writeBytes(FunctionTag, 4);
369  uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
370  1 + lengthOfGCOVString(SP->getFilename()) + 1;
371  if (UseCfgChecksum)
372  ++BlockLen;
373  write(BlockLen);
374  write(Ident);
375  write(FuncChecksum);
376  if (UseCfgChecksum)
377  write(CfgChecksum);
378  writeGCOVString(getFunctionName(SP));
379  writeGCOVString(SP->getFilename());
380  write(SP->getLine());
381 
382  // Emit count of blocks.
383  writeBytes(BlockTag, 4);
384  write(Blocks.size() + 1);
385  for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
386  write(0); // No flags on our blocks.
387  }
388  LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n");
389 
390  // Emit edges between blocks.
391  if (Blocks.empty()) return;
392  Function *F = Blocks.begin()->first->getParent();
393  for (BasicBlock &I : *F) {
394  GCOVBlock &Block = getBlock(&I);
395  if (Block.OutEdges.empty()) continue;
396 
397  writeBytes(EdgeTag, 4);
398  write(Block.OutEdges.size() * 2 + 1);
399  write(Block.Number);
400  for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
401  LLVM_DEBUG(dbgs() << Block.Number << " -> "
402  << Block.OutEdges[i]->Number << "\n");
403  write(Block.OutEdges[i]->Number);
404  write(0); // no flags
405  }
406  }
407 
408  // Emit lines for each block.
409  for (BasicBlock &I : *F)
410  getBlock(&I).writeOut();
411  }
412 
413  private:
414  const DISubprogram *SP;
415  uint32_t Ident;
416  uint32_t FuncChecksum;
417  bool UseCfgChecksum;
418  uint32_t CfgChecksum;
420  GCOVBlock ReturnBlock;
421  };
422 }
423 
424 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
425  GCovFileType OutputType) {
426  bool Notes = OutputType == GCovFileType::GCNO;
427 
428  if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
429  for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
430  MDNode *N = GCov->getOperand(i);
431  bool ThreeElement = N->getNumOperands() == 3;
432  if (!ThreeElement && N->getNumOperands() != 2)
433  continue;
434  if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
435  continue;
436 
437  if (ThreeElement) {
438  // These nodes have no mangling to apply, it's stored mangled in the
439  // bitcode.
440  MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
441  MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
442  if (!NotesFile || !DataFile)
443  continue;
444  return Notes ? NotesFile->getString() : DataFile->getString();
445  }
446 
447  MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
448  if (!GCovFile)
449  continue;
450 
451  SmallString<128> Filename = GCovFile->getString();
452  sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
453  return Filename.str();
454  }
455  }
456 
457  SmallString<128> Filename = CU->getFilename();
458  sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
459  StringRef FName = sys::path::filename(Filename);
460  SmallString<128> CurPath;
461  if (sys::fs::current_path(CurPath)) return FName;
462  sys::path::append(CurPath, FName);
463  return CurPath.str();
464 }
465 
466 bool GCOVProfiler::runOnModule(Module &M, const TargetLibraryInfo &TLI) {
467  this->M = &M;
468  this->TLI = &TLI;
469  Ctx = &M.getContext();
470 
471  if (Options.EmitNotes) emitProfileNotes();
472  if (Options.EmitData) return emitProfileArcs();
473  return false;
474 }
475 
477  ModuleAnalysisManager &AM) {
478 
479  GCOVProfiler Profiler(GCOVOpts);
480 
481  auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
482  if (!Profiler.runOnModule(M, TLI))
483  return PreservedAnalyses::all();
484 
485  return PreservedAnalyses::none();
486 }
487 
488 static bool functionHasLines(Function &F) {
489  // Check whether this function actually has any source lines. Not only
490  // do these waste space, they also can crash gcov.
491  for (auto &BB : F) {
492  for (auto &I : BB) {
493  // Debug intrinsic locations correspond to the location of the
494  // declaration, not necessarily any statements or expressions.
495  if (isa<DbgInfoIntrinsic>(&I)) continue;
496 
497  const DebugLoc &Loc = I.getDebugLoc();
498  if (!Loc)
499  continue;
500 
501  // Artificial lines such as calls to the global constructors.
502  if (Loc.getLine() == 0) continue;
503 
504  return true;
505  }
506  }
507  return false;
508 }
509 
511  if (!F.hasPersonalityFn()) return false;
512 
514  return isScopedEHPersonality(Personality);
515 }
516 
518  if (isa<AllocaInst>(*It)) return true;
519  if (isa<DbgInfoIntrinsic>(*It)) return true;
520  if (auto *II = dyn_cast<IntrinsicInst>(It)) {
521  if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
522  }
523 
524  return false;
525 }
526 
527 void GCOVProfiler::emitProfileNotes() {
528  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
529  if (!CU_Nodes) return;
530 
531  for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
532  // Each compile unit gets its own .gcno file. This means that whether we run
533  // this pass over the original .o's as they're produced, or run it after
534  // LTO, we'll generate the same .gcno files.
535 
536  auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
537 
538  // Skip module skeleton (and module) CUs.
539  if (CU->getDWOId())
540  continue;
541 
542  std::error_code EC;
543  raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
544  if (EC) {
545  Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
546  EC.message());
547  continue;
548  }
549 
550  std::string EdgeDestinations;
551 
552  unsigned FunctionIdent = 0;
553  for (auto &F : M->functions()) {
554  DISubprogram *SP = F.getSubprogram();
555  if (!SP) continue;
556  if (!functionHasLines(F)) continue;
557  // TODO: Functions using scope-based EH are currently not supported.
558  if (isUsingScopeBasedEH(F)) continue;
559 
560  // gcov expects every function to start with an entry block that has a
561  // single successor, so split the entry block to make sure of that.
562  BasicBlock &EntryBlock = F.getEntryBlock();
563  BasicBlock::iterator It = EntryBlock.begin();
564  while (shouldKeepInEntry(It))
565  ++It;
566  EntryBlock.splitBasicBlock(It);
567 
568  Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
569  Options.UseCfgChecksum,
570  Options.ExitBlockBeforeBody));
571  GCOVFunction &Func = *Funcs.back();
572 
573  // Add the function line number to the lines of the entry block
574  // to have a counter for the function definition.
575  Func.getBlock(&EntryBlock)
576  .getFile(SP->getFilename())
577  .addLine(SP->getLine());
578 
579  for (auto &BB : F) {
580  GCOVBlock &Block = Func.getBlock(&BB);
581  Instruction *TI = BB.getTerminator();
582  if (int successors = TI->getNumSuccessors()) {
583  for (int i = 0; i != successors; ++i) {
584  Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
585  }
586  } else if (isa<ReturnInst>(TI)) {
587  Block.addEdge(Func.getReturnBlock());
588  }
589 
590  uint32_t Line = 0;
591  for (auto &I : BB) {
592  // Debug intrinsic locations correspond to the location of the
593  // declaration, not necessarily any statements or expressions.
594  if (isa<DbgInfoIntrinsic>(&I)) continue;
595 
596  const DebugLoc &Loc = I.getDebugLoc();
597  if (!Loc)
598  continue;
599 
600  // Artificial lines such as calls to the global constructors.
601  if (Loc.getLine() == 0 || Loc.isImplicitCode())
602  continue;
603 
604  if (Line == Loc.getLine()) continue;
605  Line = Loc.getLine();
606  if (SP != getDISubprogram(Loc.getScope()))
607  continue;
608 
609  GCOVLines &Lines = Block.getFile(SP->getFilename());
610  Lines.addLine(Loc.getLine());
611  }
612  }
613  EdgeDestinations += Func.getEdgeDestinations();
614  }
615 
616  FileChecksums.push_back(hash_value(EdgeDestinations));
617  out.write("oncg", 4);
618  out.write(ReversedVersion, 4);
619  out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
620 
621  for (auto &Func : Funcs) {
622  Func->setCfgChecksum(FileChecksums.back());
623  Func->writeOut();
624  }
625 
626  out.write("\0\0\0\0\0\0\0\0", 8); // EOF
627  out.close();
628  }
629 }
630 
631 bool GCOVProfiler::emitProfileArcs() {
632  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
633  if (!CU_Nodes) return false;
634 
635  bool Result = false;
636  for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
638  for (auto &F : M->functions()) {
639  DISubprogram *SP = F.getSubprogram();
640  if (!SP) continue;
641  if (!functionHasLines(F)) continue;
642  // TODO: Functions using scope-based EH are currently not supported.
643  if (isUsingScopeBasedEH(F)) continue;
644  if (!Result) Result = true;
645 
646  DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
647  unsigned Edges = 0;
648  for (auto &BB : F) {
649  Instruction *TI = BB.getTerminator();
650  if (isa<ReturnInst>(TI)) {
651  EdgeToCounter[{&BB, nullptr}] = Edges++;
652  } else {
653  for (BasicBlock *Succ : successors(TI)) {
654  EdgeToCounter[{&BB, Succ}] = Edges++;
655  }
656  }
657  }
658 
659  ArrayType *CounterTy =
660  ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
661  GlobalVariable *Counters =
662  new GlobalVariable(*M, CounterTy, false,
664  Constant::getNullValue(CounterTy),
665  "__llvm_gcov_ctr");
666  CountersBySP.push_back(std::make_pair(Counters, SP));
667 
668  // If a BB has several predecessors, use a PHINode to select
669  // the correct counter.
670  for (auto &BB : F) {
671  const unsigned EdgeCount =
672  std::distance(pred_begin(&BB), pred_end(&BB));
673  if (EdgeCount) {
674  // The phi node must be at the begin of the BB.
675  IRBuilder<> BuilderForPhi(&*BB.begin());
676  Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
677  PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
678  for (BasicBlock *Pred : predecessors(&BB)) {
679  auto It = EdgeToCounter.find({Pred, &BB});
680  assert(It != EdgeToCounter.end());
681  const unsigned Edge = It->second;
682  Value *EdgeCounter =
683  BuilderForPhi.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
684  Phi->addIncoming(EdgeCounter, Pred);
685  }
686 
687  // Skip phis, landingpads.
688  IRBuilder<> Builder(&*BB.getFirstInsertionPt());
689  Value *Count = Builder.CreateLoad(Phi);
690  Count = Builder.CreateAdd(Count, Builder.getInt64(1));
691  Builder.CreateStore(Count, Phi);
692 
693  Instruction *TI = BB.getTerminator();
694  if (isa<ReturnInst>(TI)) {
695  auto It = EdgeToCounter.find({&BB, nullptr});
696  assert(It != EdgeToCounter.end());
697  const unsigned Edge = It->second;
698  Value *Counter =
699  Builder.CreateConstInBoundsGEP2_64(Counters, 0, Edge);
700  Value *Count = Builder.CreateLoad(Counter);
701  Count = Builder.CreateAdd(Count, Builder.getInt64(1));
702  Builder.CreateStore(Count, Counter);
703  }
704  }
705  }
706  }
707 
708  Function *WriteoutF = insertCounterWriteout(CountersBySP);
709  Function *FlushF = insertFlush(CountersBySP);
710 
711  // Create a small bit of code that registers the "__llvm_gcov_writeout" to
712  // be executed at exit and the "__llvm_gcov_flush" function to be executed
713  // when "__gcov_flush" is called.
714  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
716  "__llvm_gcov_init", M);
719  F->addFnAttr(Attribute::NoInline);
720  if (Options.NoRedZone)
721  F->addFnAttr(Attribute::NoRedZone);
722 
723  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
724  IRBuilder<> Builder(BB);
725 
726  FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
727  Type *Params[] = {
728  PointerType::get(FTy, 0),
729  PointerType::get(FTy, 0)
730  };
731  FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
732 
733  // Initialize the environment and register the local writeout and flush
734  // functions.
735  Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
736  Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
737  Builder.CreateRetVoid();
738 
739  appendToGlobalCtors(*M, F, 0);
740  }
741 
742  return Result;
743 }
744 
745 Constant *GCOVProfiler::getStartFileFunc() {
746  Type *Args[] = {
747  Type::getInt8PtrTy(*Ctx), // const char *orig_filename
748  Type::getInt8PtrTy(*Ctx), // const char version[4]
749  Type::getInt32Ty(*Ctx), // uint32_t checksum
750  };
751  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
752  auto *Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy);
753  if (Function *FunRes = dyn_cast<Function>(Res))
754  if (auto AK = TLI->getExtAttrForI32Param(false))
755  FunRes->addParamAttr(2, AK);
756  return Res;
757 
758 }
759 
760 Constant *GCOVProfiler::getEmitFunctionFunc() {
761  Type *Args[] = {
762  Type::getInt32Ty(*Ctx), // uint32_t ident
763  Type::getInt8PtrTy(*Ctx), // const char *function_name
764  Type::getInt32Ty(*Ctx), // uint32_t func_checksum
765  Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
766  Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
767  };
768  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
769  auto *Res = M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
770  if (Function *FunRes = dyn_cast<Function>(Res))
771  if (auto AK = TLI->getExtAttrForI32Param(false)) {
772  FunRes->addParamAttr(0, AK);
773  FunRes->addParamAttr(2, AK);
774  FunRes->addParamAttr(3, AK);
775  FunRes->addParamAttr(4, AK);
776  }
777  return Res;
778 }
779 
780 Constant *GCOVProfiler::getEmitArcsFunc() {
781  Type *Args[] = {
782  Type::getInt32Ty(*Ctx), // uint32_t num_counters
783  Type::getInt64PtrTy(*Ctx), // uint64_t *counters
784  };
785  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
786  auto *Res = M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
787  if (Function *FunRes = dyn_cast<Function>(Res))
788  if (auto AK = TLI->getExtAttrForI32Param(false))
789  FunRes->addParamAttr(0, AK);
790  return Res;
791 }
792 
793 Constant *GCOVProfiler::getSummaryInfoFunc() {
794  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
795  return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
796 }
797 
798 Constant *GCOVProfiler::getEndFileFunc() {
799  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
800  return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
801 }
802 
803 Function *GCOVProfiler::insertCounterWriteout(
804  ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
805  FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
806  Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
807  if (!WriteoutF)
808  WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
809  "__llvm_gcov_writeout", M);
811  WriteoutF->addFnAttr(Attribute::NoInline);
812  if (Options.NoRedZone)
813  WriteoutF->addFnAttr(Attribute::NoRedZone);
814 
815  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
816  IRBuilder<> Builder(BB);
817 
818  Constant *StartFile = getStartFileFunc();
819  Constant *EmitFunction = getEmitFunctionFunc();
820  Constant *EmitArcs = getEmitArcsFunc();
821  Constant *SummaryInfo = getSummaryInfoFunc();
822  Constant *EndFile = getEndFileFunc();
823 
824  NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
825  if (!CUNodes) {
826  Builder.CreateRetVoid();
827  return WriteoutF;
828  }
829 
830  // Collect the relevant data into a large constant data structure that we can
831  // walk to write out everything.
832  StructType *StartFileCallArgsTy = StructType::create(
833  {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
834  StructType *EmitFunctionCallArgsTy = StructType::create(
835  {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
836  Builder.getInt8Ty(), Builder.getInt32Ty()});
837  StructType *EmitArcsCallArgsTy = StructType::create(
838  {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
839  StructType *FileInfoTy =
840  StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
841  EmitFunctionCallArgsTy->getPointerTo(),
842  EmitArcsCallArgsTy->getPointerTo()});
843 
844  Constant *Zero32 = Builder.getInt32(0);
845  // Build an explicit array of two zeros for use in ConstantExpr GEP building.
846  Constant *TwoZero32s[] = {Zero32, Zero32};
847 
848  SmallVector<Constant *, 8> FileInfos;
849  for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
850  auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
851 
852  // Skip module skeleton (and module) CUs.
853  if (CU->getDWOId())
854  continue;
855 
856  std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
857  uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
858  auto *StartFileCallArgs = ConstantStruct::get(
859  StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
860  Builder.CreateGlobalStringPtr(ReversedVersion),
861  Builder.getInt32(CfgChecksum)});
862 
863  SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
864  SmallVector<Constant *, 8> EmitArcsCallArgsArray;
865  for (int j : llvm::seq<int>(0, CountersBySP.size())) {
866  auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
867  uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
868  EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
869  EmitFunctionCallArgsTy,
870  {Builder.getInt32(j),
871  Options.FunctionNamesInData
874  Builder.getInt32(FuncChecksum),
875  Builder.getInt8(Options.UseCfgChecksum),
876  Builder.getInt32(CfgChecksum)}));
877 
878  GlobalVariable *GV = CountersBySP[j].first;
879  unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
880  EmitArcsCallArgsArray.push_back(ConstantStruct::get(
881  EmitArcsCallArgsTy,
883  GV->getValueType(), GV, TwoZero32s)}));
884  }
885  // Create global arrays for the two emit calls.
886  int CountersSize = CountersBySP.size();
887  assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
888  "Mismatched array size!");
889  assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
890  "Mismatched array size!");
891  auto *EmitFunctionCallArgsArrayTy =
892  ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
893  auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
894  *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
896  ConstantArray::get(EmitFunctionCallArgsArrayTy,
897  EmitFunctionCallArgsArray),
898  Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
899  auto *EmitArcsCallArgsArrayTy =
900  ArrayType::get(EmitArcsCallArgsTy, CountersSize);
901  EmitFunctionCallArgsArrayGV->setUnnamedAddr(
903  auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
904  *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
906  ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
907  Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
908  EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
909 
910  FileInfos.push_back(ConstantStruct::get(
911  FileInfoTy,
912  {StartFileCallArgs, Builder.getInt32(CountersSize),
913  ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
914  EmitFunctionCallArgsArrayGV,
915  TwoZero32s),
917  EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
918  }
919 
920  // If we didn't find anything to actually emit, bail on out.
921  if (FileInfos.empty()) {
922  Builder.CreateRetVoid();
923  return WriteoutF;
924  }
925 
926  // To simplify code, we cap the number of file infos we write out to fit
927  // easily in a 32-bit signed integer. This gives consistent behavior between
928  // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
929  // operations on 32-bit systems. It also seems unreasonable to try to handle
930  // more than 2 billion files.
931  if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
932  FileInfos.resize(INT_MAX);
933 
934  // Create a global for the entire data structure so we can walk it more
935  // easily.
936  auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
937  auto *FileInfoArrayGV = new GlobalVariable(
938  *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
939  ConstantArray::get(FileInfoArrayTy, FileInfos),
940  "__llvm_internal_gcov_emit_file_info");
941  FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
942 
943  // Create the CFG for walking this data structure.
944  auto *FileLoopHeader =
945  BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
946  auto *CounterLoopHeader =
947  BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
948  auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
949  auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
950 
951  // We always have at least one file, so just branch to the header.
952  Builder.CreateBr(FileLoopHeader);
953 
954  // The index into the files structure is our loop induction variable.
955  Builder.SetInsertPoint(FileLoopHeader);
956  PHINode *IV =
957  Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
958  IV->addIncoming(Builder.getInt32(0), BB);
959  auto *FileInfoPtr =
960  Builder.CreateInBoundsGEP(FileInfoArrayGV, {Builder.getInt32(0), IV});
961  auto *StartFileCallArgsPtr = Builder.CreateStructGEP(FileInfoPtr, 0);
962  auto *StartFileCall = Builder.CreateCall(
963  StartFile,
964  {Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 0)),
965  Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 1)),
966  Builder.CreateLoad(Builder.CreateStructGEP(StartFileCallArgsPtr, 2))});
967  if (auto AK = TLI->getExtAttrForI32Param(false))
968  StartFileCall->addParamAttr(2, AK);
969  auto *NumCounters =
970  Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 1));
971  auto *EmitFunctionCallArgsArray =
972  Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 2));
973  auto *EmitArcsCallArgsArray =
974  Builder.CreateLoad(Builder.CreateStructGEP(FileInfoPtr, 3));
975  auto *EnterCounterLoopCond =
976  Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
977  Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
978 
979  Builder.SetInsertPoint(CounterLoopHeader);
980  auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
981  JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
982  auto *EmitFunctionCallArgsPtr =
983  Builder.CreateInBoundsGEP(EmitFunctionCallArgsArray, {JV});
984  auto *EmitFunctionCall = Builder.CreateCall(
985  EmitFunction,
986  {Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 0)),
987  Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 1)),
988  Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 2)),
989  Builder.CreateLoad(Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 3)),
990  Builder.CreateLoad(
991  Builder.CreateStructGEP(EmitFunctionCallArgsPtr, 4))});
992  if (auto AK = TLI->getExtAttrForI32Param(false)) {
993  EmitFunctionCall->addParamAttr(0, AK);
994  EmitFunctionCall->addParamAttr(2, AK);
995  EmitFunctionCall->addParamAttr(3, AK);
996  EmitFunctionCall->addParamAttr(4, AK);
997  }
998  auto *EmitArcsCallArgsPtr =
999  Builder.CreateInBoundsGEP(EmitArcsCallArgsArray, {JV});
1000  auto *EmitArcsCall = Builder.CreateCall(
1001  EmitArcs,
1002  {Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 0)),
1003  Builder.CreateLoad(Builder.CreateStructGEP(EmitArcsCallArgsPtr, 1))});
1004  if (auto AK = TLI->getExtAttrForI32Param(false))
1005  EmitArcsCall->addParamAttr(0, AK);
1006  auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1007  auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1008  Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1009  JV->addIncoming(NextJV, CounterLoopHeader);
1010 
1011  Builder.SetInsertPoint(FileLoopLatch);
1012  Builder.CreateCall(SummaryInfo, {});
1013  Builder.CreateCall(EndFile, {});
1014  auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1015  auto *FileLoopCond =
1016  Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1017  Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1018  IV->addIncoming(NextIV, FileLoopLatch);
1019 
1020  Builder.SetInsertPoint(ExitBB);
1021  Builder.CreateRetVoid();
1022 
1023  return WriteoutF;
1024 }
1025 
1026 Function *GCOVProfiler::
1027 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1028  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1029  Function *FlushF = M->getFunction("__llvm_gcov_flush");
1030  if (!FlushF)
1032  "__llvm_gcov_flush", M);
1033  else
1036  FlushF->addFnAttr(Attribute::NoInline);
1037  if (Options.NoRedZone)
1038  FlushF->addFnAttr(Attribute::NoRedZone);
1039 
1040  BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1041 
1042  // Write out the current counters.
1043  Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1044  assert(WriteoutF && "Need to create the writeout function first!");
1045 
1046  IRBuilder<> Builder(Entry);
1047  Builder.CreateCall(WriteoutF, {});
1048 
1049  // Zero out the counters.
1050  for (const auto &I : CountersBySP) {
1051  GlobalVariable *GV = I.first;
1053  Builder.CreateStore(Null, GV);
1054  }
1055 
1056  Type *RetTy = FlushF->getReturnType();
1057  if (RetTy == Type::getVoidTy(*Ctx))
1058  Builder.CreateRetVoid();
1059  else if (RetTy->isIntegerTy())
1060  // Used if __llvm_gcov_flush was implicitly declared.
1061  Builder.CreateRet(ConstantInt::get(RetTy, 0));
1062  else
1063  report_fatal_error("invalid return type for __llvm_gcov_flush");
1064 
1065  return FlushF;
1066 }
static StringRef getFunctionName(TargetLowering::CallLoweringInfo &CLI)
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1405
This routine provides some synthesis utilities to produce sequences of values.
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional &#39;br Cond, TrueDest, FalseDest&#39; instruction.
Definition: IRBuilder.h:854
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1081
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:770
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Definition: StringMap.h:126
ModulePass * createGCOVProfilerPass(const GCOVOptions &Options=GCOVOptions::getDefault())
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
static cl::opt< bool > DefaultExitBlockBeforeBody("gcov-exit-block-before-body", cl::init(false), cl::Hidden)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
static GCOVOptions getDefault()
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1780
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:617
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
unsigned getLine() const
Definition: DebugLoc.cpp:26
uint64_t getDWOId() const
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:864
F(f)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1069
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
static PointerType * getInt64PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:232
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:960
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:268
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:263
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:347
Attribute::AttrKind getExtAttrForI32Param(bool Signed=true) const
Returns extension attribute kind to be used for i32 parameters corresponding to C-level int or unsign...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:480
A tuple of MDNodes.
Definition: Metadata.h:1326
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:352
bool isImplicitCode() const
Check if the DebugLoc corresponds to an implicit code.
Definition: DebugLoc.cpp:59
Class to represent struct types.
Definition: DerivedTypes.h:201
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:243
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:639
ReturnInst * CreateRet(Value *V)
Create a &#39;ret <val>&#39; instruction.
Definition: IRBuilder.h:829
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:743
unsigned getNumOperands() const
Definition: Metadata.cpp:1077
static bool isUsingScopeBasedEH(Function &F)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:974
DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
Definition: DebugInfo.cpp:44
StringRef getFilename() const
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:380
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch, catchpad/ret, and cleanuppad/ret.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1333
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:267
Subprogram description.
Class to represent function types.
Definition: DerivedTypes.h:103
This file provides the interface for the GCOV style profiler pass.
Class to represent array types.
Definition: DerivedTypes.h:369
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:245
GCOVBlock - Collects block information.
Definition: GCOV.h:312
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition: APFloat.cpp:4431
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:702
iterator begin()
Definition: Function.h:656
static void addEdge(SmallVectorImpl< LazyCallGraph::Edge > &Edges, DenseMap< LazyCallGraph::Node *, int > &EdgeIndexMap, LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:127
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
StringRef getString() const
Definition: Metadata.cpp:464
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool&#39; fo...
Definition: IRBuilder.h:1317
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:410
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:169
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
iterator_range< iterator > functions()
Definition: Module.h:596
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
This is an important base class in LLVM.
Definition: Constant.h:42
StringRef getKey() const
Definition: StringMap.h:137
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:113
INITIALIZE_PASS_BEGIN(GCOVProfilerLegacyPass, "insert-gcov-profiling", "Insert instrumentation for GCOV profiling", false, false) INITIALIZE_PASS_END(GCOVProfilerLegacyPass
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:297
static Constant * get(StructType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1021
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:100
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:312
MDNode * getScope() const
Definition: DebugLoc.cpp:36
static void write(bool isBE, void *P, T V)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
size_t size() const
Definition: SmallVector.h:53
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:385
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
raw_ostream & write(unsigned char C)
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:972
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:1878
Iterator for intrusive lists based on ilist_node.
static bool functionHasLines(Function &F)
StringRef getName() const
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition: Path.cpp:505
void initializeGCOVProfilerLegacyPassPass(PassRegistry &)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:307
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:621
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:84
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:123
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:445
Constant * CreateGlobalStringPtr(StringRef Str, const Twine &Name="", unsigned AddressSpace=0)
Same as CreateGlobalString, but return a pointer with "i8*" type instead of a pointer to array of i8...
Definition: IRBuilder.h:1551
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:175
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:220
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:337
static bool shouldKeepInEntry(BasicBlock::iterator It)
static cl::opt< std::string > DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden, cl::ValueRequired)
ReturnInst * CreateRetVoid()
Create a &#39;ret void&#39; instruction.
Definition: IRBuilder.h:824
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
GCOVFunction - Collects function information.
Definition: GCOV.h:275
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:366
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:216
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:590
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList)
Create an "inbounds" getelementptr.
Definition: Constants.h:1170
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:568
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Type * getValueType() const
Definition: GlobalValue.h:276
uint32_t Size
Definition: Profile.cpp:47
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:402
void close()
Manually flush the stream and close the file.
Analysis pass providing the TargetLibraryInfo.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:483
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1302
succ_range successors(Instruction *I)
Definition: CFG.h:262
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional &#39;br label X&#39; instruction.
Definition: IRBuilder.h:848
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:424
Value * CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, const Twine &Name="")
Definition: IRBuilder.h:1540
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:230
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition: IRBuilder.h:297
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:604
A container for analyses that lazily runs them and caches their results.
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1075
#define LLVM_DEBUG(X)
Definition: Debug.h:123
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1883
void resize(size_type N)
Definition: SmallVector.h:351