LLVM  4.0.0
AddDiscriminators.cpp
Go to the documentation of this file.
1 //===- AddDiscriminators.cpp - Insert DWARF path discriminators -----------===//
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 file adds DWARF discriminators to the IR. Path discriminators are
11 // used to decide what CFG path was taken inside sub-graphs whose instructions
12 // share the same line and column number information.
13 //
14 // The main user of this is the sample profiler. Instruction samples are
15 // mapped to line number information. Since a single line may be spread
16 // out over several basic blocks, discriminators add more precise location
17 // for the samples.
18 //
19 // For example,
20 //
21 // 1 #define ASSERT(P)
22 // 2 if (!(P))
23 // 3 abort()
24 // ...
25 // 100 while (true) {
26 // 101 ASSERT (sum < 0);
27 // 102 ...
28 // 130 }
29 //
30 // when converted to IR, this snippet looks something like:
31 //
32 // while.body: ; preds = %entry, %if.end
33 // %0 = load i32* %sum, align 4, !dbg !15
34 // %cmp = icmp slt i32 %0, 0, !dbg !15
35 // br i1 %cmp, label %if.end, label %if.then, !dbg !15
36 //
37 // if.then: ; preds = %while.body
38 // call void @abort(), !dbg !15
39 // br label %if.end, !dbg !15
40 //
41 // Notice that all the instructions in blocks 'while.body' and 'if.then'
42 // have exactly the same debug information. When this program is sampled
43 // at runtime, the profiler will assume that all these instructions are
44 // equally frequent. This, in turn, will consider the edge while.body->if.then
45 // to be frequently taken (which is incorrect).
46 //
47 // By adding a discriminator value to the instructions in block 'if.then',
48 // we can distinguish instructions at line 101 with discriminator 0 from
49 // the instructions at line 101 with discriminator 1.
50 //
51 // For more details about DWARF discriminators, please visit
52 // http://wiki.dwarfstd.org/index.php?title=Path_Discriminators
53 //===----------------------------------------------------------------------===//
54 
56 #include "llvm/ADT/DenseMap.h"
57 #include "llvm/ADT/DenseSet.h"
58 #include "llvm/IR/BasicBlock.h"
59 #include "llvm/IR/Constants.h"
60 #include "llvm/IR/DebugInfo.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/Pass.h"
66 #include "llvm/Support/Debug.h"
68 #include "llvm/Transforms/Scalar.h"
69 
70 using namespace llvm;
71 
72 #define DEBUG_TYPE "add-discriminators"
73 
74 namespace {
75 // The legacy pass of AddDiscriminators.
76 struct AddDiscriminatorsLegacyPass : public FunctionPass {
77  static char ID; // Pass identification, replacement for typeid
78  AddDiscriminatorsLegacyPass() : FunctionPass(ID) {
80  }
81 
82  bool runOnFunction(Function &F) override;
83 };
84 
85 } // end anonymous namespace
86 
88 INITIALIZE_PASS_BEGIN(AddDiscriminatorsLegacyPass, "add-discriminators",
89  "Add DWARF path discriminators", false, false)
90 INITIALIZE_PASS_END(AddDiscriminatorsLegacyPass, "add-discriminators",
91  "Add DWARF path discriminators", false, false)
92 
93 // Command line option to disable discriminator generation even in the
94 // presence of debug information. This is only needed when debugging
95 // debug info generation issues.
96 static cl::opt<bool> NoDiscriminators(
97  "no-discriminators", cl::init(false),
98  cl::desc("Disable generation of discriminator information."));
99 
100 // Create the legacy AddDiscriminatorsPass.
102  return new AddDiscriminatorsLegacyPass();
103 }
104 
105 /// \brief Assign DWARF discriminators.
106 ///
107 /// To assign discriminators, we examine the boundaries of every
108 /// basic block and its successors. Suppose there is a basic block B1
109 /// with successor B2. The last instruction I1 in B1 and the first
110 /// instruction I2 in B2 are located at the same file and line number.
111 /// This situation is illustrated in the following code snippet:
112 ///
113 /// if (i < 10) x = i;
114 ///
115 /// entry:
116 /// br i1 %cmp, label %if.then, label %if.end, !dbg !10
117 /// if.then:
118 /// %1 = load i32* %i.addr, align 4, !dbg !10
119 /// store i32 %1, i32* %x, align 4, !dbg !10
120 /// br label %if.end, !dbg !10
121 /// if.end:
122 /// ret void, !dbg !12
123 ///
124 /// Notice how the branch instruction in block 'entry' and all the
125 /// instructions in block 'if.then' have the exact same debug location
126 /// information (!dbg !10).
127 ///
128 /// To distinguish instructions in block 'entry' from instructions in
129 /// block 'if.then', we generate a new lexical block for all the
130 /// instruction in block 'if.then' that share the same file and line
131 /// location with the last instruction of block 'entry'.
132 ///
133 /// This new lexical block will have the same location information as
134 /// the previous one, but with a new DWARF discriminator value.
135 ///
136 /// One of the main uses of this discriminator value is in runtime
137 /// sample profilers. It allows the profiler to distinguish instructions
138 /// at location !dbg !10 that execute on different basic blocks. This is
139 /// important because while the predicate 'if (x < 10)' may have been
140 /// executed millions of times, the assignment 'x = i' may have only
141 /// executed a handful of times (meaning that the entry->if.then edge is
142 /// seldom taken).
143 ///
144 /// If we did not have discriminator information, the profiler would
145 /// assign the same weight to both blocks 'entry' and 'if.then', which
146 /// in turn will make it conclude that the entry->if.then edge is very
147 /// hot.
148 ///
149 /// To decide where to create new discriminator values, this function
150 /// traverses the CFG and examines instruction at basic block boundaries.
151 /// If the last instruction I1 of a block B1 is at the same file and line
152 /// location as instruction I2 of successor B2, then it creates a new
153 /// lexical block for I2 and all the instruction in B2 that share the same
154 /// file and line location as I2. This new lexical block will have a
155 /// different discriminator number than I1.
156 static bool addDiscriminators(Function &F) {
157  // If the function has debug information, but the user has disabled
158  // discriminators, do nothing.
159  // Simlarly, if the function has no debug info, do nothing.
160  if (NoDiscriminators || !F.getSubprogram())
161  return false;
162 
163  bool Changed = false;
164 
165  typedef std::pair<StringRef, unsigned> Location;
166  typedef DenseSet<const BasicBlock *> BBSet;
167  typedef DenseMap<Location, BBSet> LocationBBMap;
168  typedef DenseMap<Location, unsigned> LocationDiscriminatorMap;
169  typedef DenseSet<Location> LocationSet;
170 
171  LocationBBMap LBM;
172  LocationDiscriminatorMap LDM;
173 
174  // Traverse all instructions in the function. If the source line location
175  // of the instruction appears in other basic block, assign a new
176  // discriminator for this instruction.
177  for (BasicBlock &B : F) {
178  for (auto &I : B.getInstList()) {
179  if (isa<IntrinsicInst>(&I))
180  continue;
181  const DILocation *DIL = I.getDebugLoc();
182  if (!DIL)
183  continue;
184  Location L = std::make_pair(DIL->getFilename(), DIL->getLine());
185  auto &BBMap = LBM[L];
186  auto R = BBMap.insert(&B);
187  if (BBMap.size() == 1)
188  continue;
189  // If we could insert more than one block with the same line+file, a
190  // discriminator is needed to distinguish both instructions.
191  // Only the lowest 7 bits are used to represent a discriminator to fit
192  // it in 1 byte ULEB128 representation.
193  unsigned Discriminator = (R.second ? ++LDM[L] : LDM[L]) & 0x7f;
194  I.setDebugLoc(DIL->cloneWithDiscriminator(Discriminator));
195  DEBUG(dbgs() << DIL->getFilename() << ":" << DIL->getLine() << ":"
196  << DIL->getColumn() << ":" << Discriminator << " " << I
197  << "\n");
198  Changed = true;
199  }
200  }
201 
202  // Traverse all instructions and assign new discriminators to call
203  // instructions with the same lineno that are in the same basic block.
204  // Sample base profile needs to distinguish different function calls within
205  // a same source line for correct profile annotation.
206  for (BasicBlock &B : F) {
207  LocationSet CallLocations;
208  for (auto &I : B.getInstList()) {
209  CallInst *Current = dyn_cast<CallInst>(&I);
210  if (!Current || isa<IntrinsicInst>(&I))
211  continue;
212 
213  DILocation *CurrentDIL = Current->getDebugLoc();
214  if (!CurrentDIL)
215  continue;
216  Location L =
217  std::make_pair(CurrentDIL->getFilename(), CurrentDIL->getLine());
218  if (!CallLocations.insert(L).second) {
219  Current->setDebugLoc(
220  CurrentDIL->cloneWithDiscriminator((++LDM[L]) & 0x7f));
221  Changed = true;
222  }
223  }
224  }
225  return Changed;
226 }
227 
228 bool AddDiscriminatorsLegacyPass::runOnFunction(Function &F) {
229  return addDiscriminators(F);
230 }
233  if (!addDiscriminators(F))
234  return PreservedAnalyses::all();
235 
236  // FIXME: should be all()
237  return PreservedAnalyses::none();
238 }
MachineLoop * L
add Add DWARF path false
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Implements a dense probed hash-table based set.
Definition: DenseSet.h:202
This class represents a function call, abstracting a target machine's calling convention.
void initializeAddDiscriminatorsLegacyPassPass(PassRegistry &)
DILocation * cloneWithDiscriminator(unsigned Discriminator) const
Returns a new DILocation with updated Discriminator.
#define F(x, y, z)
Definition: MD5.cpp:51
static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y, unsigned len)
This function adds the integer array x to the integer array Y and places the result in dest...
Definition: APInt.cpp:239
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
Optimize for code generation
Debug location.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:110
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:107
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:256
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:259
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:113
static bool addDiscriminators(Function &F)
Assign DWARF discriminators.
add Add DWARF path static false cl::opt< bool > NoDiscriminators("no-discriminators", cl::init(false), cl::desc("Disable generation of discriminator information."))
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1458
INITIALIZE_PASS_BEGIN(AddDiscriminatorsLegacyPass,"add-discriminators","Add DWARF path discriminators", false, false) INITIALIZE_PASS_END(AddDiscriminatorsLegacyPass
#define I(x, y, z)
Definition: MD5.cpp:54
add discriminators
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:287
FunctionPass * createAddDiscriminatorsPass()
#define DEBUG(X)
Definition: Debug.h:100
A container for analyses that lazily runs them and caches their results.