1 //===-- Optimizer/Support/DataLayout.cpp ----------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
23 void fir::support::setMLIRDataLayout(mlir::ModuleOp mlirModule
,
24 const llvm::DataLayout
&dl
) {
25 mlir::MLIRContext
*context
= mlirModule
.getContext();
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
);
33 void 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
);
43 if (!allowDefaultLayout
)
45 llvm::DataLayout
llvmDataLayout("");
46 fir::support::setMLIRDataLayout(mlirModule
, llvmDataLayout
);
49 std::optional
<mlir::DataLayout
>
50 fir::support::getOrSetDataLayout(mlir::ModuleOp mlirModule
,
51 bool allowDefaultLayout
) {
52 if (!mlirModule
.getDataLayoutSpec()) {
53 fir::support::setMLIRDataLayoutFromAttributes(mlirModule
,
55 if (!mlirModule
.getDataLayoutSpec()) {
59 return mlir::DataLayout(mlirModule
);