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