LLVM  6.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/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/UniqueVector.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DebugLoc.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Pass.h"
34 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Path.h"
41 #include <algorithm>
42 #include <memory>
43 #include <string>
44 #include <utility>
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "insert-gcov-profiling"
48 
50 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
52 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
53  cl::init(false), cl::Hidden);
54 
56  GCOVOptions Options;
57  Options.EmitNotes = true;
58  Options.EmitData = true;
59  Options.UseCfgChecksum = false;
60  Options.NoRedZone = false;
61  Options.FunctionNamesInData = true;
63 
64  if (DefaultGCOVVersion.size() != 4) {
65  llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
67  }
68  memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
69  return Options;
70 }
71 
72 namespace {
73 class GCOVFunction;
74 
75 class GCOVProfiler {
76 public:
77  GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
78  GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
79  assert((Options.EmitNotes || Options.EmitData) &&
80  "GCOVProfiler asked to do nothing?");
81  ReversedVersion[0] = Options.Version[3];
82  ReversedVersion[1] = Options.Version[2];
83  ReversedVersion[2] = Options.Version[1];
84  ReversedVersion[3] = Options.Version[0];
85  ReversedVersion[4] = '\0';
86  }
87  bool runOnModule(Module &M);
88 
89 private:
90  // Create the .gcno files for the Module based on DebugInfo.
91  void emitProfileNotes();
92 
93  // Modify the program to track transitions along edges and call into the
94  // profiling runtime to emit .gcda files when run.
95  bool emitProfileArcs();
96 
97  // Get pointers to the functions in the runtime library.
98  Constant *getStartFileFunc();
99  Constant *getIncrementIndirectCounterFunc();
100  Constant *getEmitFunctionFunc();
101  Constant *getEmitArcsFunc();
102  Constant *getSummaryInfoFunc();
103  Constant *getEndFileFunc();
104 
105  // Create or retrieve an i32 state value that is used to represent the
106  // pred block number for certain non-trivial edges.
107  GlobalVariable *getEdgeStateValue();
108 
109  // Produce a table of pointers to counters, by predecessor and successor
110  // block number.
111  GlobalVariable *buildEdgeLookupTable(Function *F, GlobalVariable *Counter,
112  const UniqueVector<BasicBlock *> &Preds,
113  const UniqueVector<BasicBlock *> &Succs);
114 
115  // Add the function to write out all our counters to the global destructor
116  // list.
117  Function *
118  insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
119  Function *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
120  void insertIndirectCounterIncrement();
121 
122  enum class GCovFileType { GCNO, GCDA };
123  std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
124 
125  GCOVOptions Options;
126 
127  // Reversed, NUL-terminated copy of Options.Version.
128  char ReversedVersion[5];
129  // Checksum, produced by hash of EdgeDestinations
130  SmallVector<uint32_t, 4> FileChecksums;
131 
132  Module *M;
133  LLVMContext *Ctx;
135 };
136 
137 class GCOVProfilerLegacyPass : public ModulePass {
138 public:
139  static char ID;
140  GCOVProfilerLegacyPass()
141  : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
142  GCOVProfilerLegacyPass(const GCOVOptions &Opts)
143  : ModulePass(ID), Profiler(Opts) {
145  }
146  StringRef getPassName() const override { return "GCOV Profiler"; }
147 
148  bool runOnModule(Module &M) override { return Profiler.runOnModule(M); }
149 
150 private:
151  GCOVProfiler Profiler;
152 };
153 }
154 
156 INITIALIZE_PASS(GCOVProfilerLegacyPass, "insert-gcov-profiling",
157  "Insert instrumentation for GCOV profiling", false, false)
158 
160  return new GCOVProfilerLegacyPass(Options);
161 }
162 
164  if (!SP->getLinkageName().empty())
165  return SP->getLinkageName();
166  return SP->getName();
167 }
168 
169 namespace {
170  class GCOVRecord {
171  protected:
172  static const char *const LinesTag;
173  static const char *const FunctionTag;
174  static const char *const BlockTag;
175  static const char *const EdgeTag;
176 
177  GCOVRecord() = default;
178 
179  void writeBytes(const char *Bytes, int Size) {
180  os->write(Bytes, Size);
181  }
182 
183  void write(uint32_t i) {
184  writeBytes(reinterpret_cast<char*>(&i), 4);
185  }
186 
187  // Returns the length measured in 4-byte blocks that will be used to
188  // represent this string in a GCOV file
189  static unsigned lengthOfGCOVString(StringRef s) {
190  // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
191  // padding out to the next 4-byte word. The length is measured in 4-byte
192  // words including padding, not bytes of actual string.
193  return (s.size() / 4) + 1;
194  }
195 
196  void writeGCOVString(StringRef s) {
197  uint32_t Len = lengthOfGCOVString(s);
198  write(Len);
199  writeBytes(s.data(), s.size());
200 
201  // Write 1 to 4 bytes of NUL padding.
202  assert((unsigned)(4 - (s.size() % 4)) > 0);
203  assert((unsigned)(4 - (s.size() % 4)) <= 4);
204  writeBytes("\0\0\0\0", 4 - (s.size() % 4));
205  }
206 
207  raw_ostream *os;
208  };
209  const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
210  const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
211  const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
212  const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
213 
214  class GCOVFunction;
215  class GCOVBlock;
216 
217  // Constructed only by requesting it from a GCOVBlock, this object stores a
218  // list of line numbers and a single filename, representing lines that belong
219  // to the block.
220  class GCOVLines : public GCOVRecord {
221  public:
222  void addLine(uint32_t Line) {
223  assert(Line != 0 && "Line zero is not a valid real line number.");
224  Lines.push_back(Line);
225  }
226 
227  uint32_t length() const {
228  // Here 2 = 1 for string length + 1 for '0' id#.
229  return lengthOfGCOVString(Filename) + 2 + Lines.size();
230  }
231 
232  void writeOut() {
233  write(0);
234  writeGCOVString(Filename);
235  for (int i = 0, e = Lines.size(); i != e; ++i)
236  write(Lines[i]);
237  }
238 
239  GCOVLines(StringRef F, raw_ostream *os)
240  : Filename(F) {
241  this->os = os;
242  }
243 
244  private:
245  StringRef Filename;
247  };
248 
249 
250  // Represent a basic block in GCOV. Each block has a unique number in the
251  // function, number of lines belonging to each block, and a set of edges to
252  // other blocks.
253  class GCOVBlock : public GCOVRecord {
254  public:
255  GCOVLines &getFile(StringRef Filename) {
256  return LinesByFile.try_emplace(Filename, Filename, os).first->second;
257  }
258 
259  void addEdge(GCOVBlock &Successor) {
260  OutEdges.push_back(&Successor);
261  }
262 
263  void writeOut() {
264  uint32_t Len = 3;
265  SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
266  for (auto &I : LinesByFile) {
267  Len += I.second.length();
268  SortedLinesByFile.push_back(&I);
269  }
270 
271  writeBytes(LinesTag, 4);
272  write(Len);
273  write(Number);
274 
275  std::sort(
276  SortedLinesByFile.begin(), SortedLinesByFile.end(),
278  return LHS->getKey() < RHS->getKey();
279  });
280  for (auto &I : SortedLinesByFile)
281  I->getValue().writeOut();
282  write(0);
283  write(0);
284  }
285 
286  GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
287  // Only allow copy before edges and lines have been added. After that,
288  // there are inter-block pointers (eg: edges) that won't take kindly to
289  // blocks being copied or moved around.
290  assert(LinesByFile.empty());
291  assert(OutEdges.empty());
292  }
293 
294  private:
295  friend class GCOVFunction;
296 
298  : Number(Number) {
299  this->os = os;
300  }
301 
303  StringMap<GCOVLines> LinesByFile;
305  };
306 
307  // A function has a unique identifier, a checksum (we leave as zero) and a
308  // set of blocks and a map of edges between blocks. This is the only GCOV
309  // object users can construct, the blocks and lines will be rooted here.
310  class GCOVFunction : public GCOVRecord {
311  public:
313  uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
314  : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
315  ReturnBlock(1, os) {
316  this->os = os;
317 
318  DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
319 
320  uint32_t i = 0;
321  for (auto &BB : *F) {
322  // Skip index 1 if it's assigned to the ReturnBlock.
323  if (i == 1 && ExitBlockBeforeBody)
324  ++i;
325  Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
326  }
327  if (!ExitBlockBeforeBody)
328  ReturnBlock.Number = i;
329 
330  std::string FunctionNameAndLine;
331  raw_string_ostream FNLOS(FunctionNameAndLine);
332  FNLOS << getFunctionName(SP) << SP->getLine();
333  FNLOS.flush();
334  FuncChecksum = hash_value(FunctionNameAndLine);
335  }
336 
337  GCOVBlock &getBlock(BasicBlock *BB) {
338  return Blocks.find(BB)->second;
339  }
340 
341  GCOVBlock &getReturnBlock() {
342  return ReturnBlock;
343  }
344 
345  std::string getEdgeDestinations() {
346  std::string EdgeDestinations;
347  raw_string_ostream EDOS(EdgeDestinations);
348  Function *F = Blocks.begin()->first->getParent();
349  for (BasicBlock &I : *F) {
350  GCOVBlock &Block = getBlock(&I);
351  for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
352  EDOS << Block.OutEdges[i]->Number;
353  }
354  return EdgeDestinations;
355  }
356 
357  uint32_t getFuncChecksum() {
358  return FuncChecksum;
359  }
360 
361  void setCfgChecksum(uint32_t Checksum) {
362  CfgChecksum = Checksum;
363  }
364 
365  void writeOut() {
366  writeBytes(FunctionTag, 4);
367  uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
368  1 + lengthOfGCOVString(SP->getFilename()) + 1;
369  if (UseCfgChecksum)
370  ++BlockLen;
371  write(BlockLen);
372  write(Ident);
373  write(FuncChecksum);
374  if (UseCfgChecksum)
375  write(CfgChecksum);
376  writeGCOVString(getFunctionName(SP));
377  writeGCOVString(SP->getFilename());
378  write(SP->getLine());
379 
380  // Emit count of blocks.
381  writeBytes(BlockTag, 4);
382  write(Blocks.size() + 1);
383  for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
384  write(0); // No flags on our blocks.
385  }
386  DEBUG(dbgs() << Blocks.size() << " blocks.\n");
387 
388  // Emit edges between blocks.
389  if (Blocks.empty()) return;
390  Function *F = Blocks.begin()->first->getParent();
391  for (BasicBlock &I : *F) {
392  GCOVBlock &Block = getBlock(&I);
393  if (Block.OutEdges.empty()) continue;
394 
395  writeBytes(EdgeTag, 4);
396  write(Block.OutEdges.size() * 2 + 1);
397  write(Block.Number);
398  for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
399  DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
400  << "\n");
401  write(Block.OutEdges[i]->Number);
402  write(0); // no flags
403  }
404  }
405 
406  // Emit lines for each block.
407  for (BasicBlock &I : *F)
408  getBlock(&I).writeOut();
409  }
410 
411  private:
412  const DISubprogram *SP;
413  uint32_t Ident;
414  uint32_t FuncChecksum;
415  bool UseCfgChecksum;
416  uint32_t CfgChecksum;
418  GCOVBlock ReturnBlock;
419  };
420 }
421 
422 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
423  GCovFileType OutputType) {
424  bool Notes = OutputType == GCovFileType::GCNO;
425 
426  if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
427  for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
428  MDNode *N = GCov->getOperand(i);
429  bool ThreeElement = N->getNumOperands() == 3;
430  if (!ThreeElement && N->getNumOperands() != 2)
431  continue;
432  if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
433  continue;
434 
435  if (ThreeElement) {
436  // These nodes have no mangling to apply, it's stored mangled in the
437  // bitcode.
438  MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
439  MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
440  if (!NotesFile || !DataFile)
441  continue;
442  return Notes ? NotesFile->getString() : DataFile->getString();
443  }
444 
445  MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
446  if (!GCovFile)
447  continue;
448 
449  SmallString<128> Filename = GCovFile->getString();
450  sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
451  return Filename.str();
452  }
453  }
454 
455  SmallString<128> Filename = CU->getFilename();
456  sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
457  StringRef FName = sys::path::filename(Filename);
458  SmallString<128> CurPath;
459  if (sys::fs::current_path(CurPath)) return FName;
460  sys::path::append(CurPath, FName);
461  return CurPath.str();
462 }
463 
464 bool GCOVProfiler::runOnModule(Module &M) {
465  this->M = &M;
466  Ctx = &M.getContext();
467 
468  if (Options.EmitNotes) emitProfileNotes();
469  if (Options.EmitData) return emitProfileArcs();
470  return false;
471 }
472 
474  ModuleAnalysisManager &AM) {
475 
476  GCOVProfiler Profiler(GCOVOpts);
477 
478  if (!Profiler.runOnModule(M))
479  return PreservedAnalyses::all();
480 
481  return PreservedAnalyses::none();
482 }
483 
484 static bool functionHasLines(Function &F) {
485  // Check whether this function actually has any source lines. Not only
486  // do these waste space, they also can crash gcov.
487  for (auto &BB : F) {
488  for (auto &I : BB) {
489  // Debug intrinsic locations correspond to the location of the
490  // declaration, not necessarily any statements or expressions.
491  if (isa<DbgInfoIntrinsic>(&I)) continue;
492 
493  const DebugLoc &Loc = I.getDebugLoc();
494  if (!Loc)
495  continue;
496 
497  // Artificial lines such as calls to the global constructors.
498  if (Loc.getLine() == 0) continue;
499 
500  return true;
501  }
502  }
503  return false;
504 }
505 
507  if (!F.hasPersonalityFn()) return false;
508 
510  return isFuncletEHPersonality(Personality);
511 }
512 
514  if (isa<AllocaInst>(*It)) return true;
515  if (isa<DbgInfoIntrinsic>(*It)) return true;
516  if (auto *II = dyn_cast<IntrinsicInst>(It)) {
517  if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
518  }
519 
520  return false;
521 }
522 
523 void GCOVProfiler::emitProfileNotes() {
524  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
525  if (!CU_Nodes) return;
526 
527  for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
528  // Each compile unit gets its own .gcno file. This means that whether we run
529  // this pass over the original .o's as they're produced, or run it after
530  // LTO, we'll generate the same .gcno files.
531 
532  auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
533 
534  // Skip module skeleton (and module) CUs.
535  if (CU->getDWOId())
536  continue;
537 
538  std::error_code EC;
539  raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC, sys::fs::F_None);
540  if (EC) {
541  Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
542  EC.message());
543  continue;
544  }
545 
546  std::string EdgeDestinations;
547 
548  unsigned FunctionIdent = 0;
549  for (auto &F : M->functions()) {
550  DISubprogram *SP = F.getSubprogram();
551  if (!SP) continue;
552  if (!functionHasLines(F)) continue;
553  // TODO: Functions using funclet-based EH are currently not supported.
554  if (isUsingFuncletBasedEH(F)) continue;
555 
556  // gcov expects every function to start with an entry block that has a
557  // single successor, so split the entry block to make sure of that.
558  BasicBlock &EntryBlock = F.getEntryBlock();
559  BasicBlock::iterator It = EntryBlock.begin();
560  while (shouldKeepInEntry(It))
561  ++It;
562  EntryBlock.splitBasicBlock(It);
563 
564  Funcs.push_back(make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
565  Options.UseCfgChecksum,
566  Options.ExitBlockBeforeBody));
567  GCOVFunction &Func = *Funcs.back();
568 
569  for (auto &BB : F) {
570  GCOVBlock &Block = Func.getBlock(&BB);
571  TerminatorInst *TI = BB.getTerminator();
572  if (int successors = TI->getNumSuccessors()) {
573  for (int i = 0; i != successors; ++i) {
574  Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
575  }
576  } else if (isa<ReturnInst>(TI)) {
577  Block.addEdge(Func.getReturnBlock());
578  }
579 
580  uint32_t Line = 0;
581  for (auto &I : BB) {
582  // Debug intrinsic locations correspond to the location of the
583  // declaration, not necessarily any statements or expressions.
584  if (isa<DbgInfoIntrinsic>(&I)) continue;
585 
586  const DebugLoc &Loc = I.getDebugLoc();
587  if (!Loc)
588  continue;
589 
590  // Artificial lines such as calls to the global constructors.
591  if (Loc.getLine() == 0) continue;
592 
593  if (Line == Loc.getLine()) continue;
594  Line = Loc.getLine();
595  if (SP != getDISubprogram(Loc.getScope()))
596  continue;
597 
598  GCOVLines &Lines = Block.getFile(SP->getFilename());
599  Lines.addLine(Loc.getLine());
600  }
601  }
602  EdgeDestinations += Func.getEdgeDestinations();
603  }
604 
605  FileChecksums.push_back(hash_value(EdgeDestinations));
606  out.write("oncg", 4);
607  out.write(ReversedVersion, 4);
608  out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
609 
610  for (auto &Func : Funcs) {
611  Func->setCfgChecksum(FileChecksums.back());
612  Func->writeOut();
613  }
614 
615  out.write("\0\0\0\0\0\0\0\0", 8); // EOF
616  out.close();
617  }
618 }
619 
620 bool GCOVProfiler::emitProfileArcs() {
621  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
622  if (!CU_Nodes) return false;
623 
624  bool Result = false;
625  bool InsertIndCounterIncrCode = false;
626  for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
628  for (auto &F : M->functions()) {
629  DISubprogram *SP = F.getSubprogram();
630  if (!SP) continue;
631  if (!functionHasLines(F)) continue;
632  // TODO: Functions using funclet-based EH are currently not supported.
633  if (isUsingFuncletBasedEH(F)) continue;
634  if (!Result) Result = true;
635 
636  unsigned Edges = 0;
637  for (auto &BB : F) {
638  TerminatorInst *TI = BB.getTerminator();
639  if (isa<ReturnInst>(TI))
640  ++Edges;
641  else
642  Edges += TI->getNumSuccessors();
643  }
644 
645  ArrayType *CounterTy =
646  ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
647  GlobalVariable *Counters =
648  new GlobalVariable(*M, CounterTy, false,
650  Constant::getNullValue(CounterTy),
651  "__llvm_gcov_ctr");
652  CountersBySP.push_back(std::make_pair(Counters, SP));
653 
654  UniqueVector<BasicBlock *> ComplexEdgePreds;
655  UniqueVector<BasicBlock *> ComplexEdgeSuccs;
656 
657  unsigned Edge = 0;
658  for (auto &BB : F) {
659  TerminatorInst *TI = BB.getTerminator();
660  int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
661  if (Successors) {
662  if (Successors == 1) {
663  IRBuilder<> Builder(&*BB.getFirstInsertionPt());
664  Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
665  Edge);
666  Value *Count = Builder.CreateLoad(Counter);
667  Count = Builder.CreateAdd(Count, Builder.getInt64(1));
668  Builder.CreateStore(Count, Counter);
669  } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
670  IRBuilder<> Builder(BI);
671  Value *Sel = Builder.CreateSelect(BI->getCondition(),
672  Builder.getInt64(Edge),
673  Builder.getInt64(Edge + 1));
674  Value *Counter = Builder.CreateInBoundsGEP(
675  Counters->getValueType(), Counters, {Builder.getInt64(0), Sel});
676  Value *Count = Builder.CreateLoad(Counter);
677  Count = Builder.CreateAdd(Count, Builder.getInt64(1));
678  Builder.CreateStore(Count, Counter);
679  } else {
680  ComplexEdgePreds.insert(&BB);
681  for (int i = 0; i != Successors; ++i)
682  ComplexEdgeSuccs.insert(TI->getSuccessor(i));
683  }
684 
685  Edge += Successors;
686  }
687  }
688 
689  if (!ComplexEdgePreds.empty()) {
690  GlobalVariable *EdgeTable =
691  buildEdgeLookupTable(&F, Counters,
692  ComplexEdgePreds, ComplexEdgeSuccs);
693  GlobalVariable *EdgeState = getEdgeStateValue();
694 
695  for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
696  IRBuilder<> Builder(&*ComplexEdgePreds[i + 1]->getFirstInsertionPt());
697  Builder.CreateStore(Builder.getInt32(i), EdgeState);
698  }
699 
700  for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
701  // Call runtime to perform increment.
702  IRBuilder<> Builder(&*ComplexEdgeSuccs[i + 1]->getFirstInsertionPt());
703  Value *CounterPtrArray =
704  Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
705  i * ComplexEdgePreds.size());
706 
707  // Build code to increment the counter.
708  InsertIndCounterIncrCode = true;
709  Builder.CreateCall(getIncrementIndirectCounterFunc(),
710  {EdgeState, CounterPtrArray});
711  }
712  }
713  }
714 
715  Function *WriteoutF = insertCounterWriteout(CountersBySP);
716  Function *FlushF = insertFlush(CountersBySP);
717 
718  // Create a small bit of code that registers the "__llvm_gcov_writeout" to
719  // be executed at exit and the "__llvm_gcov_flush" function to be executed
720  // when "__gcov_flush" is called.
721  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
723  "__llvm_gcov_init", M);
726  F->addFnAttr(Attribute::NoInline);
727  if (Options.NoRedZone)
728  F->addFnAttr(Attribute::NoRedZone);
729 
730  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
731  IRBuilder<> Builder(BB);
732 
733  FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
734  Type *Params[] = {
735  PointerType::get(FTy, 0),
736  PointerType::get(FTy, 0)
737  };
738  FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
739 
740  // Initialize the environment and register the local writeout and flush
741  // functions.
742  Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
743  Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
744  Builder.CreateRetVoid();
745 
746  appendToGlobalCtors(*M, F, 0);
747  }
748 
749  if (InsertIndCounterIncrCode)
750  insertIndirectCounterIncrement();
751 
752  return Result;
753 }
754 
755 // All edges with successors that aren't branches are "complex", because it
756 // requires complex logic to pick which counter to update.
757 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
758  Function *F,
759  GlobalVariable *Counters,
760  const UniqueVector<BasicBlock *> &Preds,
761  const UniqueVector<BasicBlock *> &Succs) {
762  // TODO: support invoke, threads. We rely on the fact that nothing can modify
763  // the whole-Module pred edge# between the time we set it and the time we next
764  // read it. Threads and invoke make this untrue.
765 
766  // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
767  size_t TableSize = Succs.size() * Preds.size();
768  Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
769  ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
770 
771  std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
772  Constant *NullValue = Constant::getNullValue(Int64PtrTy);
773  for (size_t i = 0; i != TableSize; ++i)
774  EdgeTable[i] = NullValue;
775 
776  unsigned Edge = 0;
777  for (BasicBlock &BB : *F) {
778  TerminatorInst *TI = BB.getTerminator();
779  int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
780  if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
781  for (int i = 0; i != Successors; ++i) {
782  BasicBlock *Succ = TI->getSuccessor(i);
783  IRBuilder<> Builder(Succ);
784  Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
785  Edge + i);
786  EdgeTable[((Succs.idFor(Succ) - 1) * Preds.size()) +
787  (Preds.idFor(&BB) - 1)] = cast<Constant>(Counter);
788  }
789  }
790  Edge += Successors;
791  }
792 
793  GlobalVariable *EdgeTableGV =
794  new GlobalVariable(
795  *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
796  ConstantArray::get(EdgeTableTy,
797  makeArrayRef(&EdgeTable[0],TableSize)),
798  "__llvm_gcda_edge_table");
800  return EdgeTableGV;
801 }
802 
803 Constant *GCOVProfiler::getStartFileFunc() {
804  Type *Args[] = {
805  Type::getInt8PtrTy(*Ctx), // const char *orig_filename
806  Type::getInt8PtrTy(*Ctx), // const char version[4]
807  Type::getInt32Ty(*Ctx), // uint32_t checksum
808  };
809  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
810  return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
811 }
812 
813 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
814  Type *Int32Ty = Type::getInt32Ty(*Ctx);
815  Type *Int64Ty = Type::getInt64Ty(*Ctx);
816  Type *Args[] = {
817  Int32Ty->getPointerTo(), // uint32_t *predecessor
818  Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
819  };
820  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
821  return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
822 }
823 
824 Constant *GCOVProfiler::getEmitFunctionFunc() {
825  Type *Args[] = {
826  Type::getInt32Ty(*Ctx), // uint32_t ident
827  Type::getInt8PtrTy(*Ctx), // const char *function_name
828  Type::getInt32Ty(*Ctx), // uint32_t func_checksum
829  Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
830  Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
831  };
832  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
833  return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
834 }
835 
836 Constant *GCOVProfiler::getEmitArcsFunc() {
837  Type *Args[] = {
838  Type::getInt32Ty(*Ctx), // uint32_t num_counters
839  Type::getInt64PtrTy(*Ctx), // uint64_t *counters
840  };
841  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
842  return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
843 }
844 
845 Constant *GCOVProfiler::getSummaryInfoFunc() {
846  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
847  return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
848 }
849 
850 Constant *GCOVProfiler::getEndFileFunc() {
851  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
852  return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
853 }
854 
855 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
856  GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
857  if (!GV) {
858  GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
861  0xffffffff),
862  "__llvm_gcov_global_state_pred");
864  }
865  return GV;
866 }
867 
868 Function *GCOVProfiler::insertCounterWriteout(
869  ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
870  FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
871  Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
872  if (!WriteoutF)
873  WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
874  "__llvm_gcov_writeout", M);
876  WriteoutF->addFnAttr(Attribute::NoInline);
877  if (Options.NoRedZone)
878  WriteoutF->addFnAttr(Attribute::NoRedZone);
879 
880  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
881  IRBuilder<> Builder(BB);
882 
883  Constant *StartFile = getStartFileFunc();
884  Constant *EmitFunction = getEmitFunctionFunc();
885  Constant *EmitArcs = getEmitArcsFunc();
886  Constant *SummaryInfo = getSummaryInfoFunc();
887  Constant *EndFile = getEndFileFunc();
888 
889  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
890  if (CU_Nodes) {
891  for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
892  auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
893 
894  // Skip module skeleton (and module) CUs.
895  if (CU->getDWOId())
896  continue;
897 
898  std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
899  uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
900  Builder.CreateCall(StartFile,
901  {Builder.CreateGlobalStringPtr(FilenameGcda),
902  Builder.CreateGlobalStringPtr(ReversedVersion),
903  Builder.getInt32(CfgChecksum)});
904  for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
905  auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
906  uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
907  Builder.CreateCall(
908  EmitFunction,
909  {Builder.getInt32(j),
910  Options.FunctionNamesInData
913  Builder.getInt32(FuncChecksum),
914  Builder.getInt8(Options.UseCfgChecksum),
915  Builder.getInt32(CfgChecksum)});
916 
917  GlobalVariable *GV = CountersBySP[j].first;
918  unsigned Arcs =
919  cast<ArrayType>(GV->getValueType())->getNumElements();
920  Builder.CreateCall(EmitArcs, {Builder.getInt32(Arcs),
921  Builder.CreateConstGEP2_64(GV, 0, 0)});
922  }
923  Builder.CreateCall(SummaryInfo, {});
924  Builder.CreateCall(EndFile, {});
925  }
926  }
927 
928  Builder.CreateRetVoid();
929  return WriteoutF;
930 }
931 
932 void GCOVProfiler::insertIndirectCounterIncrement() {
933  Function *Fn =
934  cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
937  Fn->addFnAttr(Attribute::NoInline);
938  if (Options.NoRedZone)
939  Fn->addFnAttr(Attribute::NoRedZone);
940 
941  // Create basic blocks for function.
942  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
943  IRBuilder<> Builder(BB);
944 
945  BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
946  BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
947  BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
948 
949  // uint32_t pred = *predecessor;
950  // if (pred == 0xffffffff) return;
951  Argument *Arg = &*Fn->arg_begin();
952  Arg->setName("predecessor");
953  Value *Pred = Builder.CreateLoad(Arg, "pred");
954  Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
955  BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
956 
957  Builder.SetInsertPoint(PredNotNegOne);
958 
959  // uint64_t *counter = counters[pred];
960  // if (!counter) return;
961  Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
962  Arg = &*std::next(Fn->arg_begin());
963  Arg->setName("counters");
964  Value *GEP = Builder.CreateGEP(Type::getInt64PtrTy(*Ctx), Arg, ZExtPred);
965  Value *Counter = Builder.CreateLoad(GEP, "counter");
966  Cond = Builder.CreateICmpEQ(Counter,
968  Builder.getInt64Ty()->getPointerTo()));
969  Builder.CreateCondBr(Cond, Exit, CounterEnd);
970 
971  // ++*counter;
972  Builder.SetInsertPoint(CounterEnd);
973  Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
974  Builder.getInt64(1));
975  Builder.CreateStore(Add, Counter);
976  Builder.CreateBr(Exit);
977 
978  // Fill in the exit block.
979  Builder.SetInsertPoint(Exit);
980  Builder.CreateRetVoid();
981 }
982 
983 Function *GCOVProfiler::
984 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
985  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
986  Function *FlushF = M->getFunction("__llvm_gcov_flush");
987  if (!FlushF)
989  "__llvm_gcov_flush", M);
990  else
993  FlushF->addFnAttr(Attribute::NoInline);
994  if (Options.NoRedZone)
995  FlushF->addFnAttr(Attribute::NoRedZone);
996 
997  BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
998 
999  // Write out the current counters.
1000  Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1001  assert(WriteoutF && "Need to create the writeout function first!");
1002 
1003  IRBuilder<> Builder(Entry);
1004  Builder.CreateCall(WriteoutF, {});
1005 
1006  // Zero out the counters.
1007  for (const auto &I : CountersBySP) {
1008  GlobalVariable *GV = I.first;
1010  Builder.CreateStore(Null, GV);
1011  }
1012 
1013  Type *RetTy = FlushF->getReturnType();
1014  if (RetTy == Type::getVoidTy(*Ctx))
1015  Builder.CreateRetVoid();
1016  else if (RetTy->isIntegerTy())
1017  // Used if __llvm_gcov_flush was implicitly declared.
1018  Builder.CreateRet(ConstantInt::get(RetTy, 0));
1019  else
1020  report_fatal_error("invalid return type for __llvm_gcov_flush");
1021 
1022  return FlushF;
1023 }
static StringRef getFunctionName(TargetLowering::CallLoweringInfo &CLI)
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1244
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:779
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1073
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:115
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
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:142
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:63
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
static GCOVOptions getDefault()
ModulePass * createGCOVProfilerPass(const GCOVOptions &Options=GCOVOptions::getDefault())
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
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
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:368
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:862
F(f)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1067
bool empty() const
empty - Returns true if the vector is empty.
Definition: UniqueVector.h:91
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
Hexagon Common GEP
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:888
INITIALIZE_PASS(GCOVProfilerLegacyPass, "insert-gcov-profiling", "Insert instrumentation for GCOV profiling", false, false) ModulePass *llvm
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:207
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:465
A tuple of MDNodes.
Definition: Metadata.h:1323
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:353
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:451
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237
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:754
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:668
unsigned getNumOperands() const
Definition: Metadata.cpp:1069
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:893
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:286
DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
Definition: DebugInfo.cpp:45
StringRef getFilename() const
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:381
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1180
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:267
unsigned idFor(const T &Entry) const
idFor - return the ID for an existing entry.
Definition: UniqueVector.h:58
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
Value * 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:1372
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:242
GCOVBlock - Collects block information.
Definition: GCOV.h:309
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:4428
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:634
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1387
iterator begin()
Definition: Function.h:588
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:128
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
StringRef getString() const
Definition: Metadata.cpp:456
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Definition: IRBuilder.h:1168
cl::opt< TargetMachine::CodeGenFileType > FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile), cl::desc("Choose a file type (not all types are supported by all targets):"), cl::values(clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm", "Emit an assembly ('.s') file"), clEnumValN(TargetMachine::CGFT_ObjectFile, "obj", "Emit a native object ('.o') file"), clEnumValN(TargetMachine::CGFT_Null, "null", "Emit nothing, for performance testing")))
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:406
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:150
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:54
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
iterator_range< iterator > functions()
Definition: Module.h:583
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
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
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
Definition: Constant.h:42
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:116
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:1693
StringRef getKey() const
Definition: StringMap.h:137
Value * CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1, const Twine &Name="")
Definition: IRBuilder.h:1340
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
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 BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:101
arg_iterator arg_begin()
Definition: Function.h:603
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1550
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:313
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:159
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:386
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:220
size_t size() const
size - Returns the number of entries in the vector.
Definition: UniqueVector.h:88
raw_ostream & write(unsigned char C)
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1227
Iterator for intrusive lists based on ilist_node.
static bool functionHasLines(Function &F)
StringRef getName() const
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
Module.h This file contains the declarations for the Module class.
void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition: Path.cpp:490
void initializeGCOVProfilerLegacyPassPass(PassRegistry &)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:308
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:560
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
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
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:436
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:172
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:224
Value * CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1, const Twine &Name="")
Definition: IRBuilder.h:1352
static bool shouldKeepInEntry(BasicBlock::iterator It)
amdgpu Simplify well known AMD library false Value Value * Arg
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:749
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:120
GCOVFunction - Collects function information.
Definition: GCOV.h:272
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:361
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:208
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:575
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
unsigned insert(const T &Entry)
insert - Append entry to the vector if it doesn&#39;t already exist.
Definition: UniqueVector.h:41
static bool isUsingFuncletBasedEH(Function &F)
#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:267
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:382
void close()
Manually flush the stream and close the file.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:462
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1260
succ_range successors(BasicBlock *BB)
Definition: CFG.h:143
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional &#39;br label X&#39; instruction.
Definition: IRBuilder.h:773
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
#define DEBUG(X)
Definition: Debug.h:118
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:211
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition: IRBuilder.h:298
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A single uniqued string.
Definition: Metadata.h:602
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:136
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:199
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1073
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
UniqueVector - This class produces a sequential ID number (base 1) for each unique entry that is adde...
Definition: UniqueVector.h:25
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
IntegerType * Int32Ty
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1663