Debian Codegraph @

flang/lib/Optimizer/Transforms/AddDebugInfo.cpp

raw
1 //===-------------- AddDebugInfo.cpp -- add debug info -------------------===//
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 //===----------------------------------------------------------------------===//
10 /// \file
11 /// This pass populates some debug information for the module and functions.
12 //===----------------------------------------------------------------------===//
13
14 #include "DebugTypeGenerator.h"
15 #include "flang/Common/Version.h"
16 #include "flang/Optimizer/Builder/FIRBuilder.h"
17 #include "flang/Optimizer/Builder/Todo.h"
18 #include "flang/Optimizer/CodeGen/CGOps.h"
19 #include "flang/Optimizer/Dialect/FIRDialect.h"
20 #include "flang/Optimizer/Dialect/FIROps.h"
21 #include "flang/Optimizer/Dialect/FIRType.h"
22 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
23 #include "flang/Optimizer/Support/InternalNames.h"
24 #include "flang/Optimizer/Transforms/Passes.h"
25 #include "mlir/Dialect/Func/IR/FuncOps.h"
26 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
27 #include "mlir/IR/Matchers.h"
28 #include "mlir/IR/TypeUtilities.h"
29 #include "mlir/Pass/Pass.h"
30 #include "mlir/Transforms/DialectConversion.h"
31 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
32 #include "mlir/Transforms/RegionUtils.h"
33 #include "llvm/BinaryFormat/Dwarf.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/raw_ostream.h"
38
39 namespace fir {
40 #define GEN_PASS_DEF_ADDDEBUGINFO
41 #include "flang/Optimizer/Transforms/Passes.h.inc"
42 } // namespace fir
43
44 #define DEBUG_TYPE "flang-add-debug-info"
45
46 namespace {
47
48 class AddDebugInfoPass : public fir::impl::AddDebugInfoBase<AddDebugInfoPass> {
49 void handleDeclareOp(fir::cg::XDeclareOp declOp,
50 mlir::LLVM::DIFileAttr fileAttr,
51 mlir::LLVM::DIScopeAttr scopeAttr,
52 fir::DebugTypeGenerator &typeGen,
53 mlir::SymbolTable *symbolTable);
54
55 public:
56 AddDebugInfoPass(fir::AddDebugInfoOptions options) : Base(options) {}
57 void runOnOperation() override;
58
59 private:
60 llvm::StringMap<mlir::LLVM::DIModuleAttr> moduleMap;
61
62 mlir::LLVM::DIModuleAttr getOrCreateModuleAttr(
63 const std::string &name, mlir::LLVM::DIFileAttr fileAttr,
64 mlir::LLVM::DIScopeAttr scope, unsigned line, bool decl);
65
66 void handleGlobalOp(fir::GlobalOp glocalOp, mlir::LLVM::DIFileAttr fileAttr,
67 mlir::LLVM::DIScopeAttr scope,
68 mlir::SymbolTable *symbolTable);
69 void handleFuncOp(mlir::func::FuncOp funcOp, mlir::LLVM::DIFileAttr fileAttr,
70 mlir::LLVM::DICompileUnitAttr cuAttr,
71 mlir::SymbolTable *symbolTable);
72 };
73
74 static uint32_t getLineFromLoc(mlir::Location loc) {
75 uint32_t line = 1;
76 if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(loc))
77 line = fileLoc.getLine();
78 return line;
79 }
80
81 bool debugInfoIsAlreadySet(mlir::Location loc) {
82 if (mlir::isa<mlir::FusedLoc>(loc))
83 return true;
84 return false;
85 }
86
87 } // namespace
88
89 void AddDebugInfoPass::handleDeclareOp(fir::cg::XDeclareOp declOp,
90 mlir::LLVM::DIFileAttr fileAttr,
91 mlir::LLVM::DIScopeAttr scopeAttr,
92 fir::DebugTypeGenerator &typeGen,
93 mlir::SymbolTable *symbolTable) {
94 mlir::MLIRContext *context = &getContext();
95 mlir::OpBuilder builder(context);
96 auto result = fir::NameUniquer::deconstruct(declOp.getUniqName());
97
98 if (result.first != fir::NameUniquer::NameKind::VARIABLE)
99 return;
100
101 // If this DeclareOp actually represents a global then treat it as such.
102 if (auto global = symbolTable->lookup<fir::GlobalOp>(declOp.getUniqName())) {
103 handleGlobalOp(global, fileAttr, scopeAttr, symbolTable);
104 return;
105 }
106
107 // Only accept local variables.
108 if (result.second.procs.empty())
109 return;
110
111 // FIXME: There may be cases where an argument is processed a bit before
112 // DeclareOp is generated. In that case, DeclareOp may point to an
113 // intermediate op and not to BlockArgument.
114 // Moreover, with MLIR inlining we cannot use the BlockArgument
115 // position to identify the original number of the dummy argument.
116 // If we want to keep running AddDebugInfoPass late, the dummy argument
117 // position in the argument list has to be expressed in FIR (e.g. as a
118 // constant attribute of [hl]fir.declare/fircg.ext_declare operation that has
119 // a dummy_scope operand).
120 unsigned argNo = 0;
121 if (fir::isDummyArgument(declOp.getMemref())) {
122 auto arg = llvm::cast<mlir::BlockArgument>(declOp.getMemref());
123 argNo = arg.getArgNumber() + 1;
124 }
125
126 auto tyAttr = typeGen.convertType(fir::unwrapRefType(declOp.getType()),
127 fileAttr, scopeAttr, declOp.getLoc());
128
129 auto localVarAttr = mlir::LLVM::DILocalVariableAttr::get(
130 context, scopeAttr, mlir::StringAttr::get(context, result.second.name),
131 fileAttr, getLineFromLoc(declOp.getLoc()), argNo, /* alignInBits*/ 0,
132 tyAttr);
133 declOp->setLoc(builder.getFusedLoc({declOp->getLoc()}, localVarAttr));
134 }
135
136 // The `module` does not have a first class representation in the `FIR`. We
137 // extract information about it from the name of the identifiers and keep a
138 // map to avoid duplication.
139 mlir::LLVM::DIModuleAttr AddDebugInfoPass::getOrCreateModuleAttr(
140 const std::string &name, mlir::LLVM::DIFileAttr fileAttr,
141 mlir::LLVM::DIScopeAttr scope, unsigned line, bool decl) {
142 mlir::MLIRContext *context = &getContext();
143 mlir::LLVM::DIModuleAttr modAttr;
144 if (auto iter{moduleMap.find(name)}; iter != moduleMap.end()) {
145 modAttr = iter->getValue();
146 } else {
147 modAttr = mlir::LLVM::DIModuleAttr::get(
148 context, fileAttr, scope, mlir::StringAttr::get(context, name),
149 /* configMacros */ mlir::StringAttr(),
150 /* includePath */ mlir::StringAttr(),
151 /* apinotes */ mlir::StringAttr(), line, decl);
152 moduleMap[name] = modAttr;
153 }
154 return modAttr;
155 }
156
157 void AddDebugInfoPass::handleGlobalOp(fir::GlobalOp globalOp,
158 mlir::LLVM::DIFileAttr fileAttr,
159 mlir::LLVM::DIScopeAttr scope,
160 mlir::SymbolTable *symbolTable) {
161 if (debugInfoIsAlreadySet(globalOp.getLoc()))
162 return;
163 mlir::ModuleOp module = getOperation();
164 mlir::MLIRContext *context = &getContext();
165 fir::DebugTypeGenerator typeGen(module);
166 mlir::OpBuilder builder(context);
167
168 std::pair result = fir::NameUniquer::deconstruct(globalOp.getSymName());
169 if (result.first != fir::NameUniquer::NameKind::VARIABLE)
170 return;
171
172 unsigned line = getLineFromLoc(globalOp.getLoc());
173
174 // DWARF5 says following about the fortran modules:
175 // A Fortran 90 module may also be represented by a module entry
176 // (but no declaration attribute is warranted because Fortran has no concept
177 // of a corresponding module body).
178 // But in practice, compilers use declaration attribute with a module in cases
179 // where module was defined in another source file (only being used in this
180 // one). The isInitialized() seems to provide the right information
181 // but inverted. It is true where module is actually defined but false where
182 // it is used.
183 // FIXME: Currently we don't have the line number on which a module was
184 // declared. We are using a best guess of line - 1 where line is the source
185 // line of the first member of the module that we encounter.
186
187 if (result.second.procs.empty()) {
188 // Only look for module if this variable is not part of a function.
189 if (result.second.modules.empty())
190 return;
191
192 // Modules are generated at compile unit scope
193 if (mlir::LLVM::DISubprogramAttr sp =
194 mlir::dyn_cast_if_present<mlir::LLVM::DISubprogramAttr>(scope))
195 scope = sp.getCompileUnit();
196
197 scope = getOrCreateModuleAttr(result.second.modules[0], fileAttr, scope,
198 line - 1, !globalOp.isInitialized());
199 }
200 mlir::LLVM::DITypeAttr diType = typeGen.convertType(
201 globalOp.getType(), fileAttr, scope, globalOp.getLoc());
202 auto gvAttr = mlir::LLVM::DIGlobalVariableAttr::get(
203 context, scope, mlir::StringAttr::get(context, result.second.name),
204 mlir::StringAttr::get(context, globalOp.getName()), fileAttr, line,
205 diType, /*isLocalToUnit*/ false,
206 /*isDefinition*/ globalOp.isInitialized(), /* alignInBits*/ 0);
207 globalOp->setLoc(builder.getFusedLoc({globalOp->getLoc()}, gvAttr));
208 }
209
210 void AddDebugInfoPass::handleFuncOp(mlir::func::FuncOp funcOp,
211 mlir::LLVM::DIFileAttr fileAttr,
212 mlir::LLVM::DICompileUnitAttr cuAttr,
213 mlir::SymbolTable *symbolTable) {
214 mlir::Location l = funcOp->getLoc();
215 // If fused location has already been created then nothing to do
216 // Otherwise, create a fused location.
217 if (debugInfoIsAlreadySet(l))
218 return;
219
220 mlir::ModuleOp module = getOperation();
221 mlir::MLIRContext *context = &getContext();
222 mlir::OpBuilder builder(context);
223 llvm::StringRef fileName(fileAttr.getName());
224 llvm::StringRef filePath(fileAttr.getDirectory());
225 unsigned int CC = (funcOp.getName() == fir::NameUniquer::doProgramEntry())
226 ? llvm::dwarf::getCallingConvention("DW_CC_program")
227 : llvm::dwarf::getCallingConvention("DW_CC_normal");
228
229 if (auto funcLoc = mlir::dyn_cast<mlir::FileLineColLoc>(l)) {
230 fileName = llvm::sys::path::filename(funcLoc.getFilename().getValue());
231 filePath = llvm::sys::path::parent_path(funcLoc.getFilename().getValue());
232 }
233
234 mlir::StringAttr fullName = mlir::StringAttr::get(context, funcOp.getName());
235 mlir::Attribute attr = funcOp->getAttr(fir::getInternalFuncNameAttrName());
236 mlir::StringAttr funcName =
237 (attr) ? mlir::cast<mlir::StringAttr>(attr)
238 : mlir::StringAttr::get(context, funcOp.getName());
239
240 auto result = fir::NameUniquer::deconstruct(funcName);
241 funcName = mlir::StringAttr::get(context, result.second.name);
242
243 llvm::SmallVector<mlir::LLVM::DITypeAttr> types;
244 fir::DebugTypeGenerator typeGen(module);
245 for (auto resTy : funcOp.getResultTypes()) {
246 auto tyAttr = typeGen.convertType(resTy, fileAttr, cuAttr, funcOp.getLoc());
247 types.push_back(tyAttr);
248 }
249 for (auto inTy : funcOp.getArgumentTypes()) {
250 auto tyAttr = typeGen.convertType(fir::unwrapRefType(inTy), fileAttr,
251 cuAttr, funcOp.getLoc());
252 types.push_back(tyAttr);
253 }
254
255 mlir::LLVM::DISubroutineTypeAttr subTypeAttr =
256 mlir::LLVM::DISubroutineTypeAttr::get(context, CC, types);
257 mlir::LLVM::DIFileAttr funcFileAttr =
258 mlir::LLVM::DIFileAttr::get(context, fileName, filePath);
259
260 // Only definitions need a distinct identifier and a compilation unit.
261 mlir::DistinctAttr id;
262 mlir::LLVM::DIScopeAttr Scope = fileAttr;
263 mlir::LLVM::DICompileUnitAttr compilationUnit;
264 mlir::LLVM::DISubprogramFlags subprogramFlags =
265 mlir::LLVM::DISubprogramFlags{};
266 if (isOptimized)
267 subprogramFlags = mlir::LLVM::DISubprogramFlags::Optimized;
268 if (!funcOp.isExternal()) {
269 id = mlir::DistinctAttr::create(mlir::UnitAttr::get(context));
270 compilationUnit = cuAttr;
271 subprogramFlags =
272 subprogramFlags | mlir::LLVM::DISubprogramFlags::Definition;
273 }
274 unsigned line = getLineFromLoc(l);
275 if (fir::isInternalProcedure(funcOp)) {
276 // For contained functions, the scope is the parent subroutine.
277 mlir::SymbolRefAttr sym = mlir::cast<mlir::SymbolRefAttr>(
278 funcOp->getAttr(fir::getHostSymbolAttrName()));
279 if (sym) {
280 if (auto func =
281 symbolTable->lookup<mlir::func::FuncOp>(sym.getLeafReference())) {
282 // Make sure that parent is processed.
283 handleFuncOp(func, fileAttr, cuAttr, symbolTable);
284 if (auto fusedLoc =
285 mlir::dyn_cast_if_present<mlir::FusedLoc>(func.getLoc())) {
286 if (auto spAttr =
287 mlir::dyn_cast_if_present<mlir::LLVM::DISubprogramAttr>(
288 fusedLoc.getMetadata()))
289 Scope = spAttr;
290 }
291 }
292 }
293 } else if (!result.second.modules.empty()) {
294 Scope = getOrCreateModuleAttr(result.second.modules[0], fileAttr, cuAttr,
295 line - 1, false);
296 }
297
298 auto spAttr = mlir::LLVM::DISubprogramAttr::get(
299 context, id, compilationUnit, Scope, funcName, fullName, funcFileAttr,
300 line, line, subprogramFlags, subTypeAttr);
301 funcOp->setLoc(builder.getFusedLoc({funcOp->getLoc()}, spAttr));
302
303 // Don't process variables if user asked for line tables only.
304 if (debugLevel == mlir::LLVM::DIEmissionKind::LineTablesOnly)
305 return;
306
307 funcOp.walk([&](fir::cg::XDeclareOp declOp) {
308 handleDeclareOp(declOp, fileAttr, spAttr, typeGen, symbolTable);
309 });
310 }
311
312 void AddDebugInfoPass::runOnOperation() {
313 mlir::ModuleOp module = getOperation();
314 mlir::MLIRContext *context = &getContext();
315 mlir::SymbolTable symbolTable(module);
316 llvm::StringRef fileName;
317 std::string filePath;
318 // We need 2 type of file paths here.
319 // 1. Name of the file as was presented to compiler. This can be absolute
320 // or relative to 2.
321 // 2. Current working directory
322 //
323 // We are also dealing with 2 different situations below. One is normal
324 // compilation where we will have a value in 'inputFilename' and we can
325 // obtain the current directory using 'current_path'.
326 // The 2nd case is when this pass is invoked directly from 'fir-opt' tool.
327 // In that case, 'inputFilename' may be empty. Location embedded in the
328 // module will be used to get file name and its directory.
329 if (inputFilename.empty()) {
330 if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(module.getLoc())) {
331 fileName = llvm::sys::path::filename(fileLoc.getFilename().getValue());
332 filePath = llvm::sys::path::parent_path(fileLoc.getFilename().getValue());
333 } else
334 fileName = "-";
335 } else {
336 fileName = inputFilename;
337 llvm::SmallString<256> cwd;
338 if (!llvm::sys::fs::current_path(cwd))
339 filePath = cwd.str();
340 }
341
342 mlir::LLVM::DIFileAttr fileAttr =
343 mlir::LLVM::DIFileAttr::get(context, fileName, filePath);
344 mlir::StringAttr producer =
345 mlir::StringAttr::get(context, Fortran::common::getFlangFullVersion());
346 mlir::LLVM::DICompileUnitAttr cuAttr = mlir::LLVM::DICompileUnitAttr::get(
347 mlir::DistinctAttr::create(mlir::UnitAttr::get(context)),
348 llvm::dwarf::getLanguage("DW_LANG_Fortran95"), fileAttr, producer,
349 isOptimized, debugLevel);
350
351 module.walk([&](mlir::func::FuncOp funcOp) {
352 handleFuncOp(funcOp, fileAttr, cuAttr, &symbolTable);
353 });
354 // Process any global which was not processed through DeclareOp.
355 if (debugLevel == mlir::LLVM::DIEmissionKind::Full) {
356 // Process 'GlobalOp' only if full debug info is requested.
357 for (auto globalOp : module.getOps<fir::GlobalOp>())
358 handleGlobalOp(globalOp, fileAttr, cuAttr, &symbolTable);
359 }
360 }
361
362 std::unique_ptr<mlir::Pass>
363 fir::createAddDebugInfoPass(fir::AddDebugInfoOptions options) {
364 return std::make_unique<AddDebugInfoPass>(options);
365 }