[llvm] Replacing asserts with static_asserts where appropriate
[oota-llvm.git] / lib / Transforms / Instrumentation / GCOVProfiling.cpp
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/Transforms/Instrumentation.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/Hashing.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #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"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Transforms/Utils/ModuleUtils.h"
39 #include <algorithm>
40 #include <memory>
41 #include <string>
42 #include <utility>
43 using namespace llvm;
44
45 #define DEBUG_TYPE "insert-gcov-profiling"
46
47 static cl::opt<std::string>
48 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
49                    cl::ValueRequired);
50
51 GCOVOptions GCOVOptions::getDefault() {
52   GCOVOptions Options;
53   Options.EmitNotes = true;
54   Options.EmitData = true;
55   Options.UseCfgChecksum = false;
56   Options.NoRedZone = false;
57   Options.FunctionNamesInData = true;
58
59   if (DefaultGCOVVersion.size() != 4) {
60     llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
61                              DefaultGCOVVersion);
62   }
63   memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
64   return Options;
65 }
66
67 namespace {
68   class GCOVFunction;
69
70   class GCOVProfiler : public ModulePass {
71   public:
72     static char ID;
73     GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
74     GCOVProfiler(const GCOVOptions &Opts) : ModulePass(ID), Options(Opts) {
75       assert((Options.EmitNotes || Options.EmitData) &&
76              "GCOVProfiler asked to do nothing?");
77       ReversedVersion[0] = Options.Version[3];
78       ReversedVersion[1] = Options.Version[2];
79       ReversedVersion[2] = Options.Version[1];
80       ReversedVersion[3] = Options.Version[0];
81       ReversedVersion[4] = '\0';
82       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
83     }
84     const char *getPassName() const override {
85       return "GCOV Profiler";
86     }
87
88   private:
89     bool runOnModule(Module &M) override;
90
91     // Create the .gcno files for the Module based on DebugInfo.
92     void emitProfileNotes();
93
94     // Modify the program to track transitions along edges and call into the
95     // profiling runtime to emit .gcda files when run.
96     bool emitProfileArcs();
97
98     // Get pointers to the functions in the runtime library.
99     Constant *getStartFileFunc();
100     Constant *getIncrementIndirectCounterFunc();
101     Constant *getEmitFunctionFunc();
102     Constant *getEmitArcsFunc();
103     Constant *getSummaryInfoFunc();
104     Constant *getDeleteWriteoutFunctionListFunc();
105     Constant *getDeleteFlushFunctionListFunc();
106     Constant *getEndFileFunc();
107
108     // Create or retrieve an i32 state value that is used to represent the
109     // pred block number for certain non-trivial edges.
110     GlobalVariable *getEdgeStateValue();
111
112     // Produce a table of pointers to counters, by predecessor and successor
113     // block number.
114     GlobalVariable *buildEdgeLookupTable(Function *F,
115                                          GlobalVariable *Counter,
116                                          const UniqueVector<BasicBlock *>&Preds,
117                                          const UniqueVector<BasicBlock*>&Succs);
118
119     // Add the function to write out all our counters to the global destructor
120     // list.
121     Function *insertCounterWriteout(ArrayRef<std::pair<GlobalVariable*,
122                                                        MDNode*> >);
123     Function *insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> >);
124     void insertIndirectCounterIncrement();
125
126     std::string mangleName(DICompileUnit CU, const char *NewStem);
127
128     GCOVOptions Options;
129
130     // Reversed, NUL-terminated copy of Options.Version.
131     char ReversedVersion[5];
132     // Checksum, produced by hash of EdgeDestinations
133     SmallVector<uint32_t, 4> FileChecksums;
134
135     Module *M;
136     LLVMContext *Ctx;
137     SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
138   };
139 }
140
141 char GCOVProfiler::ID = 0;
142 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
143                 "Insert instrumentation for GCOV profiling", false, false)
144
145 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
146   return new GCOVProfiler(Options);
147 }
148
149 static StringRef getFunctionName(DISubprogram SP) {
150   if (!SP.getLinkageName().empty())
151     return SP.getLinkageName();
152   return SP.getName();
153 }
154
155 namespace {
156   class GCOVRecord {
157    protected:
158     static const char *const LinesTag;
159     static const char *const FunctionTag;
160     static const char *const BlockTag;
161     static const char *const EdgeTag;
162
163     GCOVRecord() {}
164
165     void writeBytes(const char *Bytes, int Size) {
166       os->write(Bytes, Size);
167     }
168
169     void write(uint32_t i) {
170       writeBytes(reinterpret_cast<char*>(&i), 4);
171     }
172
173     // Returns the length measured in 4-byte blocks that will be used to
174     // represent this string in a GCOV file
175     static unsigned lengthOfGCOVString(StringRef s) {
176       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
177       // padding out to the next 4-byte word. The length is measured in 4-byte
178       // words including padding, not bytes of actual string.
179       return (s.size() / 4) + 1;
180     }
181
182     void writeGCOVString(StringRef s) {
183       uint32_t Len = lengthOfGCOVString(s);
184       write(Len);
185       writeBytes(s.data(), s.size());
186
187       // Write 1 to 4 bytes of NUL padding.
188       assert((unsigned)(4 - (s.size() % 4)) > 0);
189       assert((unsigned)(4 - (s.size() % 4)) <= 4);
190       writeBytes("\0\0\0\0", 4 - (s.size() % 4));
191     }
192
193     raw_ostream *os;
194   };
195   const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
196   const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
197   const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
198   const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
199
200   class GCOVFunction;
201   class GCOVBlock;
202
203   // Constructed only by requesting it from a GCOVBlock, this object stores a
204   // list of line numbers and a single filename, representing lines that belong
205   // to the block.
206   class GCOVLines : public GCOVRecord {
207    public:
208     void addLine(uint32_t Line) {
209       assert(Line != 0 && "Line zero is not a valid real line number.");
210       Lines.push_back(Line);
211     }
212
213     uint32_t length() const {
214       // Here 2 = 1 for string length + 1 for '0' id#.
215       return lengthOfGCOVString(Filename) + 2 + Lines.size();
216     }
217
218     void writeOut() {
219       write(0);
220       writeGCOVString(Filename);
221       for (int i = 0, e = Lines.size(); i != e; ++i)
222         write(Lines[i]);
223     }
224
225     GCOVLines(StringRef F, raw_ostream *os)
226       : Filename(F) {
227       this->os = os;
228     }
229
230    private:
231     StringRef Filename;
232     SmallVector<uint32_t, 32> Lines;
233   };
234
235
236   // Represent a basic block in GCOV. Each block has a unique number in the
237   // function, number of lines belonging to each block, and a set of edges to
238   // other blocks.
239   class GCOVBlock : public GCOVRecord {
240    public:
241     GCOVLines &getFile(StringRef Filename) {
242       GCOVLines *&Lines = LinesByFile[Filename];
243       if (!Lines) {
244         Lines = new GCOVLines(Filename, os);
245       }
246       return *Lines;
247     }
248
249     void addEdge(GCOVBlock &Successor) {
250       OutEdges.push_back(&Successor);
251     }
252
253     void writeOut() {
254       uint32_t Len = 3;
255       SmallVector<StringMapEntry<GCOVLines *> *, 32> SortedLinesByFile;
256       for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
257                E = LinesByFile.end(); I != E; ++I) {
258         Len += I->second->length();
259         SortedLinesByFile.push_back(&*I);
260       }
261
262       writeBytes(LinesTag, 4);
263       write(Len);
264       write(Number);
265
266       std::sort(SortedLinesByFile.begin(), SortedLinesByFile.end(),
267                 [](StringMapEntry<GCOVLines *> *LHS,
268                    StringMapEntry<GCOVLines *> *RHS) {
269         return LHS->getKey() < RHS->getKey();
270       });
271       for (SmallVectorImpl<StringMapEntry<GCOVLines *> *>::iterator
272                I = SortedLinesByFile.begin(), E = SortedLinesByFile.end();
273            I != E; ++I)
274         (*I)->getValue()->writeOut();
275       write(0);
276       write(0);
277     }
278
279     ~GCOVBlock() {
280       DeleteContainerSeconds(LinesByFile);
281     }
282
283     GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
284       // Only allow copy before edges and lines have been added. After that,
285       // there are inter-block pointers (eg: edges) that won't take kindly to
286       // blocks being copied or moved around.
287       assert(LinesByFile.empty());
288       assert(OutEdges.empty());
289     }
290
291    private:
292     friend class GCOVFunction;
293
294     GCOVBlock(uint32_t Number, raw_ostream *os)
295         : Number(Number) {
296       this->os = os;
297     }
298
299     uint32_t Number;
300     StringMap<GCOVLines *> LinesByFile;
301     SmallVector<GCOVBlock *, 4> OutEdges;
302   };
303
304   // A function has a unique identifier, a checksum (we leave as zero) and a
305   // set of blocks and a map of edges between blocks. This is the only GCOV
306   // object users can construct, the blocks and lines will be rooted here.
307   class GCOVFunction : public GCOVRecord {
308    public:
309      GCOVFunction(DISubprogram SP, raw_ostream *os, uint32_t Ident,
310                   bool UseCfgChecksum)
311          : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
312            ReturnBlock(1, os) {
313       this->os = os;
314
315       Function *F = SP.getFunction();
316       DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
317
318       uint32_t i = 0;
319       for (auto &BB : *F) {
320         // Skip index 1 (0, 2, 3, 4, ...) because that's assigned to the
321         // ReturnBlock.
322         bool first = i == 0;
323         Blocks.insert(std::make_pair(&BB, GCOVBlock(i++ + !first, os)));
324       }
325
326       std::string FunctionNameAndLine;
327       raw_string_ostream FNLOS(FunctionNameAndLine);
328       FNLOS << getFunctionName(SP) << SP.getLineNumber();
329       FNLOS.flush();
330       FuncChecksum = hash_value(FunctionNameAndLine);
331     }
332
333     GCOVBlock &getBlock(BasicBlock *BB) {
334       return Blocks.find(BB)->second;
335     }
336
337     GCOVBlock &getReturnBlock() {
338       return ReturnBlock;
339     }
340
341     std::string getEdgeDestinations() {
342       std::string EdgeDestinations;
343       raw_string_ostream EDOS(EdgeDestinations);
344       Function *F = Blocks.begin()->first->getParent();
345       for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
346         GCOVBlock &Block = getBlock(I);
347         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
348           EDOS << Block.OutEdges[i]->Number;
349       }
350       return EdgeDestinations;
351     }
352
353     uint32_t getFuncChecksum() {
354       return FuncChecksum;
355     }
356
357     void setCfgChecksum(uint32_t Checksum) {
358       CfgChecksum = Checksum;
359     }
360
361     void writeOut() {
362       writeBytes(FunctionTag, 4);
363       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
364           1 + lengthOfGCOVString(SP.getFilename()) + 1;
365       if (UseCfgChecksum)
366         ++BlockLen;
367       write(BlockLen);
368       write(Ident);
369       write(FuncChecksum);
370       if (UseCfgChecksum)
371         write(CfgChecksum);
372       writeGCOVString(getFunctionName(SP));
373       writeGCOVString(SP.getFilename());
374       write(SP.getLineNumber());
375
376       // Emit count of blocks.
377       writeBytes(BlockTag, 4);
378       write(Blocks.size() + 1);
379       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
380         write(0);  // No flags on our blocks.
381       }
382       DEBUG(dbgs() << Blocks.size() << " blocks.\n");
383
384       // Emit edges between blocks.
385       if (Blocks.empty()) return;
386       Function *F = Blocks.begin()->first->getParent();
387       for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
388         GCOVBlock &Block = getBlock(I);
389         if (Block.OutEdges.empty()) continue;
390
391         writeBytes(EdgeTag, 4);
392         write(Block.OutEdges.size() * 2 + 1);
393         write(Block.Number);
394         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
395           DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
396                        << "\n");
397           write(Block.OutEdges[i]->Number);
398           write(0);  // no flags
399         }
400       }
401
402       // Emit lines for each block.
403       for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
404         getBlock(I).writeOut();
405       }
406     }
407
408    private:
409     DISubprogram SP;
410     uint32_t Ident;
411     uint32_t FuncChecksum;
412     bool UseCfgChecksum;
413     uint32_t CfgChecksum;
414     DenseMap<BasicBlock *, GCOVBlock> Blocks;
415     GCOVBlock ReturnBlock;
416   };
417 }
418
419 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
420   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
421     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
422       MDNode *N = GCov->getOperand(i);
423       if (N->getNumOperands() != 2) continue;
424       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
425       MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
426       if (!GCovFile || !CompileUnit) continue;
427       if (CompileUnit == CU) {
428         SmallString<128> Filename = GCovFile->getString();
429         sys::path::replace_extension(Filename, NewStem);
430         return Filename.str();
431       }
432     }
433   }
434
435   SmallString<128> Filename = CU.getFilename();
436   sys::path::replace_extension(Filename, NewStem);
437   StringRef FName = sys::path::filename(Filename);
438   SmallString<128> CurPath;
439   if (sys::fs::current_path(CurPath)) return FName;
440   sys::path::append(CurPath, FName.str());
441   return CurPath.str();
442 }
443
444 bool GCOVProfiler::runOnModule(Module &M) {
445   this->M = &M;
446   Ctx = &M.getContext();
447
448   if (Options.EmitNotes) emitProfileNotes();
449   if (Options.EmitData) return emitProfileArcs();
450   return false;
451 }
452
453 static bool functionHasLines(Function *F) {
454   // Check whether this function actually has any source lines. Not only
455   // do these waste space, they also can crash gcov.
456   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
457     for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
458          I != IE; ++I) {
459       // Debug intrinsic locations correspond to the location of the
460       // declaration, not necessarily any statements or expressions.
461       if (isa<DbgInfoIntrinsic>(I)) continue;
462
463       const DebugLoc &Loc = I->getDebugLoc();
464       if (Loc.isUnknown()) continue;
465
466       // Artificial lines such as calls to the global constructors.
467       if (Loc.getLine() == 0) continue; 
468
469       return true;
470     }
471   }
472   return false;
473 }
474
475 void GCOVProfiler::emitProfileNotes() {
476   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
477   if (!CU_Nodes) return;
478
479   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
480     // Each compile unit gets its own .gcno file. This means that whether we run
481     // this pass over the original .o's as they're produced, or run it after
482     // LTO, we'll generate the same .gcno files.
483
484     DICompileUnit CU(CU_Nodes->getOperand(i));
485     std::error_code EC;
486     raw_fd_ostream out(mangleName(CU, "gcno"), EC, sys::fs::F_None);
487     std::string EdgeDestinations;
488
489     DIArray SPs = CU.getSubprograms();
490     unsigned FunctionIdent = 0;
491     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
492       DISubprogram SP(SPs.getElement(i));
493       assert((!SP || SP.isSubprogram()) &&
494         "A MDNode in subprograms of a CU should be null or a DISubprogram.");
495       if (!SP)
496         continue;
497
498       Function *F = SP.getFunction();
499       if (!F) continue;
500       if (!functionHasLines(F)) continue;
501
502       // gcov expects every function to start with an entry block that has a
503       // single successor, so split the entry block to make sure of that.
504       BasicBlock &EntryBlock = F->getEntryBlock();
505       BasicBlock::iterator It = EntryBlock.begin();
506       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
507         ++It;
508       EntryBlock.splitBasicBlock(It);
509
510       Funcs.push_back(make_unique<GCOVFunction>(SP, &out, FunctionIdent++,
511                                                 Options.UseCfgChecksum));
512       GCOVFunction &Func = *Funcs.back();
513
514       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
515         GCOVBlock &Block = Func.getBlock(BB);
516         TerminatorInst *TI = BB->getTerminator();
517         if (int successors = TI->getNumSuccessors()) {
518           for (int i = 0; i != successors; ++i) {
519             Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
520           }
521         } else if (isa<ReturnInst>(TI)) {
522           Block.addEdge(Func.getReturnBlock());
523         }
524
525         uint32_t Line = 0;
526         for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
527              I != IE; ++I) {
528           // Debug intrinsic locations correspond to the location of the
529           // declaration, not necessarily any statements or expressions.
530           if (isa<DbgInfoIntrinsic>(I)) continue;
531
532           const DebugLoc &Loc = I->getDebugLoc();
533           if (Loc.isUnknown()) continue;
534
535           // Artificial lines such as calls to the global constructors.
536           if (Loc.getLine() == 0) continue;
537
538           if (Line == Loc.getLine()) continue;
539           Line = Loc.getLine();
540           if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
541
542           GCOVLines &Lines = Block.getFile(SP.getFilename());
543           Lines.addLine(Loc.getLine());
544         }
545       }
546       EdgeDestinations += Func.getEdgeDestinations();
547     }
548
549     FileChecksums.push_back(hash_value(EdgeDestinations));
550     out.write("oncg", 4);
551     out.write(ReversedVersion, 4);
552     out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
553
554     for (auto &Func : Funcs) {
555       Func->setCfgChecksum(FileChecksums.back());
556       Func->writeOut();
557     }
558
559     out.write("\0\0\0\0\0\0\0\0", 8);  // EOF
560     out.close();
561   }
562 }
563
564 bool GCOVProfiler::emitProfileArcs() {
565   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
566   if (!CU_Nodes) return false;
567
568   bool Result = false;
569   bool InsertIndCounterIncrCode = false;
570   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
571     DICompileUnit CU(CU_Nodes->getOperand(i));
572     DIArray SPs = CU.getSubprograms();
573     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
574     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
575       DISubprogram SP(SPs.getElement(i));
576       assert((!SP || SP.isSubprogram()) &&
577         "A MDNode in subprograms of a CU should be null or a DISubprogram.");
578       if (!SP)
579         continue;
580       Function *F = SP.getFunction();
581       if (!F) continue;
582       if (!functionHasLines(F)) continue;
583       if (!Result) Result = true;
584       unsigned Edges = 0;
585       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
586         TerminatorInst *TI = BB->getTerminator();
587         if (isa<ReturnInst>(TI))
588           ++Edges;
589         else
590           Edges += TI->getNumSuccessors();
591       }
592
593       ArrayType *CounterTy =
594         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
595       GlobalVariable *Counters =
596         new GlobalVariable(*M, CounterTy, false,
597                            GlobalValue::InternalLinkage,
598                            Constant::getNullValue(CounterTy),
599                            "__llvm_gcov_ctr");
600       CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
601
602       UniqueVector<BasicBlock *> ComplexEdgePreds;
603       UniqueVector<BasicBlock *> ComplexEdgeSuccs;
604
605       unsigned Edge = 0;
606       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
607         TerminatorInst *TI = BB->getTerminator();
608         int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
609         if (Successors) {
610           if (Successors == 1) {
611             IRBuilder<> Builder(BB->getFirstInsertionPt());
612             Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
613                                                                 Edge);
614             Value *Count = Builder.CreateLoad(Counter);
615             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
616             Builder.CreateStore(Count, Counter);
617           } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
618             IRBuilder<> Builder(BI);
619             Value *Sel = Builder.CreateSelect(BI->getCondition(),
620                                               Builder.getInt64(Edge),
621                                               Builder.getInt64(Edge + 1));
622             SmallVector<Value *, 2> Idx;
623             Idx.push_back(Builder.getInt64(0));
624             Idx.push_back(Sel);
625             Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
626             Value *Count = Builder.CreateLoad(Counter);
627             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
628             Builder.CreateStore(Count, Counter);
629           } else {
630             ComplexEdgePreds.insert(BB);
631             for (int i = 0; i != Successors; ++i)
632               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
633           }
634
635           Edge += Successors;
636         }
637       }
638
639       if (!ComplexEdgePreds.empty()) {
640         GlobalVariable *EdgeTable =
641           buildEdgeLookupTable(F, Counters,
642                                ComplexEdgePreds, ComplexEdgeSuccs);
643         GlobalVariable *EdgeState = getEdgeStateValue();
644
645         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
646           IRBuilder<> Builder(ComplexEdgePreds[i + 1]->getFirstInsertionPt());
647           Builder.CreateStore(Builder.getInt32(i), EdgeState);
648         }
649
650         for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
651           // Call runtime to perform increment.
652           IRBuilder<> Builder(ComplexEdgeSuccs[i+1]->getFirstInsertionPt());
653           Value *CounterPtrArray =
654             Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
655                                                i * ComplexEdgePreds.size());
656
657           // Build code to increment the counter.
658           InsertIndCounterIncrCode = true;
659           Builder.CreateCall2(getIncrementIndirectCounterFunc(),
660                               EdgeState, CounterPtrArray);
661         }
662       }
663     }
664
665     Function *WriteoutF = insertCounterWriteout(CountersBySP);
666     Function *FlushF = insertFlush(CountersBySP);
667
668     // Create a small bit of code that registers the "__llvm_gcov_writeout" to
669     // be executed at exit and the "__llvm_gcov_flush" function to be executed
670     // when "__gcov_flush" is called.
671     FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
672     Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
673                                    "__llvm_gcov_init", M);
674     F->setUnnamedAddr(true);
675     F->setLinkage(GlobalValue::InternalLinkage);
676     F->addFnAttr(Attribute::NoInline);
677     if (Options.NoRedZone)
678       F->addFnAttr(Attribute::NoRedZone);
679
680     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
681     IRBuilder<> Builder(BB);
682
683     FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
684     Type *Params[] = {
685       PointerType::get(FTy, 0),
686       PointerType::get(FTy, 0)
687     };
688     FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
689
690     // Initialize the environment and register the local writeout and flush
691     // functions.
692     Constant *GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
693     Builder.CreateCall2(GCOVInit, WriteoutF, FlushF);
694     Builder.CreateRetVoid();
695
696     appendToGlobalCtors(*M, F, 0);
697   }
698
699   if (InsertIndCounterIncrCode)
700     insertIndirectCounterIncrement();
701
702   return Result;
703 }
704
705 // All edges with successors that aren't branches are "complex", because it
706 // requires complex logic to pick which counter to update.
707 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
708     Function *F,
709     GlobalVariable *Counters,
710     const UniqueVector<BasicBlock *> &Preds,
711     const UniqueVector<BasicBlock *> &Succs) {
712   // TODO: support invoke, threads. We rely on the fact that nothing can modify
713   // the whole-Module pred edge# between the time we set it and the time we next
714   // read it. Threads and invoke make this untrue.
715
716   // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
717   size_t TableSize = Succs.size() * Preds.size();
718   Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
719   ArrayType *EdgeTableTy = ArrayType::get(Int64PtrTy, TableSize);
720
721   std::unique_ptr<Constant * []> EdgeTable(new Constant *[TableSize]);
722   Constant *NullValue = Constant::getNullValue(Int64PtrTy);
723   for (size_t i = 0; i != TableSize; ++i)
724     EdgeTable[i] = NullValue;
725
726   unsigned Edge = 0;
727   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
728     TerminatorInst *TI = BB->getTerminator();
729     int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
730     if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
731       for (int i = 0; i != Successors; ++i) {
732         BasicBlock *Succ = TI->getSuccessor(i);
733         IRBuilder<> Builder(Succ);
734         Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
735                                                             Edge + i);
736         EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
737                   (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
738       }
739     }
740     Edge += Successors;
741   }
742
743   GlobalVariable *EdgeTableGV =
744       new GlobalVariable(
745           *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
746           ConstantArray::get(EdgeTableTy,
747                              makeArrayRef(&EdgeTable[0],TableSize)),
748           "__llvm_gcda_edge_table");
749   EdgeTableGV->setUnnamedAddr(true);
750   return EdgeTableGV;
751 }
752
753 Constant *GCOVProfiler::getStartFileFunc() {
754   Type *Args[] = {
755     Type::getInt8PtrTy(*Ctx),  // const char *orig_filename
756     Type::getInt8PtrTy(*Ctx),  // const char version[4]
757     Type::getInt32Ty(*Ctx),    // uint32_t checksum
758   };
759   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
760   return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
761 }
762
763 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
764   Type *Int32Ty = Type::getInt32Ty(*Ctx);
765   Type *Int64Ty = Type::getInt64Ty(*Ctx);
766   Type *Args[] = {
767     Int32Ty->getPointerTo(),                // uint32_t *predecessor
768     Int64Ty->getPointerTo()->getPointerTo() // uint64_t **counters
769   };
770   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
771   return M->getOrInsertFunction("__llvm_gcov_indirect_counter_increment", FTy);
772 }
773
774 Constant *GCOVProfiler::getEmitFunctionFunc() {
775   Type *Args[] = {
776     Type::getInt32Ty(*Ctx),    // uint32_t ident
777     Type::getInt8PtrTy(*Ctx),  // const char *function_name
778     Type::getInt32Ty(*Ctx),    // uint32_t func_checksum
779     Type::getInt8Ty(*Ctx),     // uint8_t use_extra_checksum
780     Type::getInt32Ty(*Ctx),    // uint32_t cfg_checksum
781   };
782   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
783   return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
784 }
785
786 Constant *GCOVProfiler::getEmitArcsFunc() {
787   Type *Args[] = {
788     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
789     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
790   };
791   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
792   return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
793 }
794
795 Constant *GCOVProfiler::getSummaryInfoFunc() {
796   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
797   return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
798 }
799
800 Constant *GCOVProfiler::getDeleteWriteoutFunctionListFunc() {
801   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
802   return M->getOrInsertFunction("llvm_delete_writeout_function_list", FTy);
803 }
804
805 Constant *GCOVProfiler::getDeleteFlushFunctionListFunc() {
806   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
807   return M->getOrInsertFunction("llvm_delete_flush_function_list", FTy);
808 }
809
810 Constant *GCOVProfiler::getEndFileFunc() {
811   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
812   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
813 }
814
815 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
816   GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
817   if (!GV) {
818     GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
819                             GlobalValue::InternalLinkage,
820                             ConstantInt::get(Type::getInt32Ty(*Ctx),
821                                              0xffffffff),
822                             "__llvm_gcov_global_state_pred");
823     GV->setUnnamedAddr(true);
824   }
825   return GV;
826 }
827
828 Function *GCOVProfiler::insertCounterWriteout(
829     ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
830   FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
831   Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
832   if (!WriteoutF)
833     WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
834                                  "__llvm_gcov_writeout", M);
835   WriteoutF->setUnnamedAddr(true);
836   WriteoutF->addFnAttr(Attribute::NoInline);
837   if (Options.NoRedZone)
838     WriteoutF->addFnAttr(Attribute::NoRedZone);
839
840   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
841   IRBuilder<> Builder(BB);
842
843   Constant *StartFile = getStartFileFunc();
844   Constant *EmitFunction = getEmitFunctionFunc();
845   Constant *EmitArcs = getEmitArcsFunc();
846   Constant *SummaryInfo = getSummaryInfoFunc();
847   Constant *EndFile = getEndFileFunc();
848
849   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
850   if (CU_Nodes) {
851     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
852       DICompileUnit CU(CU_Nodes->getOperand(i));
853       std::string FilenameGcda = mangleName(CU, "gcda");
854       uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
855       Builder.CreateCall3(StartFile,
856                           Builder.CreateGlobalStringPtr(FilenameGcda),
857                           Builder.CreateGlobalStringPtr(ReversedVersion),
858                           Builder.getInt32(CfgChecksum));
859       for (unsigned j = 0, e = CountersBySP.size(); j != e; ++j) {
860         DISubprogram SP(CountersBySP[j].second);
861         uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
862         Builder.CreateCall5(
863             EmitFunction, Builder.getInt32(j),
864             Options.FunctionNamesInData ?
865               Builder.CreateGlobalStringPtr(getFunctionName(SP)) :
866               Constant::getNullValue(Builder.getInt8PtrTy()),
867             Builder.getInt32(FuncChecksum),
868             Builder.getInt8(Options.UseCfgChecksum),
869             Builder.getInt32(CfgChecksum));
870
871         GlobalVariable *GV = CountersBySP[j].first;
872         unsigned Arcs =
873           cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
874         Builder.CreateCall2(EmitArcs,
875                             Builder.getInt32(Arcs),
876                             Builder.CreateConstGEP2_64(GV, 0, 0));
877       }
878       Builder.CreateCall(SummaryInfo);
879       Builder.CreateCall(EndFile);
880     }
881   }
882
883   Builder.CreateRetVoid();
884   return WriteoutF;
885 }
886
887 void GCOVProfiler::insertIndirectCounterIncrement() {
888   Function *Fn =
889     cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
890   Fn->setUnnamedAddr(true);
891   Fn->setLinkage(GlobalValue::InternalLinkage);
892   Fn->addFnAttr(Attribute::NoInline);
893   if (Options.NoRedZone)
894     Fn->addFnAttr(Attribute::NoRedZone);
895
896   // Create basic blocks for function.
897   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
898   IRBuilder<> Builder(BB);
899
900   BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
901   BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
902   BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
903
904   // uint32_t pred = *predecessor;
905   // if (pred == 0xffffffff) return;
906   Argument *Arg = Fn->arg_begin();
907   Arg->setName("predecessor");
908   Value *Pred = Builder.CreateLoad(Arg, "pred");
909   Value *Cond = Builder.CreateICmpEQ(Pred, Builder.getInt32(0xffffffff));
910   BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
911
912   Builder.SetInsertPoint(PredNotNegOne);
913
914   // uint64_t *counter = counters[pred];
915   // if (!counter) return;
916   Value *ZExtPred = Builder.CreateZExt(Pred, Builder.getInt64Ty());
917   Arg = std::next(Fn->arg_begin());
918   Arg->setName("counters");
919   Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
920   Value *Counter = Builder.CreateLoad(GEP, "counter");
921   Cond = Builder.CreateICmpEQ(Counter,
922                               Constant::getNullValue(
923                                   Builder.getInt64Ty()->getPointerTo()));
924   Builder.CreateCondBr(Cond, Exit, CounterEnd);
925
926   // ++*counter;
927   Builder.SetInsertPoint(CounterEnd);
928   Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
929                                  Builder.getInt64(1));
930   Builder.CreateStore(Add, Counter);
931   Builder.CreateBr(Exit);
932
933   // Fill in the exit block.
934   Builder.SetInsertPoint(Exit);
935   Builder.CreateRetVoid();
936 }
937
938 Function *GCOVProfiler::
939 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
940   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
941   Function *FlushF = M->getFunction("__llvm_gcov_flush");
942   if (!FlushF)
943     FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
944                               "__llvm_gcov_flush", M);
945   else
946     FlushF->setLinkage(GlobalValue::InternalLinkage);
947   FlushF->setUnnamedAddr(true);
948   FlushF->addFnAttr(Attribute::NoInline);
949   if (Options.NoRedZone)
950     FlushF->addFnAttr(Attribute::NoRedZone);
951
952   BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
953
954   // Write out the current counters.
955   Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
956   assert(WriteoutF && "Need to create the writeout function first!");
957
958   IRBuilder<> Builder(Entry);
959   Builder.CreateCall(WriteoutF);
960
961   // Zero out the counters.
962   for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
963          I = CountersBySP.begin(), E = CountersBySP.end();
964        I != E; ++I) {
965     GlobalVariable *GV = I->first;
966     Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
967     Builder.CreateStore(Null, GV);
968   }
969
970   Type *RetTy = FlushF->getReturnType();
971   if (RetTy == Type::getVoidTy(*Ctx))
972     Builder.CreateRetVoid();
973   else if (RetTy->isIntegerTy())
974     // Used if __llvm_gcov_flush was implicitly declared.
975     Builder.CreateRet(ConstantInt::get(RetTy, 0));
976   else
977     report_fatal_error("invalid return type for __llvm_gcov_flush");
978
979   return FlushF;
980 }