LLVM API Documentation

AddDiscriminators.cpp
Go to the documentation of this file.
00001 //===- AddDiscriminators.cpp - Insert DWARF path discriminators -----------===//
00002 //
00003 //                      The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file adds DWARF discriminators to the IR. Path discriminators are
00011 // used to decide what CFG path was taken inside sub-graphs whose instructions
00012 // share the same line and column number information.
00013 //
00014 // The main user of this is the sample profiler. Instruction samples are
00015 // mapped to line number information. Since a single line may be spread
00016 // out over several basic blocks, discriminators add more precise location
00017 // for the samples.
00018 //
00019 // For example,
00020 //
00021 //   1  #define ASSERT(P)
00022 //   2      if (!(P))
00023 //   3        abort()
00024 //   ...
00025 //   100   while (true) {
00026 //   101     ASSERT (sum < 0);
00027 //   102     ...
00028 //   130   }
00029 //
00030 // when converted to IR, this snippet looks something like:
00031 //
00032 // while.body:                                       ; preds = %entry, %if.end
00033 //   %0 = load i32* %sum, align 4, !dbg !15
00034 //   %cmp = icmp slt i32 %0, 0, !dbg !15
00035 //   br i1 %cmp, label %if.end, label %if.then, !dbg !15
00036 //
00037 // if.then:                                          ; preds = %while.body
00038 //   call void @abort(), !dbg !15
00039 //   br label %if.end, !dbg !15
00040 //
00041 // Notice that all the instructions in blocks 'while.body' and 'if.then'
00042 // have exactly the same debug information. When this program is sampled
00043 // at runtime, the profiler will assume that all these instructions are
00044 // equally frequent. This, in turn, will consider the edge while.body->if.then
00045 // to be frequently taken (which is incorrect).
00046 //
00047 // By adding a discriminator value to the instructions in block 'if.then',
00048 // we can distinguish instructions at line 101 with discriminator 0 from
00049 // the instructions at line 101 with discriminator 1.
00050 //
00051 // For more details about DWARF discriminators, please visit
00052 // http://wiki.dwarfstd.org/index.php?title=Path_Discriminators
00053 //===----------------------------------------------------------------------===//
00054 
00055 #include "llvm/Transforms/Scalar.h"
00056 #include "llvm/IR/BasicBlock.h"
00057 #include "llvm/IR/Constants.h"
00058 #include "llvm/IR/DIBuilder.h"
00059 #include "llvm/IR/DebugInfo.h"
00060 #include "llvm/IR/Instructions.h"
00061 #include "llvm/IR/LLVMContext.h"
00062 #include "llvm/IR/Module.h"
00063 #include "llvm/Pass.h"
00064 #include "llvm/Support/CommandLine.h"
00065 #include "llvm/Support/Debug.h"
00066 #include "llvm/Support/raw_ostream.h"
00067 
00068 using namespace llvm;
00069 
00070 #define DEBUG_TYPE "add-discriminators"
00071 
00072 namespace {
00073   struct AddDiscriminators : public FunctionPass {
00074     static char ID; // Pass identification, replacement for typeid
00075     AddDiscriminators() : FunctionPass(ID) {
00076       initializeAddDiscriminatorsPass(*PassRegistry::getPassRegistry());
00077     }
00078 
00079     bool runOnFunction(Function &F) override;
00080   };
00081 }
00082 
00083 char AddDiscriminators::ID = 0;
00084 INITIALIZE_PASS_BEGIN(AddDiscriminators, "add-discriminators",
00085                       "Add DWARF path discriminators", false, false)
00086 INITIALIZE_PASS_END(AddDiscriminators, "add-discriminators",
00087                     "Add DWARF path discriminators", false, false)
00088 
00089 // Command line option to disable discriminator generation even in the
00090 // presence of debug information. This is only needed when debugging
00091 // debug info generation issues.
00092 static cl::opt<bool>
00093 NoDiscriminators("no-discriminators", cl::init(false),
00094                  cl::desc("Disable generation of discriminator information."));
00095 
00096 FunctionPass *llvm::createAddDiscriminatorsPass() {
00097   return new AddDiscriminators();
00098 }
00099 
00100 static bool hasDebugInfo(const Function &F) {
00101   NamedMDNode *CUNodes = F.getParent()->getNamedMetadata("llvm.dbg.cu");
00102   return CUNodes != nullptr;
00103 }
00104 
00105 /// \brief Assign DWARF discriminators.
00106 ///
00107 /// To assign discriminators, we examine the boundaries of every
00108 /// basic block and its successors. Suppose there is a basic block B1
00109 /// with successor B2. The last instruction I1 in B1 and the first
00110 /// instruction I2 in B2 are located at the same file and line number.
00111 /// This situation is illustrated in the following code snippet:
00112 ///
00113 ///       if (i < 10) x = i;
00114 ///
00115 ///     entry:
00116 ///       br i1 %cmp, label %if.then, label %if.end, !dbg !10
00117 ///     if.then:
00118 ///       %1 = load i32* %i.addr, align 4, !dbg !10
00119 ///       store i32 %1, i32* %x, align 4, !dbg !10
00120 ///       br label %if.end, !dbg !10
00121 ///     if.end:
00122 ///       ret void, !dbg !12
00123 ///
00124 /// Notice how the branch instruction in block 'entry' and all the
00125 /// instructions in block 'if.then' have the exact same debug location
00126 /// information (!dbg !10).
00127 ///
00128 /// To distinguish instructions in block 'entry' from instructions in
00129 /// block 'if.then', we generate a new lexical block for all the
00130 /// instruction in block 'if.then' that share the same file and line
00131 /// location with the last instruction of block 'entry'.
00132 ///
00133 /// This new lexical block will have the same location information as
00134 /// the previous one, but with a new DWARF discriminator value.
00135 ///
00136 /// One of the main uses of this discriminator value is in runtime
00137 /// sample profilers. It allows the profiler to distinguish instructions
00138 /// at location !dbg !10 that execute on different basic blocks. This is
00139 /// important because while the predicate 'if (x < 10)' may have been
00140 /// executed millions of times, the assignment 'x = i' may have only
00141 /// executed a handful of times (meaning that the entry->if.then edge is
00142 /// seldom taken).
00143 ///
00144 /// If we did not have discriminator information, the profiler would
00145 /// assign the same weight to both blocks 'entry' and 'if.then', which
00146 /// in turn will make it conclude that the entry->if.then edge is very
00147 /// hot.
00148 ///
00149 /// To decide where to create new discriminator values, this function
00150 /// traverses the CFG and examines instruction at basic block boundaries.
00151 /// If the last instruction I1 of a block B1 is at the same file and line
00152 /// location as instruction I2 of successor B2, then it creates a new
00153 /// lexical block for I2 and all the instruction in B2 that share the same
00154 /// file and line location as I2. This new lexical block will have a
00155 /// different discriminator number than I1.
00156 bool AddDiscriminators::runOnFunction(Function &F) {
00157   // If the function has debug information, but the user has disabled
00158   // discriminators, do nothing.
00159   // Simlarly, if the function has no debug info, do nothing.
00160   // Finally, if this module is built with dwarf versions earlier than 4,
00161   // do nothing (discriminator support is a DWARF 4 feature).
00162   if (NoDiscriminators ||
00163       !hasDebugInfo(F) ||
00164       F.getParent()->getDwarfVersion() < 4)
00165     return false;
00166 
00167   bool Changed = false;
00168   Module *M = F.getParent();
00169   LLVMContext &Ctx = M->getContext();
00170   DIBuilder Builder(*M);
00171 
00172   // Traverse all the blocks looking for instructions in different
00173   // blocks that are at the same file:line location.
00174   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
00175     BasicBlock *B = I;
00176     TerminatorInst *Last = B->getTerminator();
00177     DebugLoc LastLoc = Last->getDebugLoc();
00178     if (LastLoc.isUnknown()) continue;
00179     DILocation LastDIL(LastLoc.getAsMDNode(Ctx));
00180 
00181     for (unsigned I = 0; I < Last->getNumSuccessors(); ++I) {
00182       BasicBlock *Succ = Last->getSuccessor(I);
00183       Instruction *First = Succ->getFirstNonPHIOrDbgOrLifetime();
00184       DebugLoc FirstLoc = First->getDebugLoc();
00185       if (FirstLoc.isUnknown()) continue;
00186       DILocation FirstDIL(FirstLoc.getAsMDNode(Ctx));
00187 
00188       // If the first instruction (First) of Succ is at the same file
00189       // location as B's last instruction (Last), add a new
00190       // discriminator for First's location and all the instructions
00191       // in Succ that share the same location with First.
00192       if (FirstDIL.atSameLineAs(LastDIL)) {
00193         // Create a new lexical scope and compute a new discriminator
00194         // number for it.
00195         StringRef Filename = FirstDIL.getFilename();
00196         DIScope Scope = FirstDIL.getScope();
00197         DIFile File = Builder.createFile(Filename, Scope.getDirectory());
00198         unsigned Discriminator = FirstDIL.computeNewDiscriminator(Ctx);
00199         DILexicalBlockFile NewScope =
00200             Builder.createLexicalBlockFile(Scope, File, Discriminator);
00201         DILocation NewDIL = FirstDIL.copyWithNewScope(Ctx, NewScope);
00202         DebugLoc newDebugLoc = DebugLoc::getFromDILocation(NewDIL);
00203 
00204         // Attach this new debug location to First and every
00205         // instruction following First that shares the same location.
00206         for (BasicBlock::iterator I1(*First), E1 = Succ->end(); I1 != E1;
00207              ++I1) {
00208           if (I1->getDebugLoc() != FirstLoc) break;
00209           I1->setDebugLoc(newDebugLoc);
00210           DEBUG(dbgs() << NewDIL.getFilename() << ":" << NewDIL.getLineNumber()
00211                        << ":" << NewDIL.getColumnNumber() << ":"
00212                        << NewDIL.getDiscriminator() << *I1 << "\n");
00213         }
00214         DEBUG(dbgs() << "\n");
00215         Changed = true;
00216       }
00217     }
00218   }
00219   return Changed;
00220 }