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 
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/DenseSet.h"
57 #include "llvm/IR/BasicBlock.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DIBuilder.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/IR/Module.h"
65 #include "llvm/Pass.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Scalar.h"
70 
71 using namespace llvm;
72 
73 #define DEBUG_TYPE "add-discriminators"
74 
75 namespace {
76 struct AddDiscriminators : public FunctionPass {
77   static char ID; // Pass identification, replacement for typeid
78   AddDiscriminators() : FunctionPass(ID) {
79     initializeAddDiscriminatorsPass(*PassRegistry::getPassRegistry());
80   }
81 
82   bool runOnFunction(Function &F) override;
83 };
84 } // end anonymous namespace
85 
86 char AddDiscriminators::ID = 0;
87 INITIALIZE_PASS_BEGIN(AddDiscriminators, "add-discriminators",
88                       "Add DWARF path discriminators", false, false)
89 INITIALIZE_PASS_END(AddDiscriminators, "add-discriminators",
90                     "Add DWARF path discriminators", false, false)
91 
92 // Command line option to disable discriminator generation even in the
93 // presence of debug information. This is only needed when debugging
94 // debug info generation issues.
95 static cl::opt<bool> NoDiscriminators(
96     "no-discriminators", cl::init(false),
97     cl::desc("Disable generation of discriminator information."));
98 
99 FunctionPass *llvm::createAddDiscriminatorsPass() {
100   return new AddDiscriminators();
101 }
102 
103 /// \brief Assign DWARF discriminators.
104 ///
105 /// To assign discriminators, we examine the boundaries of every
106 /// basic block and its successors. Suppose there is a basic block B1
107 /// with successor B2. The last instruction I1 in B1 and the first
108 /// instruction I2 in B2 are located at the same file and line number.
109 /// This situation is illustrated in the following code snippet:
110 ///
111 ///       if (i < 10) x = i;
112 ///
113 ///     entry:
114 ///       br i1 %cmp, label %if.then, label %if.end, !dbg !10
115 ///     if.then:
116 ///       %1 = load i32* %i.addr, align 4, !dbg !10
117 ///       store i32 %1, i32* %x, align 4, !dbg !10
118 ///       br label %if.end, !dbg !10
119 ///     if.end:
120 ///       ret void, !dbg !12
121 ///
122 /// Notice how the branch instruction in block 'entry' and all the
123 /// instructions in block 'if.then' have the exact same debug location
124 /// information (!dbg !10).
125 ///
126 /// To distinguish instructions in block 'entry' from instructions in
127 /// block 'if.then', we generate a new lexical block for all the
128 /// instruction in block 'if.then' that share the same file and line
129 /// location with the last instruction of block 'entry'.
130 ///
131 /// This new lexical block will have the same location information as
132 /// the previous one, but with a new DWARF discriminator value.
133 ///
134 /// One of the main uses of this discriminator value is in runtime
135 /// sample profilers. It allows the profiler to distinguish instructions
136 /// at location !dbg !10 that execute on different basic blocks. This is
137 /// important because while the predicate 'if (x < 10)' may have been
138 /// executed millions of times, the assignment 'x = i' may have only
139 /// executed a handful of times (meaning that the entry->if.then edge is
140 /// seldom taken).
141 ///
142 /// If we did not have discriminator information, the profiler would
143 /// assign the same weight to both blocks 'entry' and 'if.then', which
144 /// in turn will make it conclude that the entry->if.then edge is very
145 /// hot.
146 ///
147 /// To decide where to create new discriminator values, this function
148 /// traverses the CFG and examines instruction at basic block boundaries.
149 /// If the last instruction I1 of a block B1 is at the same file and line
150 /// location as instruction I2 of successor B2, then it creates a new
151 /// lexical block for I2 and all the instruction in B2 that share the same
152 /// file and line location as I2. This new lexical block will have a
153 /// different discriminator number than I1.
154 bool AddDiscriminators::runOnFunction(Function &F) {
155   // If the function has debug information, but the user has disabled
156   // discriminators, do nothing.
157   // Simlarly, if the function has no debug info, do nothing.
158   // Finally, if this module is built with dwarf versions earlier than 4,
159   // do nothing (discriminator support is a DWARF 4 feature).
160   if (NoDiscriminators || !F.getSubprogram() ||
161       F.getParent()->getDwarfVersion() < 4)
162     return false;
163 
164   bool Changed = false;
165   Module *M = F.getParent();
166   LLVMContext &Ctx = M->getContext();
167   DIBuilder Builder(*M, /*AllowUnresolved*/ false);
168 
169   typedef std::pair<StringRef, unsigned> Location;
170   typedef DenseMap<const BasicBlock *, Metadata *> BBScopeMap;
171   typedef DenseMap<Location, BBScopeMap> LocationBBMap;
172   typedef DenseMap<Location, unsigned> LocationDiscriminatorMap;
173   typedef DenseSet<Location> LocationSet;
174 
175   LocationBBMap LBM;
176   LocationDiscriminatorMap LDM;
177 
178   // Traverse all instructions in the function. If the source line location
179   // of the instruction appears in other basic block, assign a new
180   // discriminator for this instruction.
181   for (BasicBlock &B : F) {
182     for (auto &I : B.getInstList()) {
183       if (isa<DbgInfoIntrinsic>(&I))
184         continue;
185       const DILocation *DIL = I.getDebugLoc();
186       if (!DIL)
187         continue;
188       Location L = std::make_pair(DIL->getFilename(), DIL->getLine());
189       auto &BBMap = LBM[L];
190       auto R = BBMap.insert(std::make_pair(&B, (Metadata *)nullptr));
191       if (BBMap.size() == 1)
192         continue;
193       bool InsertSuccess = R.second;
194       Metadata *&NewScope = R.first->second;
195       // If we could insert a different block in the same location, a
196       // discriminator is needed to distinguish both instructions.
197       if (InsertSuccess) {
198         auto *Scope = DIL->getScope();
199         auto *File =
200             Builder.createFile(DIL->getFilename(), Scope->getDirectory());
201         NewScope = Builder.createLexicalBlockFile(Scope, File, ++LDM[L]);
202       }
203       I.setDebugLoc(DILocation::get(Ctx, DIL->getLine(), DIL->getColumn(),
204                                     NewScope, DIL->getInlinedAt()));
205       DEBUG(dbgs() << DIL->getFilename() << ":" << DIL->getLine() << ":"
206                    << DIL->getColumn() << ":"
207                    << dyn_cast<DILexicalBlockFile>(NewScope)->getDiscriminator()
208                    << I << "\n");
209       Changed = true;
210     }
211   }
212 
213   // Traverse all instructions and assign new discriminators to call
214   // instructions with the same lineno that are in the same basic block.
215   // Sample base profile needs to distinguish different function calls within
216   // a same source line for correct profile annotation.
217   for (BasicBlock &B : F) {
218     LocationSet CallLocations;
219     for (auto &I : B.getInstList()) {
220       CallInst *Current = dyn_cast<CallInst>(&I);
221       if (!Current || isa<DbgInfoIntrinsic>(&I))
222         continue;
223 
224       DILocation *CurrentDIL = Current->getDebugLoc();
225       if (!CurrentDIL)
226         continue;
227       Location L =
228           std::make_pair(CurrentDIL->getFilename(), CurrentDIL->getLine());
229       if (!CallLocations.insert(L).second) {
230         auto *Scope = CurrentDIL->getScope();
231         auto *File = Builder.createFile(CurrentDIL->getFilename(),
232                                         Scope->getDirectory());
233         auto *NewScope = Builder.createLexicalBlockFile(Scope, File, ++LDM[L]);
234         Current->setDebugLoc(DILocation::get(Ctx, CurrentDIL->getLine(),
235                                              CurrentDIL->getColumn(), NewScope,
236                                              CurrentDIL->getInlinedAt()));
237         Changed = true;
238       }
239     }
240   }
241   return Changed;
242 }
243