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