xref: /llvm-project/flang/lib/Optimizer/Dialect/Support/FIRContext.cpp (revision b07ef9e7cd6f5348df0a4f63e70a60491427ff64)
1 //===-- FIRContext.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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
14 #include "flang/Optimizer/Dialect/Support/KindMapping.h"
15 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
16 #include "mlir/IR/BuiltinAttributes.h"
17 #include "mlir/IR/BuiltinOps.h"
18 #include "llvm/TargetParser/Host.h"
19 
20 void fir::setTargetTriple(mlir::ModuleOp mod, llvm::StringRef triple) {
21   auto target = fir::determineTargetTriple(triple);
22   mod->setAttr(mlir::LLVM::LLVMDialect::getTargetTripleAttrName(),
23                mlir::StringAttr::get(mod.getContext(), target));
24 }
25 
26 llvm::Triple fir::getTargetTriple(mlir::ModuleOp mod) {
27   if (auto target = mod->getAttrOfType<mlir::StringAttr>(
28           mlir::LLVM::LLVMDialect::getTargetTripleAttrName()))
29     return llvm::Triple(target.getValue());
30   return llvm::Triple(llvm::sys::getDefaultTargetTriple());
31 }
32 
33 static constexpr const char *kindMapName = "fir.kindmap";
34 static constexpr const char *defKindName = "fir.defaultkind";
35 
36 void fir::setKindMapping(mlir::ModuleOp mod, fir::KindMapping &kindMap) {
37   auto *ctx = mod.getContext();
38   mod->setAttr(kindMapName, mlir::StringAttr::get(ctx, kindMap.mapToString()));
39   auto defs = kindMap.defaultsToString();
40   mod->setAttr(defKindName, mlir::StringAttr::get(ctx, defs));
41 }
42 
43 fir::KindMapping fir::getKindMapping(mlir::ModuleOp mod) {
44   auto *ctx = mod.getContext();
45   if (auto defs = mod->getAttrOfType<mlir::StringAttr>(defKindName)) {
46     auto defVals = fir::KindMapping::toDefaultKinds(defs.getValue());
47     if (auto maps = mod->getAttrOfType<mlir::StringAttr>(kindMapName))
48       return fir::KindMapping(ctx, maps.getValue(), defVals);
49     return fir::KindMapping(ctx, defVals);
50   }
51   return fir::KindMapping(ctx);
52 }
53 
54 std::string fir::determineTargetTriple(llvm::StringRef triple) {
55   // Treat "" or "default" as stand-ins for the default machine.
56   if (triple.empty() || triple == "default")
57     return llvm::sys::getDefaultTargetTriple();
58   // Treat "native" as stand-in for the host machine.
59   if (triple == "native")
60     return llvm::sys::getProcessTriple();
61   // TODO: normalize the triple?
62   return triple.str();
63 }
64