xref: /llvm-project/flang/lib/Optimizer/Transforms/AddDebugInfo.cpp (revision 6cd86d0fae8cbb752a713860f131b9b759b2cbb8)
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 
54 public:
55   AddDebugInfoPass(fir::AddDebugInfoOptions options) : Base(options) {}
56   void runOnOperation() override;
57 
58 private:
59   llvm::StringMap<mlir::LLVM::DIModuleAttr> moduleMap;
60 
61   mlir::LLVM::DIModuleAttr getOrCreateModuleAttr(
62       const std::string &name, mlir::LLVM::DIFileAttr fileAttr,
63       mlir::LLVM::DIScopeAttr scope, unsigned line, bool decl);
64 
65   void handleGlobalOp(fir::GlobalOp glocalOp, mlir::LLVM::DIFileAttr fileAttr,
66                       mlir::LLVM::DIScopeAttr scope);
67 };
68 
69 static uint32_t getLineFromLoc(mlir::Location loc) {
70   uint32_t line = 1;
71   if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(loc))
72     line = fileLoc.getLine();
73   return line;
74 }
75 
76 } // namespace
77 
78 void AddDebugInfoPass::handleDeclareOp(fir::cg::XDeclareOp declOp,
79                                        mlir::LLVM::DIFileAttr fileAttr,
80                                        mlir::LLVM::DIScopeAttr scopeAttr,
81                                        fir::DebugTypeGenerator &typeGen) {
82   mlir::MLIRContext *context = &getContext();
83   mlir::OpBuilder builder(context);
84   auto result = fir::NameUniquer::deconstruct(declOp.getUniqName());
85 
86   if (result.first != fir::NameUniquer::NameKind::VARIABLE)
87     return;
88 
89   // Only accept local variables.
90   if (result.second.procs.empty())
91     return;
92 
93   // FIXME: There may be cases where an argument is processed a bit before
94   // DeclareOp is generated. In that case, DeclareOp may point to an
95   // intermediate op and not to BlockArgument.
96   // Moreover, with MLIR inlining we cannot use the BlockArgument
97   // position to identify the original number of the dummy argument.
98   // If we want to keep running AddDebugInfoPass late, the dummy argument
99   // position in the argument list has to be expressed in FIR (e.g. as a
100   // constant attribute of [hl]fir.declare/fircg.ext_declare operation that has
101   // a dummy_scope operand).
102   unsigned argNo = 0;
103   if (fir::isDummyArgument(declOp.getMemref())) {
104     auto arg = llvm::cast<mlir::BlockArgument>(declOp.getMemref());
105     argNo = arg.getArgNumber() + 1;
106   }
107 
108   auto tyAttr = typeGen.convertType(fir::unwrapRefType(declOp.getType()),
109                                     fileAttr, scopeAttr, declOp.getLoc());
110 
111   auto localVarAttr = mlir::LLVM::DILocalVariableAttr::get(
112       context, scopeAttr, mlir::StringAttr::get(context, result.second.name),
113       fileAttr, getLineFromLoc(declOp.getLoc()), argNo, /* alignInBits*/ 0,
114       tyAttr);
115   declOp->setLoc(builder.getFusedLoc({declOp->getLoc()}, localVarAttr));
116 }
117 
118 // The `module` does not have a first class representation in the `FIR`. We
119 // extract information about it from the name of the identifiers and keep a
120 // map to avoid duplication.
121 mlir::LLVM::DIModuleAttr AddDebugInfoPass::getOrCreateModuleAttr(
122     const std::string &name, mlir::LLVM::DIFileAttr fileAttr,
123     mlir::LLVM::DIScopeAttr scope, unsigned line, bool decl) {
124   mlir::MLIRContext *context = &getContext();
125   mlir::LLVM::DIModuleAttr modAttr;
126   if (auto iter{moduleMap.find(name)}; iter != moduleMap.end()) {
127     modAttr = iter->getValue();
128   } else {
129     modAttr = mlir::LLVM::DIModuleAttr::get(
130         context, fileAttr, scope, mlir::StringAttr::get(context, name),
131         /* configMacros */ mlir::StringAttr(),
132         /* includePath */ mlir::StringAttr(),
133         /* apinotes */ mlir::StringAttr(), line, decl);
134     moduleMap[name] = modAttr;
135   }
136   return modAttr;
137 }
138 
139 void AddDebugInfoPass::handleGlobalOp(fir::GlobalOp globalOp,
140                                       mlir::LLVM::DIFileAttr fileAttr,
141                                       mlir::LLVM::DIScopeAttr scope) {
142   mlir::ModuleOp module = getOperation();
143   mlir::MLIRContext *context = &getContext();
144   fir::DebugTypeGenerator typeGen(module);
145   mlir::OpBuilder builder(context);
146 
147   std::pair result = fir::NameUniquer::deconstruct(globalOp.getSymName());
148   if (result.first != fir::NameUniquer::NameKind::VARIABLE)
149     return;
150 
151   unsigned line = getLineFromLoc(globalOp.getLoc());
152 
153   // DWARF5 says following about the fortran modules:
154   // A Fortran 90 module may also be represented by a module entry
155   // (but no declaration attribute is warranted because Fortran has no concept
156   // of a corresponding module body).
157   // But in practice, compilers use declaration attribute with a module in cases
158   // where module was defined in another source file (only being used in this
159   // one). The isInitialized() seems to provide the right information
160   // but inverted. It is true where module is actually defined but false where
161   // it is used.
162   // FIXME: Currently we don't have the line number on which a module was
163   // declared. We are using a best guess of line - 1 where line is the source
164   // line of the first member of the module that we encounter.
165 
166   if (result.second.modules.empty())
167     return;
168 
169   scope = getOrCreateModuleAttr(result.second.modules[0], fileAttr, scope,
170                                 line - 1, !globalOp.isInitialized());
171 
172   mlir::LLVM::DITypeAttr diType = typeGen.convertType(
173       globalOp.getType(), fileAttr, scope, globalOp.getLoc());
174   auto gvAttr = mlir::LLVM::DIGlobalVariableAttr::get(
175       context, scope, mlir::StringAttr::get(context, result.second.name),
176       mlir::StringAttr::get(context, globalOp.getName()), fileAttr, line,
177       diType, /*isLocalToUnit*/ false,
178       /*isDefinition*/ globalOp.isInitialized(), /* alignInBits*/ 0);
179   globalOp->setLoc(builder.getFusedLoc({globalOp->getLoc()}, gvAttr));
180 }
181 
182 void AddDebugInfoPass::runOnOperation() {
183   mlir::ModuleOp module = getOperation();
184   mlir::MLIRContext *context = &getContext();
185   mlir::OpBuilder builder(context);
186   llvm::StringRef fileName;
187   std::string filePath;
188   // We need 2 type of file paths here.
189   // 1. Name of the file as was presented to compiler. This can be absolute
190   // or relative to 2.
191   // 2. Current working directory
192   //
193   // We are also dealing with 2 different situations below. One is normal
194   // compilation where we will have a value in 'inputFilename' and we can
195   // obtain the current directory using 'current_path'.
196   // The 2nd case is when this pass is invoked directly from 'fir-opt' tool.
197   // In that case, 'inputFilename' may be empty. Location embedded in the
198   // module will be used to get file name and its directory.
199   if (inputFilename.empty()) {
200     if (auto fileLoc = mlir::dyn_cast<mlir::FileLineColLoc>(module.getLoc())) {
201       fileName = llvm::sys::path::filename(fileLoc.getFilename().getValue());
202       filePath = llvm::sys::path::parent_path(fileLoc.getFilename().getValue());
203     } else
204       fileName = "-";
205   } else {
206     fileName = inputFilename;
207     llvm::SmallString<256> cwd;
208     if (!llvm::sys::fs::current_path(cwd))
209       filePath = cwd.str();
210   }
211 
212   mlir::LLVM::DIFileAttr fileAttr =
213       mlir::LLVM::DIFileAttr::get(context, fileName, filePath);
214   mlir::StringAttr producer =
215       mlir::StringAttr::get(context, Fortran::common::getFlangFullVersion());
216   mlir::LLVM::DICompileUnitAttr cuAttr = mlir::LLVM::DICompileUnitAttr::get(
217       mlir::DistinctAttr::create(mlir::UnitAttr::get(context)),
218       llvm::dwarf::getLanguage("DW_LANG_Fortran95"), fileAttr, producer,
219       isOptimized, debugLevel);
220 
221   if (debugLevel == mlir::LLVM::DIEmissionKind::Full) {
222     // Process 'GlobalOp' only if full debug info is requested.
223     for (auto globalOp : module.getOps<fir::GlobalOp>())
224       handleGlobalOp(globalOp, fileAttr, cuAttr);
225   }
226 
227   module.walk([&](mlir::func::FuncOp funcOp) {
228     mlir::Location l = funcOp->getLoc();
229     // If fused location has already been created then nothing to do
230     // Otherwise, create a fused location.
231     if (mlir::dyn_cast<mlir::FusedLoc>(l))
232       return;
233 
234     unsigned int CC = (funcOp.getName() == fir::NameUniquer::doProgramEntry())
235                           ? llvm::dwarf::getCallingConvention("DW_CC_program")
236                           : llvm::dwarf::getCallingConvention("DW_CC_normal");
237 
238     if (auto funcLoc = mlir::dyn_cast<mlir::FileLineColLoc>(l)) {
239       fileName = llvm::sys::path::filename(funcLoc.getFilename().getValue());
240       filePath = llvm::sys::path::parent_path(funcLoc.getFilename().getValue());
241     }
242 
243     mlir::StringAttr fullName =
244         mlir::StringAttr::get(context, funcOp.getName());
245     auto result = fir::NameUniquer::deconstruct(funcOp.getName());
246     mlir::StringAttr funcName =
247         mlir::StringAttr::get(context, result.second.name);
248 
249     llvm::SmallVector<mlir::LLVM::DITypeAttr> types;
250     fir::DebugTypeGenerator typeGen(module);
251     for (auto resTy : funcOp.getResultTypes()) {
252       auto tyAttr =
253           typeGen.convertType(resTy, fileAttr, cuAttr, funcOp.getLoc());
254       types.push_back(tyAttr);
255     }
256     for (auto inTy : funcOp.getArgumentTypes()) {
257       auto tyAttr = typeGen.convertType(fir::unwrapRefType(inTy), fileAttr,
258                                         cuAttr, funcOp.getLoc());
259       types.push_back(tyAttr);
260     }
261 
262     mlir::LLVM::DISubroutineTypeAttr subTypeAttr =
263         mlir::LLVM::DISubroutineTypeAttr::get(context, CC, types);
264     mlir::LLVM::DIFileAttr funcFileAttr =
265         mlir::LLVM::DIFileAttr::get(context, fileName, filePath);
266 
267     // Only definitions need a distinct identifier and a compilation unit.
268     mlir::DistinctAttr id;
269     mlir::LLVM::DIScopeAttr Scope = fileAttr;
270     mlir::LLVM::DICompileUnitAttr compilationUnit;
271     mlir::LLVM::DISubprogramFlags subprogramFlags =
272         mlir::LLVM::DISubprogramFlags{};
273     if (isOptimized)
274       subprogramFlags = mlir::LLVM::DISubprogramFlags::Optimized;
275     if (!funcOp.isExternal()) {
276       id = mlir::DistinctAttr::create(mlir::UnitAttr::get(context));
277       compilationUnit = cuAttr;
278       subprogramFlags =
279           subprogramFlags | mlir::LLVM::DISubprogramFlags::Definition;
280     }
281     unsigned line = getLineFromLoc(l);
282     if (!result.second.modules.empty())
283       Scope = getOrCreateModuleAttr(result.second.modules[0], fileAttr, cuAttr,
284                                     line - 1, false);
285 
286     auto spAttr = mlir::LLVM::DISubprogramAttr::get(
287         context, id, compilationUnit, Scope, funcName, fullName, funcFileAttr,
288         line, line, subprogramFlags, subTypeAttr);
289     funcOp->setLoc(builder.getFusedLoc({funcOp->getLoc()}, spAttr));
290 
291     // Don't process variables if user asked for line tables only.
292     if (debugLevel == mlir::LLVM::DIEmissionKind::LineTablesOnly)
293       return;
294 
295     funcOp.walk([&](fir::cg::XDeclareOp declOp) {
296       handleDeclareOp(declOp, fileAttr, spAttr, typeGen);
297     });
298   });
299 }
300 
301 std::unique_ptr<mlir::Pass>
302 fir::createAddDebugInfoPass(fir::AddDebugInfoOptions options) {
303   return std::make_unique<AddDebugInfoPass>(options);
304 }
305