1//===-- Optimizer/Support/DataLayout.cpp ----------------------------------===//
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#include "flang/Optimizer/Support/DataLayout.h"
10#include "flang/Optimizer/Dialect/Support/FIRContext.h"
11#include "flang/Optimizer/Support/FatalError.h"
12#include "mlir/Dialect/DLTI/DLTI.h"
13#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
14#include "mlir/IR/BuiltinOps.h"
15#include "mlir/Interfaces/DataLayoutInterfaces.h"
16#include "mlir/Support/LLVM.h"
17#include "mlir/Target/LLVMIR/Import.h"
18#include "llvm/IR/DataLayout.h"
19#include "llvm/MC/TargetRegistry.h"
20#include "llvm/Support/TargetSelect.h"
21#include "llvm/Target/TargetMachine.h"
22
23void fir::support::setMLIRDataLayout(mlir::ModuleOp mlirModule,
24 const llvm::DataLayout &dl) {
25 mlir::MLIRContext *context = mlirModule.getContext();
26 mlirModule->setAttr(
27 mlir::LLVM::LLVMDialect::getDataLayoutAttrName(),
28 mlir::StringAttr::get(context, dl.getStringRepresentation()));
29 mlir::DataLayoutSpecInterface dlSpec = mlir::translateDataLayout(dl, context);
30 mlirModule->setAttr(mlir::DLTIDialect::kDataLayoutAttrName, dlSpec);
31}
32
33void fir::support::setMLIRDataLayoutFromAttributes(mlir::ModuleOp mlirModule,
34 bool allowDefaultLayout) {
35 if (mlirModule.getDataLayoutSpec())
36 return; // Already set.
37 if (auto dataLayoutString = mlirModule->getAttrOfType<mlir::StringAttr>(
38 mlir::LLVM::LLVMDialect::getDataLayoutAttrName())) {
39 llvm::DataLayout llvmDataLayout(dataLayoutString);
40 fir::support::setMLIRDataLayout(mlirModule, llvmDataLayout);
41 return;
42 }
43 if (!allowDefaultLayout)
44 return;
45 llvm::DataLayout llvmDataLayout("");
46 fir::support::setMLIRDataLayout(mlirModule, llvmDataLayout);
47}
48
49std::optional<mlir::DataLayout>
50fir::support::getOrSetDataLayout(mlir::ModuleOp mlirModule,
51 bool allowDefaultLayout) {
52 if (!mlirModule.getDataLayoutSpec()) {
53 fir::support::setMLIRDataLayoutFromAttributes(mlirModule,
54 allowDefaultLayout);
55 if (!mlirModule.getDataLayoutSpec()) {
56 return std::nullopt;
57 }
58 }
59 return mlir::DataLayout(mlirModule);
60}
61

source code of flang/lib/Optimizer/Support/DataLayout.cpp