Move all of the header files which are involved in modelling the LLVM IR
[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       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
50     }
51     GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format,
52                  bool useExtraChecksum, bool NoRedZone_)
53         : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
54           Use402Format(use402Format), UseExtraChecksum(useExtraChecksum),
55           NoRedZone(NoRedZone_) {
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     bool NoRedZone;
103
104     Module *M;
105     LLVMContext *Ctx;
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                                          bool NoRedZone) {
117   return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum,
118                           NoRedZone);
119 }
120
121 namespace {
122   class GCOVRecord {
123    protected:
124     static const char *LinesTag;
125     static const char *FunctionTag;
126     static const char *BlockTag;
127     static const char *EdgeTag;
128
129     GCOVRecord() {}
130
131     void writeBytes(const char *Bytes, int Size) {
132       os->write(Bytes, Size);
133     }
134
135     void write(uint32_t i) {
136       writeBytes(reinterpret_cast<char*>(&i), 4);
137     }
138
139     // Returns the length measured in 4-byte blocks that will be used to
140     // represent this string in a GCOV file
141     unsigned lengthOfGCOVString(StringRef s) {
142       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
143       // padding out to the next 4-byte word. The length is measured in 4-byte
144       // words including padding, not bytes of actual string.
145       return (s.size() / 4) + 1;
146     }
147
148     void writeGCOVString(StringRef s) {
149       uint32_t Len = lengthOfGCOVString(s);
150       write(Len);
151       writeBytes(s.data(), s.size());
152
153       // Write 1 to 4 bytes of NUL padding.
154       assert((unsigned)(4 - (s.size() % 4)) > 0);
155       assert((unsigned)(4 - (s.size() % 4)) <= 4);
156       writeBytes("\0\0\0\0", 4 - (s.size() % 4));
157     }
158
159     raw_ostream *os;
160   };
161   const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
162   const char *GCOVRecord::FunctionTag = "\0\0\0\1";
163   const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
164   const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
165
166   class GCOVFunction;
167   class GCOVBlock;
168
169   // Constructed only by requesting it from a GCOVBlock, this object stores a
170   // list of line numbers and a single filename, representing lines that belong
171   // to the block.
172   class GCOVLines : public GCOVRecord {
173    public:
174     void addLine(uint32_t Line) {
175       Lines.push_back(Line);
176     }
177
178     uint32_t length() {
179       // Here 2 = 1 for string length + 1 for '0' id#.
180       return lengthOfGCOVString(Filename) + 2 + Lines.size();
181     }
182
183     void writeOut() {
184       write(0);
185       writeGCOVString(Filename);
186       for (int i = 0, e = Lines.size(); i != e; ++i)
187         write(Lines[i]);
188     }
189
190     GCOVLines(StringRef F, raw_ostream *os) 
191       : Filename(F) {
192       this->os = os;
193     }
194
195    private:
196     StringRef Filename;
197     SmallVector<uint32_t, 32> Lines;
198   };
199
200   // Represent a basic block in GCOV. Each block has a unique number in the
201   // function, number of lines belonging to each block, and a set of edges to
202   // other blocks.
203   class GCOVBlock : public GCOVRecord {
204    public:
205     GCOVLines &getFile(StringRef Filename) {
206       GCOVLines *&Lines = LinesByFile[Filename];
207       if (!Lines) {
208         Lines = new GCOVLines(Filename, os);
209       }
210       return *Lines;
211     }
212
213     void addEdge(GCOVBlock &Successor) {
214       OutEdges.push_back(&Successor);
215     }
216
217     void writeOut() {
218       uint32_t Len = 3;
219       for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
220                E = LinesByFile.end(); I != E; ++I) {
221         Len += I->second->length();
222       }
223
224       writeBytes(LinesTag, 4);
225       write(Len);
226       write(Number);
227       for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
228                E = LinesByFile.end(); I != E; ++I) 
229         I->second->writeOut();
230       write(0);
231       write(0);
232     }
233
234     ~GCOVBlock() {
235       DeleteContainerSeconds(LinesByFile);
236     }
237
238    private:
239     friend class GCOVFunction;
240
241     GCOVBlock(uint32_t Number, raw_ostream *os)
242         : Number(Number) {
243       this->os = os;
244     }
245
246     uint32_t Number;
247     StringMap<GCOVLines *> LinesByFile;
248     SmallVector<GCOVBlock *, 4> OutEdges;
249   };
250
251   // A function has a unique identifier, a checksum (we leave as zero) and a
252   // set of blocks and a map of edges between blocks. This is the only GCOV
253   // object users can construct, the blocks and lines will be rooted here.
254   class GCOVFunction : public GCOVRecord {
255    public:
256     GCOVFunction(DISubprogram SP, raw_ostream *os,
257                  bool Use402Format, bool UseExtraChecksum) {
258       this->os = os;
259
260       Function *F = SP.getFunction();
261       DEBUG(dbgs() << "Function: " << F->getName() << "\n");
262       uint32_t i = 0;
263       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
264         Blocks[BB] = new GCOVBlock(i++, os);
265       }
266       ReturnBlock = new GCOVBlock(i++, os);
267
268       writeBytes(FunctionTag, 4);
269       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
270           1 + lengthOfGCOVString(SP.getFilename()) + 1;
271       if (UseExtraChecksum)
272         ++BlockLen;
273       write(BlockLen);
274       uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
275       write(Ident);
276       write(0);  // lineno checksum
277       if (UseExtraChecksum)
278         write(0);  // cfg checksum
279       writeGCOVString(SP.getName());
280       writeGCOVString(SP.getFilename());
281       write(SP.getLineNumber());
282     }
283
284     ~GCOVFunction() {
285       DeleteContainerSeconds(Blocks);
286       delete ReturnBlock;
287     }
288
289     GCOVBlock &getBlock(BasicBlock *BB) {
290       return *Blocks[BB];
291     }
292
293     GCOVBlock &getReturnBlock() {
294       return *ReturnBlock;
295     }
296
297     void writeOut() {
298       // Emit count of blocks.
299       writeBytes(BlockTag, 4);
300       write(Blocks.size() + 1);
301       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
302         write(0);  // No flags on our blocks.
303       }
304       DEBUG(dbgs() << Blocks.size() << " blocks.\n");
305
306       // Emit edges between blocks.
307       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
308                E = Blocks.end(); I != E; ++I) {
309         GCOVBlock &Block = *I->second;
310         if (Block.OutEdges.empty()) continue;
311
312         writeBytes(EdgeTag, 4);
313         write(Block.OutEdges.size() * 2 + 1);
314         write(Block.Number);
315         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
316           DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
317                        << "\n");
318           write(Block.OutEdges[i]->Number);
319           write(0);  // no flags
320         }
321       }
322
323       // Emit lines for each block.
324       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
325                E = Blocks.end(); I != E; ++I) {
326         I->second->writeOut();
327       }
328     }
329
330    private:
331     DenseMap<BasicBlock *, GCOVBlock *> Blocks;
332     GCOVBlock *ReturnBlock;
333   };
334 }
335
336 std::string GCOVProfiler::mangleName(DICompileUnit CU, const char *NewStem) {
337   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
338     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
339       MDNode *N = GCov->getOperand(i);
340       if (N->getNumOperands() != 2) continue;
341       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
342       MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
343       if (!GCovFile || !CompileUnit) continue;
344       if (CompileUnit == CU) {
345         SmallString<128> Filename = GCovFile->getString();
346         sys::path::replace_extension(Filename, NewStem);
347         return Filename.str();
348       }
349     }
350   }
351
352   SmallString<128> Filename = CU.getFilename();
353   sys::path::replace_extension(Filename, NewStem);
354   return sys::path::filename(Filename.str());
355 }
356
357 bool GCOVProfiler::runOnModule(Module &M) {
358   this->M = &M;
359   Ctx = &M.getContext();
360
361   if (EmitNotes) emitGCNO();
362   if (EmitData) return emitProfileArcs();
363   return false;
364 }
365
366 void GCOVProfiler::emitGCNO() {
367   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
368   if (!CU_Nodes) return;
369
370   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
371     // Each compile unit gets its own .gcno file. This means that whether we run
372     // this pass over the original .o's as they're produced, or run it after
373     // LTO, we'll generate the same .gcno files.
374
375     DICompileUnit CU(CU_Nodes->getOperand(i));
376     std::string ErrorInfo;
377     raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
378                        raw_fd_ostream::F_Binary);
379     if (!Use402Format)
380       out.write("oncg*404MVLL", 12);
381     else
382       out.write("oncg*204MVLL", 12);
383
384     DIArray SPs = CU.getSubprograms();
385     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
386       DISubprogram SP(SPs.getElement(i));
387       if (!SP.Verify()) continue;
388
389       Function *F = SP.getFunction();
390       if (!F) continue;
391       GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
392
393       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
394         GCOVBlock &Block = Func.getBlock(BB);
395         TerminatorInst *TI = BB->getTerminator();
396         if (int successors = TI->getNumSuccessors()) {
397           for (int i = 0; i != successors; ++i) {
398             Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
399           }
400         } else if (isa<ReturnInst>(TI)) {
401           Block.addEdge(Func.getReturnBlock());
402         }
403
404         uint32_t Line = 0;
405         for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
406              I != IE; ++I) {
407           const DebugLoc &Loc = I->getDebugLoc();
408           if (Loc.isUnknown()) continue;
409           if (Line == Loc.getLine()) continue;
410           Line = Loc.getLine();
411           if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
412
413           GCOVLines &Lines = Block.getFile(SP.getFilename());
414           Lines.addLine(Loc.getLine());
415         }
416       }
417       Func.writeOut();
418     }
419     out.write("\0\0\0\0\0\0\0\0", 8);  // EOF
420     out.close();
421   }
422 }
423
424 bool GCOVProfiler::emitProfileArcs() {
425   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
426   if (!CU_Nodes) return false;
427
428   bool Result = false;  
429   bool InsertIndCounterIncrCode = false;
430   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
431     DICompileUnit CU(CU_Nodes->getOperand(i));
432     DIArray SPs = CU.getSubprograms();
433     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
434     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
435       DISubprogram SP(SPs.getElement(i));
436       if (!SP.Verify()) continue;
437       Function *F = SP.getFunction();
438       if (!F) continue;
439       if (!Result) Result = true;
440       unsigned Edges = 0;
441       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
442         TerminatorInst *TI = BB->getTerminator();
443         if (isa<ReturnInst>(TI))
444           ++Edges;
445         else
446           Edges += TI->getNumSuccessors();
447       }
448       
449       ArrayType *CounterTy =
450         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
451       GlobalVariable *Counters =
452         new GlobalVariable(*M, CounterTy, false,
453                            GlobalValue::InternalLinkage,
454                            Constant::getNullValue(CounterTy),
455                            "__llvm_gcov_ctr");
456       CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
457       
458       UniqueVector<BasicBlock *> ComplexEdgePreds;
459       UniqueVector<BasicBlock *> ComplexEdgeSuccs;
460       
461       unsigned Edge = 0;
462       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
463         TerminatorInst *TI = BB->getTerminator();
464         int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
465         if (Successors) {
466           IRBuilder<> Builder(TI);
467           
468           if (Successors == 1) {
469             Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
470                                                                 Edge);
471             Value *Count = Builder.CreateLoad(Counter);
472             Count = Builder.CreateAdd(Count,
473                                       ConstantInt::get(Type::getInt64Ty(*Ctx),1));
474             Builder.CreateStore(Count, Counter);
475           } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
476             Value *Sel = Builder.CreateSelect(
477               BI->getCondition(),
478               ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
479               ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
480             SmallVector<Value *, 2> Idx;
481             Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
482             Idx.push_back(Sel);
483             Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
484             Value *Count = Builder.CreateLoad(Counter);
485             Count = Builder.CreateAdd(Count,
486                                       ConstantInt::get(Type::getInt64Ty(*Ctx),1));
487             Builder.CreateStore(Count, Counter);
488           } else {
489             ComplexEdgePreds.insert(BB);
490             for (int i = 0; i != Successors; ++i)
491               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
492           }
493           Edge += Successors;
494         }
495       }
496       
497       if (!ComplexEdgePreds.empty()) {
498         GlobalVariable *EdgeTable =
499           buildEdgeLookupTable(F, Counters,
500                                ComplexEdgePreds, ComplexEdgeSuccs);
501         GlobalVariable *EdgeState = getEdgeStateValue();
502         
503         Type *Int32Ty = Type::getInt32Ty(*Ctx);
504         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
505           IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
506           Builder.CreateStore(ConstantInt::get(Int32Ty, 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                             ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
671                             Builder.CreateGlobalStringPtr(SP.getName()));
672         
673         GlobalVariable *GV = I->first;
674         unsigned Arcs =
675           cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
676         Builder.CreateCall2(EmitArcs,
677                             ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
678                             Builder.CreateConstGEP2_64(GV, 0, 0));
679       }
680       Builder.CreateCall(EndFile);
681     }
682   }
683   Builder.CreateRetVoid();
684
685   // Create a small bit of code that registers the "__llvm_gcov_writeout"
686   // function to be executed at exit.
687   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
688   Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
689                                  "__llvm_gcov_init", M);
690   F->setUnnamedAddr(true);
691   F->setLinkage(GlobalValue::InternalLinkage);
692   F->addFnAttr(Attribute::NoInline);
693   if (NoRedZone)
694     F->addFnAttr(Attribute::NoRedZone);
695
696   BB = BasicBlock::Create(*Ctx, "entry", F);
697   Builder.SetInsertPoint(BB);
698
699   FTy = FunctionType::get(Type::getInt32Ty(*Ctx),
700                           PointerType::get(FTy, 0), false);
701   Constant *AtExitFn = M->getOrInsertFunction("atexit", FTy);
702   Builder.CreateCall(AtExitFn, WriteoutF);
703   Builder.CreateRetVoid();
704
705   appendToGlobalCtors(*M, F, 0);
706 }
707
708 void GCOVProfiler::insertIndirectCounterIncrement() {
709   Function *Fn =
710     cast<Function>(GCOVProfiler::getIncrementIndirectCounterFunc());
711   Fn->setUnnamedAddr(true);
712   Fn->setLinkage(GlobalValue::InternalLinkage);
713   Fn->addFnAttr(Attribute::NoInline);
714   if (NoRedZone)
715     Fn->addFnAttr(Attribute::NoRedZone);
716
717   Type *Int32Ty = Type::getInt32Ty(*Ctx);
718   Type *Int64Ty = Type::getInt64Ty(*Ctx);
719   Constant *NegOne = ConstantInt::get(Int32Ty, 0xffffffff);
720
721   // Create basic blocks for function.
722   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", Fn);
723   IRBuilder<> Builder(BB);
724
725   BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn);
726   BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn);
727   BasicBlock *Exit = BasicBlock::Create(*Ctx, "exit", Fn);
728
729   // uint32_t pred = *predecessor;
730   // if (pred == 0xffffffff) return;
731   Argument *Arg = Fn->arg_begin();
732   Arg->setName("predecessor");
733   Value *Pred = Builder.CreateLoad(Arg, "pred");
734   Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
735   BranchInst::Create(Exit, PredNotNegOne, Cond, BB);
736
737   Builder.SetInsertPoint(PredNotNegOne);
738
739   // uint64_t *counter = counters[pred];
740   // if (!counter) return;
741   Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
742   Arg = llvm::next(Fn->arg_begin());
743   Arg->setName("counters");
744   Value *GEP = Builder.CreateGEP(Arg, ZExtPred);
745   Value *Counter = Builder.CreateLoad(GEP, "counter");
746   Cond = Builder.CreateICmpEQ(Counter,
747                               Constant::getNullValue(Int64Ty->getPointerTo()));
748   Builder.CreateCondBr(Cond, Exit, CounterEnd);
749
750   // ++*counter;
751   Builder.SetInsertPoint(CounterEnd);
752   Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
753                                  ConstantInt::get(Int64Ty, 1));
754   Builder.CreateStore(Add, Counter);
755   Builder.CreateBr(Exit);
756
757   // Fill in the exit block.
758   Builder.SetInsertPoint(Exit);
759   Builder.CreateRetVoid();
760 }
761
762 void GCOVProfiler::
763 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
764   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
765   Function *FlushF = M->getFunction("__gcov_flush");
766   if (!FlushF)
767     FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
768                               "__gcov_flush", M);
769   else
770     FlushF->setLinkage(GlobalValue::InternalLinkage);
771   FlushF->setUnnamedAddr(true);
772   FlushF->addFnAttr(Attribute::NoInline);
773   if (NoRedZone)
774     FlushF->addFnAttr(Attribute::NoRedZone);
775
776   BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
777
778   // Write out the current counters.
779   Constant *WriteoutF = M->getFunction("__llvm_gcov_writeout");
780   assert(WriteoutF && "Need to create the writeout function first!");
781
782   IRBuilder<> Builder(Entry);
783   Builder.CreateCall(WriteoutF);
784
785   // Zero out the counters.
786   for (ArrayRef<std::pair<GlobalVariable *, MDNode *> >::iterator
787          I = CountersBySP.begin(), E = CountersBySP.end();
788        I != E; ++I) {
789     GlobalVariable *GV = I->first;
790     Constant *Null = Constant::getNullValue(GV->getType()->getElementType());
791     Builder.CreateStore(Null, GV);
792   }
793
794   Type *RetTy = FlushF->getReturnType();
795   if (RetTy == Type::getVoidTy(*Ctx))
796     Builder.CreateRetVoid();
797   else if (RetTy->isIntegerTy())
798     // Used if __gcov_flush was implicitly declared.
799     Builder.CreateRet(ConstantInt::get(RetTy, 0));
800   else
801     report_fatal_error("invalid return type for __gcov_flush");
802 }