xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/Utils/AddDiscriminators.cpp (revision f126890ac5386406dadf7c4cfa9566cbb56537c5)
1 //===- AddDiscriminators.cpp - Insert DWARF path discriminators -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file adds DWARF discriminators to the IR. Path discriminators are
10 // used to decide what CFG path was taken inside sub-graphs whose instructions
11 // share the same line and column number information.
12 //
13 // The main user of this is the sample profiler. Instruction samples are
14 // mapped to line number information. Since a single line may be spread
15 // out over several basic blocks, discriminators add more precise location
16 // for the samples.
17 //
18 // For example,
19 //
20 //   1  #define ASSERT(P)
21 //   2      if (!(P))
22 //   3        abort()
23 //   ...
24 //   100   while (true) {
25 //   101     ASSERT (sum < 0);
26 //   102     ...
27 //   130   }
28 //
29 // when converted to IR, this snippet looks something like:
30 //
31 // while.body:                                       ; preds = %entry, %if.end
32 //   %0 = load i32* %sum, align 4, !dbg !15
33 //   %cmp = icmp slt i32 %0, 0, !dbg !15
34 //   br i1 %cmp, label %if.end, label %if.then, !dbg !15
35 //
36 // if.then:                                          ; preds = %while.body
37 //   call void @abort(), !dbg !15
38 //   br label %if.end, !dbg !15
39 //
40 // Notice that all the instructions in blocks 'while.body' and 'if.then'
41 // have exactly the same debug information. When this program is sampled
42 // at runtime, the profiler will assume that all these instructions are
43 // equally frequent. This, in turn, will consider the edge while.body->if.then
44 // to be frequently taken (which is incorrect).
45 //
46 // By adding a discriminator value to the instructions in block 'if.then',
47 // we can distinguish instructions at line 101 with discriminator 0 from
48 // the instructions at line 101 with discriminator 1.
49 //
50 // For more details about DWARF discriminators, please visit
51 // http://wiki.dwarfstd.org/index.php?title=Path_Discriminators
52 //
53 //===----------------------------------------------------------------------===//
54 
55 #include "llvm/Transforms/Utils/AddDiscriminators.h"
56 #include "llvm/ADT/DenseMap.h"
57 #include "llvm/ADT/DenseSet.h"
58 #include "llvm/ADT/StringRef.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/DebugInfoMetadata.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/PassManager.h"
66 #include "llvm/InitializePasses.h"
67 #include "llvm/Pass.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Transforms/Utils.h"
73 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
74 #include <utility>
75 
76 using namespace llvm;
77 using namespace sampleprofutil;
78 
79 #define DEBUG_TYPE "add-discriminators"
80 
81 // Command line option to disable discriminator generation even in the
82 // presence of debug information. This is only needed when debugging
83 // debug info generation issues.
84 static cl::opt<bool> NoDiscriminators(
85     "no-discriminators", cl::init(false),
86     cl::desc("Disable generation of discriminator information."));
87 
88 static bool shouldHaveDiscriminator(const Instruction *I) {
89   return !isa<IntrinsicInst>(I) || isa<MemIntrinsic>(I);
90 }
91 
92 /// Assign DWARF discriminators.
93 ///
94 /// To assign discriminators, we examine the boundaries of every
95 /// basic block and its successors. Suppose there is a basic block B1
96 /// with successor B2. The last instruction I1 in B1 and the first
97 /// instruction I2 in B2 are located at the same file and line number.
98 /// This situation is illustrated in the following code snippet:
99 ///
100 ///       if (i < 10) x = i;
101 ///
102 ///     entry:
103 ///       br i1 %cmp, label %if.then, label %if.end, !dbg !10
104 ///     if.then:
105 ///       %1 = load i32* %i.addr, align 4, !dbg !10
106 ///       store i32 %1, i32* %x, align 4, !dbg !10
107 ///       br label %if.end, !dbg !10
108 ///     if.end:
109 ///       ret void, !dbg !12
110 ///
111 /// Notice how the branch instruction in block 'entry' and all the
112 /// instructions in block 'if.then' have the exact same debug location
113 /// information (!dbg !10).
114 ///
115 /// To distinguish instructions in block 'entry' from instructions in
116 /// block 'if.then', we generate a new lexical block for all the
117 /// instruction in block 'if.then' that share the same file and line
118 /// location with the last instruction of block 'entry'.
119 ///
120 /// This new lexical block will have the same location information as
121 /// the previous one, but with a new DWARF discriminator value.
122 ///
123 /// One of the main uses of this discriminator value is in runtime
124 /// sample profilers. It allows the profiler to distinguish instructions
125 /// at location !dbg !10 that execute on different basic blocks. This is
126 /// important because while the predicate 'if (x < 10)' may have been
127 /// executed millions of times, the assignment 'x = i' may have only
128 /// executed a handful of times (meaning that the entry->if.then edge is
129 /// seldom taken).
130 ///
131 /// If we did not have discriminator information, the profiler would
132 /// assign the same weight to both blocks 'entry' and 'if.then', which
133 /// in turn will make it conclude that the entry->if.then edge is very
134 /// hot.
135 ///
136 /// To decide where to create new discriminator values, this function
137 /// traverses the CFG and examines instruction at basic block boundaries.
138 /// If the last instruction I1 of a block B1 is at the same file and line
139 /// location as instruction I2 of successor B2, then it creates a new
140 /// lexical block for I2 and all the instruction in B2 that share the same
141 /// file and line location as I2. This new lexical block will have a
142 /// different discriminator number than I1.
143 static bool addDiscriminators(Function &F) {
144   // If the function has debug information, but the user has disabled
145   // discriminators, do nothing.
146   // Simlarly, if the function has no debug info, do nothing.
147   if (NoDiscriminators || !F.getSubprogram())
148     return false;
149 
150   // Create FSDiscriminatorVariable if flow sensitive discriminators are used.
151   if (EnableFSDiscriminator)
152     createFSDiscriminatorVariable(F.getParent());
153 
154   bool Changed = false;
155 
156   using Location = std::pair<StringRef, unsigned>;
157   using BBSet = DenseSet<const BasicBlock *>;
158   using LocationBBMap = DenseMap<Location, BBSet>;
159   using LocationDiscriminatorMap = DenseMap<Location, unsigned>;
160   using LocationSet = DenseSet<Location>;
161 
162   LocationBBMap LBM;
163   LocationDiscriminatorMap LDM;
164 
165   // Traverse all instructions in the function. If the source line location
166   // of the instruction appears in other basic block, assign a new
167   // discriminator for this instruction.
168   for (BasicBlock &B : F) {
169     for (auto &I : B) {
170       // Not all intrinsic calls should have a discriminator.
171       // We want to avoid a non-deterministic assignment of discriminators at
172       // different debug levels. We still allow discriminators on memory
173       // intrinsic calls because those can be early expanded by SROA into
174       // pairs of loads and stores, and the expanded load/store instructions
175       // should have a valid discriminator.
176       if (!shouldHaveDiscriminator(&I))
177         continue;
178       const DILocation *DIL = I.getDebugLoc();
179       if (!DIL)
180         continue;
181       Location L = std::make_pair(DIL->getFilename(), DIL->getLine());
182       auto &BBMap = LBM[L];
183       auto R = BBMap.insert(&B);
184       if (BBMap.size() == 1)
185         continue;
186       // If we could insert more than one block with the same line+file, a
187       // discriminator is needed to distinguish both instructions.
188       // Only the lowest 7 bits are used to represent a discriminator to fit
189       // it in 1 byte ULEB128 representation.
190       unsigned Discriminator = R.second ? ++LDM[L] : LDM[L];
191       auto NewDIL = DIL->cloneWithBaseDiscriminator(Discriminator);
192       if (!NewDIL) {
193         LLVM_DEBUG(dbgs() << "Could not encode discriminator: "
194                           << DIL->getFilename() << ":" << DIL->getLine() << ":"
195                           << DIL->getColumn() << ":" << Discriminator << " "
196                           << I << "\n");
197       } else {
198         I.setDebugLoc(*NewDIL);
199         LLVM_DEBUG(dbgs() << DIL->getFilename() << ":" << DIL->getLine() << ":"
200                    << DIL->getColumn() << ":" << Discriminator << " " << I
201                    << "\n");
202       }
203       Changed = true;
204     }
205   }
206 
207   // Traverse all instructions and assign new discriminators to call
208   // instructions with the same lineno that are in the same basic block.
209   // Sample base profile needs to distinguish different function calls within
210   // a same source line for correct profile annotation.
211   for (BasicBlock &B : F) {
212     LocationSet CallLocations;
213     for (auto &I : B) {
214       // We bypass intrinsic calls for the following two reasons:
215       //  1) We want to avoid a non-deterministic assignment of
216       //     discriminators.
217       //  2) We want to minimize the number of base discriminators used.
218       if (!isa<InvokeInst>(I) && (!isa<CallInst>(I) || isa<IntrinsicInst>(I)))
219         continue;
220 
221       DILocation *CurrentDIL = I.getDebugLoc();
222       if (!CurrentDIL)
223         continue;
224       Location L =
225           std::make_pair(CurrentDIL->getFilename(), CurrentDIL->getLine());
226       if (!CallLocations.insert(L).second) {
227         unsigned Discriminator = ++LDM[L];
228         auto NewDIL = CurrentDIL->cloneWithBaseDiscriminator(Discriminator);
229         if (!NewDIL) {
230           LLVM_DEBUG(dbgs()
231                      << "Could not encode discriminator: "
232                      << CurrentDIL->getFilename() << ":"
233                      << CurrentDIL->getLine() << ":" << CurrentDIL->getColumn()
234                      << ":" << Discriminator << " " << I << "\n");
235         } else {
236           I.setDebugLoc(*NewDIL);
237           Changed = true;
238         }
239       }
240     }
241   }
242   return Changed;
243 }
244 
245 PreservedAnalyses AddDiscriminatorsPass::run(Function &F,
246                                              FunctionAnalysisManager &AM) {
247   if (!addDiscriminators(F))
248     return PreservedAnalyses::all();
249 
250   // FIXME: should be all()
251   return PreservedAnalyses::none();
252 }
253