There is no need to write a local utility routine to find subprogram info if the...
[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 #define DEBUG_TYPE "insert-gcov-profiling"
18
19 #include "ProfilingUtils.h"
20 #include "llvm/Transforms/Instrumentation.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/DebugLoc.h"
28 #include "llvm/Support/InstIterator.h"
29 #include "llvm/Support/IRBuilder.h"
30 #include "llvm/Support/PathV2.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/ADT/UniqueVector.h"
37 #include <string>
38 #include <utility>
39 using namespace llvm;
40
41 namespace {
42   class GCOVProfiler : public ModulePass {
43   public:
44     static char ID;
45     GCOVProfiler()
46         : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false) {
47       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
48     }
49     GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false)
50         : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
51           Use402Format(use402Format) {
52       assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
53       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
54     }
55     virtual const char *getPassName() const {
56       return "GCOV Profiler";
57     }
58
59   private:
60     bool runOnModule(Module &M);
61
62     // Create the GCNO files for the Module based on DebugInfo.
63     void emitGCNO();
64
65     // Modify the program to track transitions along edges and call into the
66     // profiling runtime to emit .gcda files when run.
67     bool emitProfileArcs();
68
69     // Get pointers to the functions in the runtime library.
70     Constant *getStartFileFunc();
71     Constant *getIncrementIndirectCounterFunc();
72     Constant *getEmitFunctionFunc();
73     Constant *getEmitArcsFunc();
74     Constant *getEndFileFunc();
75
76     // Create or retrieve an i32 state value that is used to represent the
77     // pred block number for certain non-trivial edges.
78     GlobalVariable *getEdgeStateValue();
79
80     // Produce a table of pointers to counters, by predecessor and successor
81     // block number.
82     GlobalVariable *buildEdgeLookupTable(Function *F,
83                                          GlobalVariable *Counter,
84                                          const UniqueVector<BasicBlock *> &Preds,
85                                          const UniqueVector<BasicBlock *> &Succs);
86
87     // Add the function to write out all our counters to the global destructor
88     // list.
89     void insertCounterWriteout(SmallVector<std::pair<GlobalVariable *,
90                                                      MDNode *>, 8> &);
91
92     std::string mangleName(DICompileUnit CU, std::string NewStem);
93
94     bool EmitNotes;
95     bool EmitData;
96     bool Use402Format;
97
98     Module *M;
99     LLVMContext *Ctx;
100   };
101 }
102
103 char GCOVProfiler::ID = 0;
104 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
105                 "Insert instrumentation for GCOV profiling", false, false)
106
107 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
108                                          bool Use402Format) {
109   return new GCOVProfiler(EmitNotes, EmitData, Use402Format);
110 }
111
112 namespace {
113   class GCOVRecord {
114    protected:
115     static const char *LinesTag;
116     static const char *FunctionTag;
117     static const char *BlockTag;
118     static const char *EdgeTag;
119
120     GCOVRecord() {}
121
122     void writeBytes(const char *Bytes, int Size) {
123       os->write(Bytes, Size);
124     }
125
126     void write(uint32_t i) {
127       writeBytes(reinterpret_cast<char*>(&i), 4);
128     }
129
130     // Returns the length measured in 4-byte blocks that will be used to
131     // represent this string in a GCOV file
132     unsigned lengthOfGCOVString(StringRef s) {
133       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
134       // padding out to the next 4-byte word. The length is measured in 4-byte
135       // words including padding, not bytes of actual string.
136       return (s.size() / 4) + 1;
137     }
138
139     void writeGCOVString(StringRef s) {
140       uint32_t Len = lengthOfGCOVString(s);
141       write(Len);
142       writeBytes(s.data(), s.size());
143
144       // Write 1 to 4 bytes of NUL padding.
145       assert((unsigned)(4 - (s.size() % 4)) > 0);
146       assert((unsigned)(4 - (s.size() % 4)) <= 4);
147       writeBytes("\0\0\0\0", 4 - (s.size() % 4));
148     }
149
150     raw_ostream *os;
151   };
152   const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
153   const char *GCOVRecord::FunctionTag = "\0\0\0\1";
154   const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
155   const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
156
157   class GCOVFunction;
158   class GCOVBlock;
159
160   // Constructed only by requesting it from a GCOVBlock, this object stores a
161   // list of line numbers and a single filename, representing lines that belong
162   // to the block.
163   class GCOVLines : public GCOVRecord {
164    public:
165     void addLine(uint32_t Line) {
166       Lines.push_back(Line);
167     }
168
169     uint32_t length() {
170       return lengthOfGCOVString(Filename) + 2 + Lines.size();
171     }
172
173    private:
174     friend class GCOVBlock;
175
176     GCOVLines(std::string Filename, raw_ostream *os)
177         : Filename(Filename) {
178       this->os = os;
179     }
180
181     std::string Filename;
182     SmallVector<uint32_t, 32> Lines;
183   };
184
185   // Represent a basic block in GCOV. Each block has a unique number in the
186   // function, number of lines belonging to each block, and a set of edges to
187   // other blocks.
188   class GCOVBlock : public GCOVRecord {
189    public:
190     GCOVLines &getFile(std::string Filename) {
191       GCOVLines *&Lines = LinesByFile[Filename];
192       if (!Lines) {
193         Lines = new GCOVLines(Filename, os);
194       }
195       return *Lines;
196     }
197
198     void addEdge(GCOVBlock &Successor) {
199       OutEdges.push_back(&Successor);
200     }
201
202     void writeOut() {
203       uint32_t Len = 3;
204       for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
205                E = LinesByFile.end(); I != E; ++I) {
206         Len += I->second->length();
207       }
208
209       writeBytes(LinesTag, 4);
210       write(Len);
211       write(Number);
212       for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
213                E = LinesByFile.end(); I != E; ++I) {
214         write(0);
215         writeGCOVString(I->second->Filename);
216         for (int i = 0, e = I->second->Lines.size(); i != e; ++i) {
217           write(I->second->Lines[i]);
218         }
219       }
220       write(0);
221       write(0);
222     }
223
224     ~GCOVBlock() {
225       DeleteContainerSeconds(LinesByFile);
226     }
227
228    private:
229     friend class GCOVFunction;
230
231     GCOVBlock(uint32_t Number, raw_ostream *os)
232         : Number(Number) {
233       this->os = os;
234     }
235
236     uint32_t Number;
237     StringMap<GCOVLines *> LinesByFile;
238     SmallVector<GCOVBlock *, 4> OutEdges;
239   };
240
241   // A function has a unique identifier, a checksum (we leave as zero) and a
242   // set of blocks and a map of edges between blocks. This is the only GCOV
243   // object users can construct, the blocks and lines will be rooted here.
244   class GCOVFunction : public GCOVRecord {
245    public:
246     GCOVFunction(DISubprogram SP, raw_ostream *os, bool Use402Format) {
247       this->os = os;
248
249       Function *F = SP.getFunction();
250       uint32_t i = 0;
251       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
252         Blocks[BB] = new GCOVBlock(i++, os);
253       }
254       ReturnBlock = new GCOVBlock(i++, os);
255
256       writeBytes(FunctionTag, 4);
257       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
258           1 + lengthOfGCOVString(SP.getFilename()) + 1;
259       if (!Use402Format)
260         ++BlockLen; // For second checksum.
261       write(BlockLen);
262       uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
263       write(Ident);
264       write(0);  // checksum #1
265       if (!Use402Format)
266         write(0);  // checksum #2
267       writeGCOVString(SP.getName());
268       writeGCOVString(SP.getFilename());
269       write(SP.getLineNumber());
270     }
271
272     ~GCOVFunction() {
273       DeleteContainerSeconds(Blocks);
274       delete ReturnBlock;
275     }
276
277     GCOVBlock &getBlock(BasicBlock *BB) {
278       return *Blocks[BB];
279     }
280
281     GCOVBlock &getReturnBlock() {
282       return *ReturnBlock;
283     }
284
285     void writeOut() {
286       // Emit count of blocks.
287       writeBytes(BlockTag, 4);
288       write(Blocks.size() + 1);
289       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
290         write(0);  // No flags on our blocks.
291       }
292
293       // Emit edges between blocks.
294       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
295                E = Blocks.end(); I != E; ++I) {
296         GCOVBlock &Block = *I->second;
297         if (Block.OutEdges.empty()) continue;
298
299         writeBytes(EdgeTag, 4);
300         write(Block.OutEdges.size() * 2 + 1);
301         write(Block.Number);
302         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
303           write(Block.OutEdges[i]->Number);
304           write(0);  // no flags
305         }
306       }
307
308       // Emit lines for each block.
309       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
310                E = Blocks.end(); I != E; ++I) {
311         I->second->writeOut();
312       }
313     }
314
315    private:
316     DenseMap<BasicBlock *, GCOVBlock *> Blocks;
317     GCOVBlock *ReturnBlock;
318   };
319 }
320
321 std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
322   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
323     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
324       MDNode *N = GCov->getOperand(i);
325       if (N->getNumOperands() != 2) continue;
326       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
327       MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
328       if (!GCovFile || !CompileUnit) continue;
329       if (CompileUnit == CU) {
330         SmallString<128> Filename = GCovFile->getString();
331         sys::path::replace_extension(Filename, NewStem);
332         return Filename.str();
333       }
334     }
335   }
336
337   SmallString<128> Filename = CU.getFilename();
338   sys::path::replace_extension(Filename, NewStem);
339   return sys::path::filename(Filename.str());
340 }
341
342 bool GCOVProfiler::runOnModule(Module &M) {
343   this->M = &M;
344   Ctx = &M.getContext();
345
346   if (EmitNotes) emitGCNO();
347   if (EmitData) return emitProfileArcs();
348   return false;
349 }
350
351 void GCOVProfiler::emitGCNO() {
352   DenseMap<const MDNode *, raw_fd_ostream *> GcnoFiles;
353   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
354   if (CU_Nodes) {
355     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
356       // Each compile unit gets its own .gcno file. This means that whether we run
357       // this pass over the original .o's as they're produced, or run it after
358       // LTO, we'll generate the same .gcno files.
359       
360       DICompileUnit CU(CU_Nodes->getOperand(i));
361       raw_fd_ostream *&out = GcnoFiles[CU];
362       std::string ErrorInfo;
363       out = new raw_fd_ostream(mangleName(CU, "gcno").c_str(), ErrorInfo,
364                                raw_fd_ostream::F_Binary);
365       if (!Use402Format)
366         out->write("oncg*404MVLL", 12);
367       else
368         out->write("oncg*204MVLL", 12);
369   
370       DIArray SPs = CU.getSubprograms();
371       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
372         DISubprogram SP(SPs.getElement(i));
373         if (!SP.Verify()) continue;
374         raw_fd_ostream *&os = GcnoFiles[CU];
375         
376         Function *F = SP.getFunction();
377         if (!F) continue;
378         GCOVFunction Func(SP, os, Use402Format);
379         
380         for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
381           GCOVBlock &Block = Func.getBlock(BB);
382           TerminatorInst *TI = BB->getTerminator();
383           if (int successors = TI->getNumSuccessors()) {
384             for (int i = 0; i != successors; ++i) {
385               Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
386             }
387           } else if (isa<ReturnInst>(TI)) {
388             Block.addEdge(Func.getReturnBlock());
389           }
390           
391           uint32_t Line = 0;
392           for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
393             const DebugLoc &Loc = I->getDebugLoc();
394             if (Loc.isUnknown()) continue;
395             if (Line == Loc.getLine()) continue;
396             Line = Loc.getLine();
397             if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
398             
399             GCOVLines &Lines = Block.getFile(SP.getFilename());
400             Lines.addLine(Loc.getLine());
401           }
402         }
403         Func.writeOut();
404       }
405     }
406   }
407
408   for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
409            I = GcnoFiles.begin(), E = GcnoFiles.end(); I != E; ++I) {
410     raw_fd_ostream *&out = I->second;
411     out->write("\0\0\0\0\0\0\0\0", 8);  // EOF
412     out->close();
413     delete out;
414   }
415 }
416
417 bool GCOVProfiler::emitProfileArcs() {
418   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
419   if (!CU_Nodes) return false;
420
421   bool Result = false;  
422   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
423     DICompileUnit CU(CU_Nodes->getOperand(i));
424     DIArray SPs = CU.getSubprograms();
425     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
426     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
427       DISubprogram SP(SPs.getElement(i));
428       if (!SP.Verify()) continue;
429       Function *F = SP.getFunction();
430       if (!F) continue;
431       if (!Result) Result = true;
432       unsigned Edges = 0;
433       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
434         TerminatorInst *TI = BB->getTerminator();
435         if (isa<ReturnInst>(TI))
436           ++Edges;
437         else
438           Edges += TI->getNumSuccessors();
439       }
440       
441       ArrayType *CounterTy =
442         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
443       GlobalVariable *Counters =
444         new GlobalVariable(*M, CounterTy, false,
445                            GlobalValue::InternalLinkage,
446                            Constant::getNullValue(CounterTy),
447                            "__llvm_gcov_ctr", 0, false, 0);
448       CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
449       
450       UniqueVector<BasicBlock *> ComplexEdgePreds;
451       UniqueVector<BasicBlock *> ComplexEdgeSuccs;
452       
453       unsigned Edge = 0;
454       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
455         TerminatorInst *TI = BB->getTerminator();
456         int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
457         if (Successors) {
458           IRBuilder<> Builder(TI);
459           
460           if (Successors == 1) {
461             Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
462                                                                 Edge);
463             Value *Count = Builder.CreateLoad(Counter);
464             Count = Builder.CreateAdd(Count,
465                                       ConstantInt::get(Type::getInt64Ty(*Ctx),1));
466             Builder.CreateStore(Count, Counter);
467           } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
468             Value *Sel = Builder.CreateSelect(
469               BI->getCondition(),
470               ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
471               ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
472             SmallVector<Value *, 2> Idx;
473             Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
474             Idx.push_back(Sel);
475             Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
476             Value *Count = Builder.CreateLoad(Counter);
477             Count = Builder.CreateAdd(Count,
478                                       ConstantInt::get(Type::getInt64Ty(*Ctx),1));
479             Builder.CreateStore(Count, Counter);
480           } else {
481             ComplexEdgePreds.insert(BB);
482             for (int i = 0; i != Successors; ++i)
483               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
484           }
485           Edge += Successors;
486         }
487       }
488       
489       if (!ComplexEdgePreds.empty()) {
490         GlobalVariable *EdgeTable =
491           buildEdgeLookupTable(F, Counters,
492                                ComplexEdgePreds, ComplexEdgeSuccs);
493         GlobalVariable *EdgeState = getEdgeStateValue();
494         
495         Type *Int32Ty = Type::getInt32Ty(*Ctx);
496         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
497           IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
498           Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
499         }
500         for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
501           // call runtime to perform increment
502           BasicBlock::iterator InsertPt =
503             ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
504           IRBuilder<> Builder(InsertPt);
505           Value *CounterPtrArray =
506             Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
507                                                i * ComplexEdgePreds.size());
508           Builder.CreateCall2(getIncrementIndirectCounterFunc(),
509                               EdgeState, CounterPtrArray);
510           // clear the predecessor number
511           Builder.CreateStore(ConstantInt::get(Int32Ty, 0xffffffff), EdgeState);
512         }
513       }
514     }
515     insertCounterWriteout(CountersBySP);
516   }
517   return Result;
518 }
519
520 // All edges with successors that aren't branches are "complex", because it
521 // requires complex logic to pick which counter to update.
522 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
523     Function *F,
524     GlobalVariable *Counters,
525     const UniqueVector<BasicBlock *> &Preds,
526     const UniqueVector<BasicBlock *> &Succs) {
527   // TODO: support invoke, threads. We rely on the fact that nothing can modify
528   // the whole-Module pred edge# between the time we set it and the time we next
529   // read it. Threads and invoke make this untrue.
530
531   // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
532   Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
533   ArrayType *EdgeTableTy = ArrayType::get(
534       Int64PtrTy, Succs.size() * Preds.size());
535
536   Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
537   Constant *NullValue = Constant::getNullValue(Int64PtrTy);
538   for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
539     EdgeTable[i] = NullValue;
540
541   unsigned Edge = 0;
542   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
543     TerminatorInst *TI = BB->getTerminator();
544     int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
545     if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
546       for (int i = 0; i != Successors; ++i) {
547         BasicBlock *Succ = TI->getSuccessor(i);
548         IRBuilder<> builder(Succ);
549         Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
550                                                             Edge + i);
551         EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
552                   (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
553       }
554     }
555     Edge += Successors;
556   }
557
558   ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
559   GlobalVariable *EdgeTableGV =
560       new GlobalVariable(
561           *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
562           ConstantArray::get(EdgeTableTy, V),
563           "__llvm_gcda_edge_table");
564   EdgeTableGV->setUnnamedAddr(true);
565   return EdgeTableGV;
566 }
567
568 Constant *GCOVProfiler::getStartFileFunc() {
569   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
570                                               Type::getInt8PtrTy(*Ctx), false);
571   return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
572 }
573
574 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
575   Type *Args[] = {
576     Type::getInt32PtrTy(*Ctx),                  // uint32_t *predecessor
577     Type::getInt64PtrTy(*Ctx)->getPointerTo(),  // uint64_t **state_table_row
578   };
579   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
580                                               Args, false);
581   return M->getOrInsertFunction("llvm_gcda_increment_indirect_counter", FTy);
582 }
583
584 Constant *GCOVProfiler::getEmitFunctionFunc() {
585   Type *Args[2] = {
586     Type::getInt32Ty(*Ctx),    // uint32_t ident
587     Type::getInt8PtrTy(*Ctx),  // const char *function_name
588   };
589   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
590                                               Args, false);
591   return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
592 }
593
594 Constant *GCOVProfiler::getEmitArcsFunc() {
595   Type *Args[] = {
596     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
597     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
598   };
599   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
600                                               Args, false);
601   return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
602 }
603
604 Constant *GCOVProfiler::getEndFileFunc() {
605   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
606   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
607 }
608
609 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
610   GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
611   if (!GV) {
612     GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
613                             GlobalValue::InternalLinkage,
614                             ConstantInt::get(Type::getInt32Ty(*Ctx),
615                                              0xffffffff),
616                             "__llvm_gcov_global_state_pred");
617     GV->setUnnamedAddr(true);
618   }
619   return GV;
620 }
621
622 void GCOVProfiler::insertCounterWriteout(
623     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> &CountersBySP) {
624   FunctionType *WriteoutFTy =
625       FunctionType::get(Type::getVoidTy(*Ctx), false);
626   Function *WriteoutF = Function::Create(WriteoutFTy,
627                                          GlobalValue::InternalLinkage,
628                                          "__llvm_gcov_writeout", M);
629   WriteoutF->setUnnamedAddr(true);
630   BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
631   IRBuilder<> Builder(BB);
632
633   Constant *StartFile = getStartFileFunc();
634   Constant *EmitFunction = getEmitFunctionFunc();
635   Constant *EmitArcs = getEmitArcsFunc();
636   Constant *EndFile = getEndFileFunc();
637
638   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
639   if (CU_Nodes) {
640     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
641       DICompileUnit compile_unit(CU_Nodes->getOperand(i));
642       std::string FilenameGcda = mangleName(compile_unit, "gcda");
643       Builder.CreateCall(StartFile,
644                          Builder.CreateGlobalStringPtr(FilenameGcda));
645       for (SmallVector<std::pair<GlobalVariable *, MDNode *>, 8>::iterator
646              I = CountersBySP.begin(), E = CountersBySP.end();
647            I != E; ++I) {
648         DISubprogram SP(I->second);
649         intptr_t ident = reinterpret_cast<intptr_t>(I->second);
650         Builder.CreateCall2(EmitFunction,
651                             ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
652                             Builder.CreateGlobalStringPtr(SP.getName()));
653         
654         GlobalVariable *GV = I->first;
655         unsigned Arcs =
656           cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
657         Builder.CreateCall2(EmitArcs,
658                             ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
659                             Builder.CreateConstGEP2_64(GV, 0, 0));
660       }
661       Builder.CreateCall(EndFile);
662     }
663   }
664   Builder.CreateRetVoid();
665
666   InsertProfilingShutdownCall(WriteoutF, M);
667 }