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